blob: 497a3ca8f5432d0cc9b9be46a2d34dd9e04fa644 [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
106/// \brief Compare two source ranges to determine their relative position in
107/// 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
122/// \brief Determine if a source location falls within, before, or after a
123/// 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
137/// \brief Translate a Clang source range into a CIndex source range.
138///
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();
149 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
150 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000151 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000152 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
153 SM, LangOpts);
154 EndLoc = EndLoc.getLocWithOffset(Length);
155 }
156
Bill Wendlingeade3622013-01-23 08:25:41 +0000157 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000158 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000159 R.getBegin().getRawEncoding(),
160 EndLoc.getRawEncoding()
161 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000162 return Result;
163}
164
165//===----------------------------------------------------------------------===//
166// Cursor visitor.
167//===----------------------------------------------------------------------===//
168
169static SourceRange getRawCursorExtent(CXCursor C);
170static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
171
172
173RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
174 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
175}
176
177/// \brief Visit the given cursor and, if requested by the visitor,
178/// its children.
179///
180/// \param Cursor the cursor to visit.
181///
182/// \param CheckedRegionOfInterest if true, then the caller already checked
183/// that this cursor is within the region of interest.
184///
185/// \returns true if the visitation should be aborted, false if it
186/// should continue.
187bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
188 if (clang_isInvalid(Cursor.kind))
189 return false;
190
191 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000192 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000193 if (!D) {
194 assert(0 && "Invalid declaration cursor");
195 return true; // abort.
196 }
197
198 // Ignore implicit declarations, unless it's an objc method because
199 // currently we should report implicit methods for properties when indexing.
200 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
201 return false;
202 }
203
204 // If we have a range of interest, and this cursor doesn't intersect with it,
205 // we're done.
206 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
207 SourceRange Range = getRawCursorExtent(Cursor);
208 if (Range.isInvalid() || CompareRegionOfInterest(Range))
209 return false;
210 }
211
212 switch (Visitor(Cursor, Parent, ClientData)) {
213 case CXChildVisit_Break:
214 return true;
215
216 case CXChildVisit_Continue:
217 return false;
218
219 case CXChildVisit_Recurse: {
220 bool ret = VisitChildren(Cursor);
221 if (PostChildrenVisitor)
222 if (PostChildrenVisitor(Cursor, ClientData))
223 return true;
224 return ret;
225 }
226 }
227
228 llvm_unreachable("Invalid CXChildVisitResult!");
229}
230
231static bool visitPreprocessedEntitiesInRange(SourceRange R,
232 PreprocessingRecord &PPRec,
233 CursorVisitor &Visitor) {
234 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
235 FileID FID;
236
237 if (!Visitor.shouldVisitIncludedEntities()) {
238 // If the begin/end of the range lie in the same FileID, do the optimization
239 // where we skip preprocessed entities that do not come from the same FileID.
240 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
241 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
242 FID = FileID();
243 }
244
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000245 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
246 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000247 PPRec, FID);
248}
249
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000250bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000251 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000252 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000253
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000254 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000255 SourceManager &SM = Unit->getSourceManager();
256
257 std::pair<FileID, unsigned>
258 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
259 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
260
261 if (End.first != Begin.first) {
262 // If the end does not reside in the same file, try to recover by
263 // picking the end of the file of begin location.
264 End.first = Begin.first;
265 End.second = SM.getFileIDSize(Begin.first);
266 }
267
268 assert(Begin.first == End.first);
269 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000270 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000271
272 FileID File = Begin.first;
273 unsigned Offset = Begin.second;
274 unsigned Length = End.second - Begin.second;
275
276 if (!VisitDeclsOnly && !VisitPreprocessorLast)
277 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000278 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000279
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 if (visitDeclsFromFileRegion(File, Offset, Length))
281 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000282
283 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000284 return visitPreprocessedEntitiesInRegion();
285
286 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000287}
288
289static bool isInLexicalContext(Decl *D, DeclContext *DC) {
290 if (!DC)
291 return false;
292
293 for (DeclContext *DeclDC = D->getLexicalDeclContext();
294 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
295 if (DeclDC == DC)
296 return true;
297 }
298 return false;
299}
300
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000301bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000303 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000304 SourceManager &SM = Unit->getSourceManager();
305 SourceRange Range = RegionOfInterest;
306
307 SmallVector<Decl *, 16> Decls;
308 Unit->findFileRegionDecls(File, Offset, Length, Decls);
309
310 // If we didn't find any file level decls for the file, try looking at the
311 // file that it was included from.
312 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
313 bool Invalid = false;
314 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
315 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000316 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000317
318 SourceLocation Outer;
319 if (SLEntry.isFile())
320 Outer = SLEntry.getFile().getIncludeLoc();
321 else
322 Outer = SLEntry.getExpansion().getExpansionLocStart();
323 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000324 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000325
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000326 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000327 Length = 0;
328 Unit->findFileRegionDecls(File, Offset, Length, Decls);
329 }
330
331 assert(!Decls.empty());
332
333 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000334 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000335 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
336 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000337 Decl *D = *DIt;
338 if (D->getSourceRange().isInvalid())
339 continue;
340
341 if (isInLexicalContext(D, CurDC))
342 continue;
343
344 CurDC = dyn_cast<DeclContext>(D);
345
346 if (TagDecl *TD = dyn_cast<TagDecl>(D))
347 if (!TD->isFreeStanding())
348 continue;
349
350 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
351 if (CompRes == RangeBefore)
352 continue;
353 if (CompRes == RangeAfter)
354 break;
355
356 assert(CompRes == RangeOverlap);
357 VisitedAtLeastOnce = true;
358
359 if (isa<ObjCContainerDecl>(D)) {
360 FileDI_current = &DIt;
361 FileDE_current = DE;
362 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000363 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 }
365
366 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000367 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000368 }
369
370 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000371 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000372
373 // No Decls overlapped with the range. Move up the lexical context until there
374 // is a context that contains the range or we reach the translation unit
375 // level.
376 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
377 : (*(DIt-1))->getLexicalDeclContext();
378
379 while (DC && !DC->isTranslationUnit()) {
380 Decl *D = cast<Decl>(DC);
381 SourceRange CurDeclRange = D->getSourceRange();
382 if (CurDeclRange.isInvalid())
383 break;
384
385 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000386 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
387 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000388 }
389
390 DC = D->getLexicalDeclContext();
391 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000392
393 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000394}
395
396bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
397 if (!AU->getPreprocessor().getPreprocessingRecord())
398 return false;
399
400 PreprocessingRecord &PPRec
401 = *AU->getPreprocessor().getPreprocessingRecord();
402 SourceManager &SM = AU->getSourceManager();
403
404 if (RegionOfInterest.isValid()) {
405 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
406 SourceLocation B = MappedRange.getBegin();
407 SourceLocation E = MappedRange.getEnd();
408
409 if (AU->isInPreambleFileID(B)) {
410 if (SM.isLoadedSourceLocation(E))
411 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
412 PPRec, *this);
413
414 // Beginning of range lies in the preamble but it also extends beyond
415 // it into the main file. Split the range into 2 parts, one covering
416 // the preamble and another covering the main file. This allows subsequent
417 // calls to visitPreprocessedEntitiesInRange to accept a source range that
418 // lies in the same FileID, allowing it to skip preprocessed entities that
419 // do not come from the same FileID.
420 bool breaked =
421 visitPreprocessedEntitiesInRange(
422 SourceRange(B, AU->getEndOfPreambleFileID()),
423 PPRec, *this);
424 if (breaked) return true;
425 return visitPreprocessedEntitiesInRange(
426 SourceRange(AU->getStartOfMainFileID(), E),
427 PPRec, *this);
428 }
429
430 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
431 }
432
433 bool OnlyLocalDecls
434 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
435
436 if (OnlyLocalDecls)
437 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
438 PPRec);
439
440 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
441}
442
443template<typename InputIterator>
444bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
445 InputIterator Last,
446 PreprocessingRecord &PPRec,
447 FileID FID) {
448 for (; First != Last; ++First) {
449 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
450 continue;
451
452 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000453 if (!PPE)
454 continue;
455
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
457 if (Visit(MakeMacroExpansionCursor(ME, TU)))
458 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000459
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 continue;
461 }
Richard Smith66a81862015-05-04 02:25:31 +0000462
463 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000464 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
465 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000466
Guy Benyei11169dd2012-12-18 14:30:41 +0000467 continue;
468 }
469
470 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
471 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
472 return true;
473
474 continue;
475 }
476 }
477
478 return false;
479}
480
481/// \brief Visit the children of the given cursor.
482///
483/// \returns true if the visitation should be aborted, false if it
484/// should continue.
485bool CursorVisitor::VisitChildren(CXCursor Cursor) {
486 if (clang_isReference(Cursor.kind) &&
487 Cursor.kind != CXCursor_CXXBaseSpecifier) {
488 // By definition, references have no children.
489 return false;
490 }
491
492 // Set the Parent field to Cursor, then back to its old value once we're
493 // done.
494 SetParentRAII SetParent(Parent, StmtParent, Cursor);
495
496 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000497 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000498 if (!D)
499 return false;
500
501 return VisitAttributes(D) || Visit(D);
502 }
503
504 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000505 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000506 return Visit(S);
507
508 return false;
509 }
510
511 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000512 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000513 return Visit(E);
514
515 return false;
516 }
517
518 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000519 CXTranslationUnit TU = getCursorTU(Cursor);
520 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000521
522 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
523 for (unsigned I = 0; I != 2; ++I) {
524 if (VisitOrder[I]) {
525 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
526 RegionOfInterest.isInvalid()) {
527 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
528 TLEnd = CXXUnit->top_level_end();
529 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000530 const Optional<bool> V = handleDeclForVisitation(*TL);
531 if (!V.hasValue())
532 continue;
533 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000534 }
535 } else if (VisitDeclContext(
536 CXXUnit->getASTContext().getTranslationUnitDecl()))
537 return true;
538 continue;
539 }
540
541 // Walk the preprocessing record.
542 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
543 visitPreprocessedEntitiesInRegion();
544 }
545
546 return false;
547 }
548
549 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000550 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000551 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
552 return Visit(BaseTSInfo->getTypeLoc());
553 }
554 }
555 }
556
557 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000558 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000559 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000560 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000561 return Visit(cxcursor::MakeCursorObjCClassRef(
562 ObjT->getInterface(),
563 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 }
565
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000566 // If pointing inside a macro definition, check if the token is an identifier
567 // that was ever defined as a macro. In such a case, create a "pseudo" macro
568 // expansion cursor for that token.
569 SourceLocation BeginLoc = RegionOfInterest.getBegin();
570 if (Cursor.kind == CXCursor_MacroDefinition &&
571 BeginLoc == RegionOfInterest.getEnd()) {
572 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000573 const MacroInfo *MI =
574 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000575 if (MacroDefinitionRecord *MacroDef =
576 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000577 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
578 }
579
Guy Benyei11169dd2012-12-18 14:30:41 +0000580 // Nothing to visit at the moment.
581 return false;
582}
583
584bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
585 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
586 if (Visit(TSInfo->getTypeLoc()))
587 return true;
588
589 if (Stmt *Body = B->getBody())
590 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
591
592 return false;
593}
594
Ted Kremenek03325582013-02-21 01:29:01 +0000595Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000596 if (RegionOfInterest.isValid()) {
597 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
598 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000599 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000600
601 switch (CompareRegionOfInterest(Range)) {
602 case RangeBefore:
603 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000604 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000605
606 case RangeAfter:
607 // This declaration comes after the region of interest; we're done.
608 return false;
609
610 case RangeOverlap:
611 // This declaration overlaps the region of interest; visit it.
612 break;
613 }
614 }
615 return true;
616}
617
618bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
619 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
620
621 // FIXME: Eventually remove. This part of a hack to support proper
622 // iteration over all Decls contained lexically within an ObjC container.
623 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
624 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
625
626 for ( ; I != E; ++I) {
627 Decl *D = *I;
628 if (D->getLexicalDeclContext() != DC)
629 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000630 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000631 if (!V.hasValue())
632 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000633 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000634 }
635 return false;
636}
637
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000638Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
639 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
640
641 // Ignore synthesized ivars here, otherwise if we have something like:
642 // @synthesize prop = _prop;
643 // and '_prop' is not declared, we will encounter a '_prop' ivar before
644 // encountering the 'prop' synthesize declaration and we will think that
645 // we passed the region-of-interest.
646 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
647 if (ivarD->getSynthesize())
648 return None;
649 }
650
651 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
652 // declarations is a mismatch with the compiler semantics.
653 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
654 auto *ID = cast<ObjCInterfaceDecl>(D);
655 if (!ID->isThisDeclarationADefinition())
656 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
657
658 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
659 auto *PD = cast<ObjCProtocolDecl>(D);
660 if (!PD->isThisDeclarationADefinition())
661 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
662 }
663
664 const Optional<bool> V = shouldVisitCursor(Cursor);
665 if (!V.hasValue())
666 return None;
667 if (!V.getValue())
668 return false;
669 if (Visit(Cursor, true))
670 return true;
671 return None;
672}
673
Guy Benyei11169dd2012-12-18 14:30:41 +0000674bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
675 llvm_unreachable("Translation units are visited directly by Visit()");
676}
677
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000678bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
679 if (VisitTemplateParameters(D->getTemplateParameters()))
680 return true;
681
682 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
683}
684
Guy Benyei11169dd2012-12-18 14:30:41 +0000685bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
686 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
687 return Visit(TSInfo->getTypeLoc());
688
689 return false;
690}
691
692bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
693 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
694 return Visit(TSInfo->getTypeLoc());
695
696 return false;
697}
698
699bool CursorVisitor::VisitTagDecl(TagDecl *D) {
700 return VisitDeclContext(D);
701}
702
703bool CursorVisitor::VisitClassTemplateSpecializationDecl(
704 ClassTemplateSpecializationDecl *D) {
705 bool ShouldVisitBody = false;
706 switch (D->getSpecializationKind()) {
707 case TSK_Undeclared:
708 case TSK_ImplicitInstantiation:
709 // Nothing to visit
710 return false;
711
712 case TSK_ExplicitInstantiationDeclaration:
713 case TSK_ExplicitInstantiationDefinition:
714 break;
715
716 case TSK_ExplicitSpecialization:
717 ShouldVisitBody = true;
718 break;
719 }
720
721 // Visit the template arguments used in the specialization.
722 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
723 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000724 if (TemplateSpecializationTypeLoc TSTLoc =
725 TL.getAs<TemplateSpecializationTypeLoc>()) {
726 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
727 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 return true;
729 }
730 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000731
732 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000733}
734
735bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
736 ClassTemplatePartialSpecializationDecl *D) {
737 // FIXME: Visit the "outer" template parameter lists on the TagDecl
738 // before visiting these template parameters.
739 if (VisitTemplateParameters(D->getTemplateParameters()))
740 return true;
741
742 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000743 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
744 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
745 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000746 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
747 return true;
748
749 return VisitCXXRecordDecl(D);
750}
751
752bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
753 // Visit the default argument.
754 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
755 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
756 if (Visit(DefArg->getTypeLoc()))
757 return true;
758
759 return false;
760}
761
762bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
763 if (Expr *Init = D->getInitExpr())
764 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
765 return false;
766}
767
768bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000769 unsigned NumParamList = DD->getNumTemplateParameterLists();
770 for (unsigned i = 0; i < NumParamList; i++) {
771 TemplateParameterList* Params = DD->getTemplateParameterList(i);
772 if (VisitTemplateParameters(Params))
773 return true;
774 }
775
Guy Benyei11169dd2012-12-18 14:30:41 +0000776 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
777 if (Visit(TSInfo->getTypeLoc()))
778 return true;
779
780 // Visit the nested-name-specifier, if present.
781 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
782 if (VisitNestedNameSpecifierLoc(QualifierLoc))
783 return true;
784
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000785 return false;
786}
787
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000788static bool HasTrailingReturnType(FunctionDecl *ND) {
789 const QualType Ty = ND->getType();
790 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
791 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
792 return FT->hasTrailingReturn();
793 }
794
795 return false;
796}
797
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000798/// \brief Compare two base or member initializers based on their source order.
799static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
800 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000801 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
802}
803
Guy Benyei11169dd2012-12-18 14:30:41 +0000804bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000805 unsigned NumParamList = ND->getNumTemplateParameterLists();
806 for (unsigned i = 0; i < NumParamList; i++) {
807 TemplateParameterList* Params = ND->getTemplateParameterList(i);
808 if (VisitTemplateParameters(Params))
809 return true;
810 }
811
Guy Benyei11169dd2012-12-18 14:30:41 +0000812 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
813 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000814 // written. This requires a bit of work.
815 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
816 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000817 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000818
819 // If we have a function declared directly (without the use of a typedef),
820 // visit just the return type. Otherwise, just visit the function's type
821 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000822 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
823 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000824 (!FTL && Visit(TL)))
825 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000826
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000827 // Visit the nested-name-specifier, if present.
828 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
829 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 return true;
831
832 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000833 if (!isa<CXXDestructorDecl>(ND))
834 if (VisitDeclarationNameInfo(ND->getNameInfo()))
835 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000836
837 // FIXME: Visit explicitly-specified template arguments!
838
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000839 // Visit the function parameters, if we have a function type.
840 if (FTL && VisitFunctionTypeLoc(FTL, true))
841 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000842
843 // Visit the function's trailing return type.
844 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
845 return true;
846
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000847 // FIXME: Attributes?
848 }
849
Guy Benyei11169dd2012-12-18 14:30:41 +0000850 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
851 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
852 // Find the initializers that were written in the source.
853 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000854 for (auto *I : Constructor->inits()) {
855 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000856 continue;
857
Aaron Ballman0ad78302014-03-13 17:34:31 +0000858 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000859 }
860
861 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000862 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
863 &CompareCXXCtorInitializers);
864
Guy Benyei11169dd2012-12-18 14:30:41 +0000865 // Visit the initializers in source order
866 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
867 CXXCtorInitializer *Init = WrittenInits[I];
868 if (Init->isAnyMemberInitializer()) {
869 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
870 Init->getMemberLocation(), TU)))
871 return true;
872 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
873 if (Visit(TInfo->getTypeLoc()))
874 return true;
875 }
876
877 // Visit the initializer value.
878 if (Expr *Initializer = Init->getInit())
879 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
880 return true;
881 }
882 }
883
884 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
885 return true;
886 }
887
888 return false;
889}
890
891bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
892 if (VisitDeclaratorDecl(D))
893 return true;
894
895 if (Expr *BitWidth = D->getBitWidth())
896 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
897
Benjamin Kramer99f97592017-11-15 12:20:41 +0000898 if (Expr *Init = D->getInClassInitializer())
899 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
900
Guy Benyei11169dd2012-12-18 14:30:41 +0000901 return false;
902}
903
904bool CursorVisitor::VisitVarDecl(VarDecl *D) {
905 if (VisitDeclaratorDecl(D))
906 return true;
907
908 if (Expr *Init = D->getInit())
909 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
910
911 return false;
912}
913
914bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
915 if (VisitDeclaratorDecl(D))
916 return true;
917
918 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
919 if (Expr *DefArg = D->getDefaultArgument())
920 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
921
922 return false;
923}
924
925bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
926 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
927 // before visiting these template parameters.
928 if (VisitTemplateParameters(D->getTemplateParameters()))
929 return true;
930
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000931 auto* FD = D->getTemplatedDecl();
932 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000933}
934
935bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
936 // FIXME: Visit the "outer" template parameter lists on the TagDecl
937 // before visiting these template parameters.
938 if (VisitTemplateParameters(D->getTemplateParameters()))
939 return true;
940
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000941 auto* CD = D->getTemplatedDecl();
942 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000943}
944
945bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
946 if (VisitTemplateParameters(D->getTemplateParameters()))
947 return true;
948
949 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
950 VisitTemplateArgumentLoc(D->getDefaultArgument()))
951 return true;
952
953 return false;
954}
955
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000956bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
957 // Visit the bound, if it's explicit.
958 if (D->hasExplicitBound()) {
959 if (auto TInfo = D->getTypeSourceInfo()) {
960 if (Visit(TInfo->getTypeLoc()))
961 return true;
962 }
963 }
964
965 return false;
966}
967
Guy Benyei11169dd2012-12-18 14:30:41 +0000968bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000969 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 if (Visit(TSInfo->getTypeLoc()))
971 return true;
972
David Majnemer59f77922016-06-24 04:05:48 +0000973 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000974 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 return true;
976 }
977
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000978 return ND->isThisDeclarationADefinition() &&
979 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000980}
981
982template <typename DeclIt>
983static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
984 SourceManager &SM, SourceLocation EndLoc,
985 SmallVectorImpl<Decl *> &Decls) {
986 DeclIt next = *DI_current;
987 while (++next != DE_current) {
988 Decl *D_next = *next;
989 if (!D_next)
990 break;
991 SourceLocation L = D_next->getLocStart();
992 if (!L.isValid())
993 break;
994 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
995 *DI_current = next;
996 Decls.push_back(D_next);
997 continue;
998 }
999 break;
1000 }
1001}
1002
Guy Benyei11169dd2012-12-18 14:30:41 +00001003bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1004 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1005 // an @implementation can lexically contain Decls that are not properly
1006 // nested in the AST. When we identify such cases, we need to retrofit
1007 // this nesting here.
1008 if (!DI_current && !FileDI_current)
1009 return VisitDeclContext(D);
1010
1011 // Scan the Decls that immediately come after the container
1012 // in the current DeclContext. If any fall within the
1013 // container's lexical region, stash them into a vector
1014 // for later processing.
1015 SmallVector<Decl *, 24> DeclsInContainer;
1016 SourceLocation EndLoc = D->getSourceRange().getEnd();
1017 SourceManager &SM = AU->getSourceManager();
1018 if (EndLoc.isValid()) {
1019 if (DI_current) {
1020 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1021 DeclsInContainer);
1022 } else {
1023 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1024 DeclsInContainer);
1025 }
1026 }
1027
1028 // The common case.
1029 if (DeclsInContainer.empty())
1030 return VisitDeclContext(D);
1031
1032 // Get all the Decls in the DeclContext, and sort them with the
1033 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001034 for (auto *SubDecl : D->decls()) {
1035 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1036 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001038 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 }
1040
1041 // Now sort the Decls so that they appear in lexical order.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001042 llvm::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1043 [&SM](Decl *A, Decl *B) {
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001044 SourceLocation L_A = A->getLocStart();
1045 SourceLocation L_B = B->getLocStart();
Mandeep Singh Grangfa51e1d2017-11-29 20:55:13 +00001046 return L_A != L_B ?
1047 SM.isBeforeInTranslationUnit(L_A, L_B) :
1048 SM.isBeforeInTranslationUnit(A->getLocEnd(), B->getLocEnd());
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001049 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001050
1051 // Now visit the decls.
1052 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1053 E = DeclsInContainer.end(); I != E; ++I) {
1054 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001055 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001056 if (!V.hasValue())
1057 continue;
1058 if (!V.getValue())
1059 return false;
1060 if (Visit(Cursor, true))
1061 return true;
1062 }
1063 return false;
1064}
1065
1066bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1067 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1068 TU)))
1069 return true;
1070
Douglas Gregore9d95f12015-07-07 03:57:35 +00001071 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1072 return true;
1073
Guy Benyei11169dd2012-12-18 14:30:41 +00001074 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1075 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1076 E = ND->protocol_end(); I != E; ++I, ++PL)
1077 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1078 return true;
1079
1080 return VisitObjCContainerDecl(ND);
1081}
1082
1083bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1084 if (!PID->isThisDeclarationADefinition())
1085 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1086
1087 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1088 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1089 E = PID->protocol_end(); I != E; ++I, ++PL)
1090 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1091 return true;
1092
1093 return VisitObjCContainerDecl(PID);
1094}
1095
1096bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1097 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1098 return true;
1099
1100 // FIXME: This implements a workaround with @property declarations also being
1101 // installed in the DeclContext for the @interface. Eventually this code
1102 // should be removed.
1103 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1104 if (!CDecl || !CDecl->IsClassExtension())
1105 return false;
1106
1107 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1108 if (!ID)
1109 return false;
1110
1111 IdentifierInfo *PropertyId = PD->getIdentifier();
1112 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001113 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1114 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001115
1116 if (!prevDecl)
1117 return false;
1118
1119 // Visit synthesized methods since they will be skipped when visiting
1120 // the @interface.
1121 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1122 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1123 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1124 return true;
1125
1126 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1127 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1128 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1129 return true;
1130
1131 return false;
1132}
1133
Douglas Gregore9d95f12015-07-07 03:57:35 +00001134bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1135 if (!typeParamList)
1136 return false;
1137
1138 for (auto *typeParam : *typeParamList) {
1139 // Visit the type parameter.
1140 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1141 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001142 }
1143
1144 return false;
1145}
1146
Guy Benyei11169dd2012-12-18 14:30:41 +00001147bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1148 if (!D->isThisDeclarationADefinition()) {
1149 // Forward declaration is treated like a reference.
1150 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1151 }
1152
Douglas Gregore9d95f12015-07-07 03:57:35 +00001153 // Objective-C type parameters.
1154 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1155 return true;
1156
Guy Benyei11169dd2012-12-18 14:30:41 +00001157 // Issue callbacks for super class.
1158 if (D->getSuperClass() &&
1159 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1160 D->getSuperClassLoc(),
1161 TU)))
1162 return true;
1163
Douglas Gregore9d95f12015-07-07 03:57:35 +00001164 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1165 if (Visit(SuperClassTInfo->getTypeLoc()))
1166 return true;
1167
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1169 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1170 E = D->protocol_end(); I != E; ++I, ++PL)
1171 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1172 return true;
1173
1174 return VisitObjCContainerDecl(D);
1175}
1176
1177bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1178 return VisitObjCContainerDecl(D);
1179}
1180
1181bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1182 // 'ID' could be null when dealing with invalid code.
1183 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1184 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1185 return true;
1186
1187 return VisitObjCImplDecl(D);
1188}
1189
1190bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1191#if 0
1192 // Issue callbacks for super class.
1193 // FIXME: No source location information!
1194 if (D->getSuperClass() &&
1195 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1196 D->getSuperClassLoc(),
1197 TU)))
1198 return true;
1199#endif
1200
1201 return VisitObjCImplDecl(D);
1202}
1203
1204bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1205 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1206 if (PD->isIvarNameSpecified())
1207 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1208
1209 return false;
1210}
1211
1212bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1213 return VisitDeclContext(D);
1214}
1215
1216bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1217 // Visit nested-name-specifier.
1218 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1219 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1220 return true;
1221
1222 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1223 D->getTargetNameLoc(), TU));
1224}
1225
1226bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1227 // Visit nested-name-specifier.
1228 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1229 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1230 return true;
1231 }
1232
1233 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1234 return true;
1235
1236 return VisitDeclarationNameInfo(D->getNameInfo());
1237}
1238
1239bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1240 // Visit nested-name-specifier.
1241 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1242 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1243 return true;
1244
1245 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1246 D->getIdentLocation(), TU));
1247}
1248
1249bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1250 // Visit nested-name-specifier.
1251 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1252 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1253 return true;
1254 }
1255
1256 return VisitDeclarationNameInfo(D->getNameInfo());
1257}
1258
1259bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1260 UnresolvedUsingTypenameDecl *D) {
1261 // Visit nested-name-specifier.
1262 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1263 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1264 return true;
1265
1266 return false;
1267}
1268
Olivier Goffart81978012016-06-09 16:15:55 +00001269bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1270 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1271 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001272 if (StringLiteral *Message = D->getMessage())
1273 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1274 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001275 return false;
1276}
1277
Olivier Goffartd211c642016-11-04 06:29:27 +00001278bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1279 if (NamedDecl *FriendD = D->getFriendDecl()) {
1280 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1281 return true;
1282 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1283 if (Visit(TI->getTypeLoc()))
1284 return true;
1285 }
1286 return false;
1287}
1288
Guy Benyei11169dd2012-12-18 14:30:41 +00001289bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1290 switch (Name.getName().getNameKind()) {
1291 case clang::DeclarationName::Identifier:
1292 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001293 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 case clang::DeclarationName::CXXOperatorName:
1295 case clang::DeclarationName::CXXUsingDirective:
1296 return false;
Richard Smith35845152017-02-07 01:37:30 +00001297
Guy Benyei11169dd2012-12-18 14:30:41 +00001298 case clang::DeclarationName::CXXConstructorName:
1299 case clang::DeclarationName::CXXDestructorName:
1300 case clang::DeclarationName::CXXConversionFunctionName:
1301 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1302 return Visit(TSInfo->getTypeLoc());
1303 return false;
1304
1305 case clang::DeclarationName::ObjCZeroArgSelector:
1306 case clang::DeclarationName::ObjCOneArgSelector:
1307 case clang::DeclarationName::ObjCMultiArgSelector:
1308 // FIXME: Per-identifier location info?
1309 return false;
1310 }
1311
1312 llvm_unreachable("Invalid DeclarationName::Kind!");
1313}
1314
1315bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1316 SourceRange Range) {
1317 // FIXME: This whole routine is a hack to work around the lack of proper
1318 // source information in nested-name-specifiers (PR5791). Since we do have
1319 // a beginning source location, we can visit the first component of the
1320 // nested-name-specifier, if it's a single-token component.
1321 if (!NNS)
1322 return false;
1323
1324 // Get the first component in the nested-name-specifier.
1325 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1326 NNS = Prefix;
1327
1328 switch (NNS->getKind()) {
1329 case NestedNameSpecifier::Namespace:
1330 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1331 TU));
1332
1333 case NestedNameSpecifier::NamespaceAlias:
1334 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1335 Range.getBegin(), TU));
1336
1337 case NestedNameSpecifier::TypeSpec: {
1338 // If the type has a form where we know that the beginning of the source
1339 // range matches up with a reference cursor. Visit the appropriate reference
1340 // cursor.
1341 const Type *T = NNS->getAsType();
1342 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1343 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1344 if (const TagType *Tag = dyn_cast<TagType>(T))
1345 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1346 if (const TemplateSpecializationType *TST
1347 = dyn_cast<TemplateSpecializationType>(T))
1348 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1349 break;
1350 }
1351
1352 case NestedNameSpecifier::TypeSpecWithTemplate:
1353 case NestedNameSpecifier::Global:
1354 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001355 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001356 break;
1357 }
1358
1359 return false;
1360}
1361
1362bool
1363CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1364 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1365 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1366 Qualifiers.push_back(Qualifier);
1367
1368 while (!Qualifiers.empty()) {
1369 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1370 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1371 switch (NNS->getKind()) {
1372 case NestedNameSpecifier::Namespace:
1373 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1374 Q.getLocalBeginLoc(),
1375 TU)))
1376 return true;
1377
1378 break;
1379
1380 case NestedNameSpecifier::NamespaceAlias:
1381 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1382 Q.getLocalBeginLoc(),
1383 TU)))
1384 return true;
1385
1386 break;
1387
1388 case NestedNameSpecifier::TypeSpec:
1389 case NestedNameSpecifier::TypeSpecWithTemplate:
1390 if (Visit(Q.getTypeLoc()))
1391 return true;
1392
1393 break;
1394
1395 case NestedNameSpecifier::Global:
1396 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001397 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001398 break;
1399 }
1400 }
1401
1402 return false;
1403}
1404
1405bool CursorVisitor::VisitTemplateParameters(
1406 const TemplateParameterList *Params) {
1407 if (!Params)
1408 return false;
1409
1410 for (TemplateParameterList::const_iterator P = Params->begin(),
1411 PEnd = Params->end();
1412 P != PEnd; ++P) {
1413 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1414 return true;
1415 }
1416
1417 return false;
1418}
1419
1420bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1421 switch (Name.getKind()) {
1422 case TemplateName::Template:
1423 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1424
1425 case TemplateName::OverloadedTemplate:
1426 // Visit the overloaded template set.
1427 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1428 return true;
1429
1430 return false;
1431
1432 case TemplateName::DependentTemplate:
1433 // FIXME: Visit nested-name-specifier.
1434 return false;
1435
1436 case TemplateName::QualifiedTemplate:
1437 // FIXME: Visit nested-name-specifier.
1438 return Visit(MakeCursorTemplateRef(
1439 Name.getAsQualifiedTemplateName()->getDecl(),
1440 Loc, TU));
1441
1442 case TemplateName::SubstTemplateTemplateParm:
1443 return Visit(MakeCursorTemplateRef(
1444 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1445 Loc, TU));
1446
1447 case TemplateName::SubstTemplateTemplateParmPack:
1448 return Visit(MakeCursorTemplateRef(
1449 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1450 Loc, TU));
1451 }
1452
1453 llvm_unreachable("Invalid TemplateName::Kind!");
1454}
1455
1456bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1457 switch (TAL.getArgument().getKind()) {
1458 case TemplateArgument::Null:
1459 case TemplateArgument::Integral:
1460 case TemplateArgument::Pack:
1461 return false;
1462
1463 case TemplateArgument::Type:
1464 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1465 return Visit(TSInfo->getTypeLoc());
1466 return false;
1467
1468 case TemplateArgument::Declaration:
1469 if (Expr *E = TAL.getSourceDeclExpression())
1470 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1471 return false;
1472
1473 case TemplateArgument::NullPtr:
1474 if (Expr *E = TAL.getSourceNullPtrExpression())
1475 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1476 return false;
1477
1478 case TemplateArgument::Expression:
1479 if (Expr *E = TAL.getSourceExpression())
1480 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1481 return false;
1482
1483 case TemplateArgument::Template:
1484 case TemplateArgument::TemplateExpansion:
1485 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1486 return true;
1487
1488 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1489 TAL.getTemplateNameLoc());
1490 }
1491
1492 llvm_unreachable("Invalid TemplateArgument::Kind!");
1493}
1494
1495bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1496 return VisitDeclContext(D);
1497}
1498
1499bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1500 return Visit(TL.getUnqualifiedLoc());
1501}
1502
1503bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1504 ASTContext &Context = AU->getASTContext();
1505
1506 // Some builtin types (such as Objective-C's "id", "sel", and
1507 // "Class") have associated declarations. Create cursors for those.
1508 QualType VisitType;
1509 switch (TL.getTypePtr()->getKind()) {
1510
1511 case BuiltinType::Void:
1512 case BuiltinType::NullPtr:
1513 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001514#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1515 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001516#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001517 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001518 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001519 case BuiltinType::OCLClkEvent:
1520 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001521 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001522#define BUILTIN_TYPE(Id, SingletonId)
1523#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1524#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1525#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1526#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1527#include "clang/AST/BuiltinTypes.def"
1528 break;
1529
1530 case BuiltinType::ObjCId:
1531 VisitType = Context.getObjCIdType();
1532 break;
1533
1534 case BuiltinType::ObjCClass:
1535 VisitType = Context.getObjCClassType();
1536 break;
1537
1538 case BuiltinType::ObjCSel:
1539 VisitType = Context.getObjCSelType();
1540 break;
1541 }
1542
1543 if (!VisitType.isNull()) {
1544 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1545 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1546 TU));
1547 }
1548
1549 return false;
1550}
1551
1552bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1553 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1554}
1555
1556bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1557 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1558}
1559
1560bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1561 if (TL.isDefinition())
1562 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1563
1564 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1565}
1566
1567bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1568 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1569}
1570
1571bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001572 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001573}
1574
Manman Rene6be26c2016-09-13 17:25:08 +00001575bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1576 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1577 return true;
1578 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1579 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1580 TU)))
1581 return true;
1582 }
1583
1584 return false;
1585}
1586
Guy Benyei11169dd2012-12-18 14:30:41 +00001587bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1588 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1589 return true;
1590
Douglas Gregore9d95f12015-07-07 03:57:35 +00001591 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1592 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1593 return true;
1594 }
1595
Guy Benyei11169dd2012-12-18 14:30:41 +00001596 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1597 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1598 TU)))
1599 return true;
1600 }
1601
1602 return false;
1603}
1604
1605bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1606 return Visit(TL.getPointeeLoc());
1607}
1608
1609bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1610 return Visit(TL.getInnerLoc());
1611}
1612
1613bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1614 return Visit(TL.getPointeeLoc());
1615}
1616
1617bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1618 return Visit(TL.getPointeeLoc());
1619}
1620
1621bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1622 return Visit(TL.getPointeeLoc());
1623}
1624
1625bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1626 return Visit(TL.getPointeeLoc());
1627}
1628
1629bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1630 return Visit(TL.getPointeeLoc());
1631}
1632
1633bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1634 return Visit(TL.getModifiedLoc());
1635}
1636
1637bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1638 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001639 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001640 return true;
1641
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001642 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1643 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1645 return true;
1646
1647 return false;
1648}
1649
1650bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1651 if (Visit(TL.getElementLoc()))
1652 return true;
1653
1654 if (Expr *Size = TL.getSizeExpr())
1655 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1656
1657 return false;
1658}
1659
Reid Kleckner8a365022013-06-24 17:51:48 +00001660bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1661 return Visit(TL.getOriginalLoc());
1662}
1663
Reid Kleckner0503a872013-12-05 01:23:43 +00001664bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1665 return Visit(TL.getOriginalLoc());
1666}
1667
Richard Smith600b5262017-01-26 20:40:47 +00001668bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1669 DeducedTemplateSpecializationTypeLoc TL) {
1670 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1671 TL.getTemplateNameLoc()))
1672 return true;
1673
1674 return false;
1675}
1676
Guy Benyei11169dd2012-12-18 14:30:41 +00001677bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1678 TemplateSpecializationTypeLoc TL) {
1679 // Visit the template name.
1680 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1681 TL.getTemplateNameLoc()))
1682 return true;
1683
1684 // Visit the template arguments.
1685 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1686 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1687 return true;
1688
1689 return false;
1690}
1691
1692bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1693 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1694}
1695
1696bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1697 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1698 return Visit(TSInfo->getTypeLoc());
1699
1700 return false;
1701}
1702
1703bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1704 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1705 return Visit(TSInfo->getTypeLoc());
1706
1707 return false;
1708}
1709
1710bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001711 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001712}
1713
1714bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1715 DependentTemplateSpecializationTypeLoc TL) {
1716 // Visit the nested-name-specifier, if there is one.
1717 if (TL.getQualifierLoc() &&
1718 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1719 return true;
1720
1721 // Visit the template arguments.
1722 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1723 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1724 return true;
1725
1726 return false;
1727}
1728
1729bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1730 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1731 return true;
1732
1733 return Visit(TL.getNamedTypeLoc());
1734}
1735
1736bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1737 return Visit(TL.getPatternLoc());
1738}
1739
1740bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1741 if (Expr *E = TL.getUnderlyingExpr())
1742 return Visit(MakeCXCursor(E, StmtParent, TU));
1743
1744 return false;
1745}
1746
1747bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1748 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1749}
1750
1751bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1752 return Visit(TL.getValueLoc());
1753}
1754
Xiuli Pan9c14e282016-01-09 12:53:17 +00001755bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1756 return Visit(TL.getValueLoc());
1757}
1758
Guy Benyei11169dd2012-12-18 14:30:41 +00001759#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1760bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1761 return Visit##PARENT##Loc(TL); \
1762}
1763
1764DEFAULT_TYPELOC_IMPL(Complex, Type)
1765DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1766DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1767DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1768DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001769DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001770DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1771DEFAULT_TYPELOC_IMPL(Vector, Type)
1772DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1773DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1774DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1775DEFAULT_TYPELOC_IMPL(Record, TagType)
1776DEFAULT_TYPELOC_IMPL(Enum, TagType)
1777DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1778DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1779DEFAULT_TYPELOC_IMPL(Auto, Type)
1780
1781bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1782 // Visit the nested-name-specifier, if present.
1783 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1784 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1785 return true;
1786
1787 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001788 for (const auto &I : D->bases()) {
1789 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001790 return true;
1791 }
1792 }
1793
1794 return VisitTagDecl(D);
1795}
1796
1797bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001798 for (const auto *I : D->attrs())
Erik Verbruggenc068e902018-04-24 08:39:46 +00001799 if (!I->isImplicit() && Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001800 return true;
1801
1802 return false;
1803}
1804
1805//===----------------------------------------------------------------------===//
1806// Data-recursive visitor methods.
1807//===----------------------------------------------------------------------===//
1808
1809namespace {
1810#define DEF_JOB(NAME, DATA, KIND)\
1811class NAME : public VisitorJob {\
1812public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001813 NAME(const DATA *d, CXCursor parent) : \
1814 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001815 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001816 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001817};
1818
1819DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1820DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1821DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1822DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001823DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1824DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1825DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1826#undef DEF_JOB
1827
James Y Knight04ec5bf2015-12-24 02:59:37 +00001828class ExplicitTemplateArgsVisit : public VisitorJob {
1829public:
1830 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1831 const TemplateArgumentLoc *End, CXCursor parent)
1832 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1833 End) {}
1834 static bool classof(const VisitorJob *VJ) {
1835 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1836 }
1837 const TemplateArgumentLoc *begin() const {
1838 return static_cast<const TemplateArgumentLoc *>(data[0]);
1839 }
1840 const TemplateArgumentLoc *end() {
1841 return static_cast<const TemplateArgumentLoc *>(data[1]);
1842 }
1843};
Guy Benyei11169dd2012-12-18 14:30:41 +00001844class DeclVisit : public VisitorJob {
1845public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001846 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001847 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001848 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 static bool classof(const VisitorJob *VJ) {
1850 return VJ->getKind() == DeclVisitKind;
1851 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001852 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001853 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001854};
1855class TypeLocVisit : public VisitorJob {
1856public:
1857 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1858 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1859 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1860
1861 static bool classof(const VisitorJob *VJ) {
1862 return VJ->getKind() == TypeLocVisitKind;
1863 }
1864
1865 TypeLoc get() const {
1866 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001867 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001868 }
1869};
1870
1871class LabelRefVisit : public VisitorJob {
1872public:
1873 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1874 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1875 labelLoc.getPtrEncoding()) {}
1876
1877 static bool classof(const VisitorJob *VJ) {
1878 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1879 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001880 const LabelDecl *get() const {
1881 return static_cast<const LabelDecl *>(data[0]);
1882 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001883 SourceLocation getLoc() const {
1884 return SourceLocation::getFromPtrEncoding(data[1]); }
1885};
1886
1887class NestedNameSpecifierLocVisit : public VisitorJob {
1888public:
1889 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1890 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1891 Qualifier.getNestedNameSpecifier(),
1892 Qualifier.getOpaqueData()) { }
1893
1894 static bool classof(const VisitorJob *VJ) {
1895 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1896 }
1897
1898 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001899 return NestedNameSpecifierLoc(
1900 const_cast<NestedNameSpecifier *>(
1901 static_cast<const NestedNameSpecifier *>(data[0])),
1902 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001903 }
1904};
1905
1906class DeclarationNameInfoVisit : public VisitorJob {
1907public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001908 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001909 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 static bool classof(const VisitorJob *VJ) {
1911 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1912 }
1913 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001914 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 switch (S->getStmtClass()) {
1916 default:
1917 llvm_unreachable("Unhandled Stmt");
1918 case clang::Stmt::MSDependentExistsStmtClass:
1919 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1920 case Stmt::CXXDependentScopeMemberExprClass:
1921 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1922 case Stmt::DependentScopeDeclRefExprClass:
1923 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001924 case Stmt::OMPCriticalDirectiveClass:
1925 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001926 }
1927 }
1928};
1929class MemberRefVisit : public VisitorJob {
1930public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001931 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001932 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1933 L.getPtrEncoding()) {}
1934 static bool classof(const VisitorJob *VJ) {
1935 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1936 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001937 const FieldDecl *get() const {
1938 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001939 }
1940 SourceLocation getLoc() const {
1941 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1942 }
1943};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001944class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001945 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001946 VisitorWorkList &WL;
1947 CXCursor Parent;
1948public:
1949 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1950 : WL(wl), Parent(parent) {}
1951
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001952 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1953 void VisitBlockExpr(const BlockExpr *B);
1954 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1955 void VisitCompoundStmt(const CompoundStmt *S);
1956 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1957 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1958 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1959 void VisitCXXNewExpr(const CXXNewExpr *E);
1960 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1961 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1962 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1963 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1964 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1965 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1966 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1967 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001968 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001969 void VisitDeclRefExpr(const DeclRefExpr *D);
1970 void VisitDeclStmt(const DeclStmt *S);
1971 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1972 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1973 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1974 void VisitForStmt(const ForStmt *FS);
1975 void VisitGotoStmt(const GotoStmt *GS);
1976 void VisitIfStmt(const IfStmt *If);
1977 void VisitInitListExpr(const InitListExpr *IE);
1978 void VisitMemberExpr(const MemberExpr *M);
1979 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1980 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1981 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1982 void VisitOverloadExpr(const OverloadExpr *E);
1983 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1984 void VisitStmt(const Stmt *S);
1985 void VisitSwitchStmt(const SwitchStmt *S);
1986 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001987 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1988 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1989 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1990 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1991 void VisitVAArgExpr(const VAArgExpr *E);
1992 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1993 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1994 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1995 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001996 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001997 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001998 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001999 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002000 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002001 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002002 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002003 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002004 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002005 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002006 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002007 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002008 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002009 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002010 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002011 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002012 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002013 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002014 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002015 void
2016 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002017 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002018 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002019 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002020 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002021 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002022 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002023 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002024 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002025 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002026 void
2027 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002028 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002029 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002030 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002031 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002032 void VisitOMPDistributeParallelForDirective(
2033 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002034 void VisitOMPDistributeParallelForSimdDirective(
2035 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002036 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002037 void VisitOMPTargetParallelForSimdDirective(
2038 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002039 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002040 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002041 void VisitOMPTeamsDistributeSimdDirective(
2042 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002043 void VisitOMPTeamsDistributeParallelForSimdDirective(
2044 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002045 void VisitOMPTeamsDistributeParallelForDirective(
2046 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002047 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002048 void VisitOMPTargetTeamsDistributeDirective(
2049 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002050 void VisitOMPTargetTeamsDistributeParallelForDirective(
2051 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002052 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2053 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002054 void VisitOMPTargetTeamsDistributeSimdDirective(
2055 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002056
Guy Benyei11169dd2012-12-18 14:30:41 +00002057private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002058 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002059 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002060 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2061 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002062 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2063 void AddStmt(const Stmt *S);
2064 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002065 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002066 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002067 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002068};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002069} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002070
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002071void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002072 // 'S' should always be non-null, since it comes from the
2073 // statement we are visiting.
2074 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2075}
2076
2077void
2078EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2079 if (Qualifier)
2080 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2081}
2082
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002083void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002084 if (S)
2085 WL.push_back(StmtVisit(S, Parent));
2086}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002087void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002088 if (D)
2089 WL.push_back(DeclVisit(D, Parent, isFirst));
2090}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002091void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2092 unsigned NumTemplateArgs) {
2093 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002094}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002095void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 if (D)
2097 WL.push_back(MemberRefVisit(D, L, Parent));
2098}
2099void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2100 if (TI)
2101 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2102 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002103void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002105 for (const Stmt *SubStmt : S->children()) {
2106 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002107 }
2108 if (size == WL.size())
2109 return;
2110 // Now reverse the entries we just added. This will match the DFS
2111 // ordering performed by the worklist.
2112 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2113 std::reverse(I, E);
2114}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002115namespace {
2116class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2117 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002118 /// \brief Process clauses with list of variables.
2119 template <typename T>
2120 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002121public:
2122 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2123#define OPENMP_CLAUSE(Name, Class) \
2124 void Visit##Class(const Class *C);
2125#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002126 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002127 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002128};
2129
Alexey Bataev3392d762016-02-16 11:18:12 +00002130void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2131 const OMPClauseWithPreInit *C) {
2132 Visitor->AddStmt(C->getPreInitStmt());
2133}
2134
Alexey Bataev005248a2016-02-25 05:25:57 +00002135void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2136 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002137 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002138 Visitor->AddStmt(C->getPostUpdateExpr());
2139}
2140
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002141void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002142 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002143 Visitor->AddStmt(C->getCondition());
2144}
2145
Alexey Bataev3778b602014-07-17 07:32:53 +00002146void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2147 Visitor->AddStmt(C->getCondition());
2148}
2149
Alexey Bataev568a8332014-03-06 06:15:19 +00002150void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002151 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002152 Visitor->AddStmt(C->getNumThreads());
2153}
2154
Alexey Bataev62c87d22014-03-21 04:51:18 +00002155void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2156 Visitor->AddStmt(C->getSafelen());
2157}
2158
Alexey Bataev66b15b52015-08-21 11:14:16 +00002159void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2160 Visitor->AddStmt(C->getSimdlen());
2161}
2162
Alexander Musman8bd31e62014-05-27 15:12:19 +00002163void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2164 Visitor->AddStmt(C->getNumForLoops());
2165}
2166
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002167void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002168
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002169void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2170
Alexey Bataev56dafe82014-06-20 07:16:17 +00002171void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002172 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002173 Visitor->AddStmt(C->getChunkSize());
2174}
2175
Alexey Bataev10e775f2015-07-30 11:36:16 +00002176void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2177 Visitor->AddStmt(C->getNumForLoops());
2178}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002179
Alexey Bataev236070f2014-06-20 11:19:47 +00002180void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2181
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002182void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2183
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002184void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2185
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002186void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2187
Alexey Bataevdea47612014-07-23 07:46:59 +00002188void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2189
Alexey Bataev67a4f222014-07-23 10:25:33 +00002190void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2191
Alexey Bataev459dec02014-07-24 06:46:57 +00002192void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2193
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002194void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2195
Alexey Bataev346265e2015-09-25 10:37:12 +00002196void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2197
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002198void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2199
Alexey Bataevb825de12015-12-07 10:51:44 +00002200void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2201
Michael Wonge710d542015-08-07 16:16:36 +00002202void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2203 Visitor->AddStmt(C->getDevice());
2204}
2205
Kelvin Li099bb8c2015-11-24 20:50:12 +00002206void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002207 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002208 Visitor->AddStmt(C->getNumTeams());
2209}
2210
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002211void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002212 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002213 Visitor->AddStmt(C->getThreadLimit());
2214}
2215
Alexey Bataeva0569352015-12-01 10:17:31 +00002216void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2217 Visitor->AddStmt(C->getPriority());
2218}
2219
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002220void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2221 Visitor->AddStmt(C->getGrainsize());
2222}
2223
Alexey Bataev382967a2015-12-08 12:06:20 +00002224void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2225 Visitor->AddStmt(C->getNumTasks());
2226}
2227
Alexey Bataev28c75412015-12-15 08:19:24 +00002228void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2229 Visitor->AddStmt(C->getHint());
2230}
2231
Alexey Bataev756c1962013-09-24 03:17:45 +00002232template<typename T>
2233void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002234 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002235 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002236 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002237}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002238
2239void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002240 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002241 for (const auto *E : C->private_copies()) {
2242 Visitor->AddStmt(E);
2243 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002244}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002245void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2246 const OMPFirstprivateClause *C) {
2247 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002248 VisitOMPClauseWithPreInit(C);
2249 for (const auto *E : C->private_copies()) {
2250 Visitor->AddStmt(E);
2251 }
2252 for (const auto *E : C->inits()) {
2253 Visitor->AddStmt(E);
2254 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002255}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002256void OMPClauseEnqueue::VisitOMPLastprivateClause(
2257 const OMPLastprivateClause *C) {
2258 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002259 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002260 for (auto *E : C->private_copies()) {
2261 Visitor->AddStmt(E);
2262 }
2263 for (auto *E : C->source_exprs()) {
2264 Visitor->AddStmt(E);
2265 }
2266 for (auto *E : C->destination_exprs()) {
2267 Visitor->AddStmt(E);
2268 }
2269 for (auto *E : C->assignment_ops()) {
2270 Visitor->AddStmt(E);
2271 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002272}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002273void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002274 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002275}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002276void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2277 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002278 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002279 for (auto *E : C->privates()) {
2280 Visitor->AddStmt(E);
2281 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002282 for (auto *E : C->lhs_exprs()) {
2283 Visitor->AddStmt(E);
2284 }
2285 for (auto *E : C->rhs_exprs()) {
2286 Visitor->AddStmt(E);
2287 }
2288 for (auto *E : C->reduction_ops()) {
2289 Visitor->AddStmt(E);
2290 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002291}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002292void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2293 const OMPTaskReductionClause *C) {
2294 VisitOMPClauseList(C);
2295 VisitOMPClauseWithPostUpdate(C);
2296 for (auto *E : C->privates()) {
2297 Visitor->AddStmt(E);
2298 }
2299 for (auto *E : C->lhs_exprs()) {
2300 Visitor->AddStmt(E);
2301 }
2302 for (auto *E : C->rhs_exprs()) {
2303 Visitor->AddStmt(E);
2304 }
2305 for (auto *E : C->reduction_ops()) {
2306 Visitor->AddStmt(E);
2307 }
2308}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002309void OMPClauseEnqueue::VisitOMPInReductionClause(
2310 const OMPInReductionClause *C) {
2311 VisitOMPClauseList(C);
2312 VisitOMPClauseWithPostUpdate(C);
2313 for (auto *E : C->privates()) {
2314 Visitor->AddStmt(E);
2315 }
2316 for (auto *E : C->lhs_exprs()) {
2317 Visitor->AddStmt(E);
2318 }
2319 for (auto *E : C->rhs_exprs()) {
2320 Visitor->AddStmt(E);
2321 }
2322 for (auto *E : C->reduction_ops()) {
2323 Visitor->AddStmt(E);
2324 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002325 for (auto *E : C->taskgroup_descriptors())
2326 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002327}
Alexander Musman8dba6642014-04-22 13:09:42 +00002328void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2329 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002330 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002331 for (const auto *E : C->privates()) {
2332 Visitor->AddStmt(E);
2333 }
Alexander Musman3276a272015-03-21 10:12:56 +00002334 for (const auto *E : C->inits()) {
2335 Visitor->AddStmt(E);
2336 }
2337 for (const auto *E : C->updates()) {
2338 Visitor->AddStmt(E);
2339 }
2340 for (const auto *E : C->finals()) {
2341 Visitor->AddStmt(E);
2342 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002343 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002344 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002345}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002346void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2347 VisitOMPClauseList(C);
2348 Visitor->AddStmt(C->getAlignment());
2349}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002350void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2351 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002352 for (auto *E : C->source_exprs()) {
2353 Visitor->AddStmt(E);
2354 }
2355 for (auto *E : C->destination_exprs()) {
2356 Visitor->AddStmt(E);
2357 }
2358 for (auto *E : C->assignment_ops()) {
2359 Visitor->AddStmt(E);
2360 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002361}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002362void
2363OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2364 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002365 for (auto *E : C->source_exprs()) {
2366 Visitor->AddStmt(E);
2367 }
2368 for (auto *E : C->destination_exprs()) {
2369 Visitor->AddStmt(E);
2370 }
2371 for (auto *E : C->assignment_ops()) {
2372 Visitor->AddStmt(E);
2373 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002374}
Alexey Bataev6125da92014-07-21 11:26:11 +00002375void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2376 VisitOMPClauseList(C);
2377}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002378void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2379 VisitOMPClauseList(C);
2380}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002381void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2382 VisitOMPClauseList(C);
2383}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002384void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2385 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002386 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002387 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002388}
Alexey Bataev3392d762016-02-16 11:18:12 +00002389void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2390 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002391void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2392 VisitOMPClauseList(C);
2393}
Samuel Antaoec172c62016-05-26 17:49:04 +00002394void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2395 VisitOMPClauseList(C);
2396}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002397void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2398 VisitOMPClauseList(C);
2399}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002400void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2401 VisitOMPClauseList(C);
2402}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002403}
Alexey Bataev756c1962013-09-24 03:17:45 +00002404
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002405void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2406 unsigned size = WL.size();
2407 OMPClauseEnqueue Visitor(this);
2408 Visitor.Visit(S);
2409 if (size == WL.size())
2410 return;
2411 // Now reverse the entries we just added. This will match the DFS
2412 // ordering performed by the worklist.
2413 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2414 std::reverse(I, E);
2415}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002416void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2418}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002419void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 AddDecl(B->getBlockDecl());
2421}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002422void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 EnqueueChildren(E);
2424 AddTypeLoc(E->getTypeSourceInfo());
2425}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002426void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002427 for (auto &I : llvm::reverse(S->body()))
2428 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002429}
2430void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002431VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 AddStmt(S->getSubStmt());
2433 AddDeclarationNameInfo(S);
2434 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2435 AddNestedNameSpecifierLoc(QualifierLoc);
2436}
2437
2438void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002439VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002440 if (E->hasExplicitTemplateArgs())
2441 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 AddDeclarationNameInfo(E);
2443 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2444 AddNestedNameSpecifierLoc(QualifierLoc);
2445 if (!E->isImplicitAccess())
2446 AddStmt(E->getBase());
2447}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002448void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 // Enqueue the initializer , if any.
2450 AddStmt(E->getInitializer());
2451 // Enqueue the array size, if any.
2452 AddStmt(E->getArraySize());
2453 // Enqueue the allocated type.
2454 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2455 // Enqueue the placement arguments.
2456 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2457 AddStmt(E->getPlacementArg(I-1));
2458}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002459void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2461 AddStmt(CE->getArg(I-1));
2462 AddStmt(CE->getCallee());
2463 AddStmt(CE->getArg(0));
2464}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002465void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2466 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 // Visit the name of the type being destroyed.
2468 AddTypeLoc(E->getDestroyedTypeInfo());
2469 // Visit the scope type that looks disturbingly like the nested-name-specifier
2470 // but isn't.
2471 AddTypeLoc(E->getScopeTypeInfo());
2472 // Visit the nested-name-specifier.
2473 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2474 AddNestedNameSpecifierLoc(QualifierLoc);
2475 // Visit base expression.
2476 AddStmt(E->getBase());
2477}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002478void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2479 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 AddTypeLoc(E->getTypeSourceInfo());
2481}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002482void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2483 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 EnqueueChildren(E);
2485 AddTypeLoc(E->getTypeSourceInfo());
2486}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002487void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 EnqueueChildren(E);
2489 if (E->isTypeOperand())
2490 AddTypeLoc(E->getTypeOperandSourceInfo());
2491}
2492
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002493void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2494 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 EnqueueChildren(E);
2496 AddTypeLoc(E->getTypeSourceInfo());
2497}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002498void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 EnqueueChildren(E);
2500 if (E->isTypeOperand())
2501 AddTypeLoc(E->getTypeOperandSourceInfo());
2502}
2503
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002504void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 EnqueueChildren(S);
2506 AddDecl(S->getExceptionDecl());
2507}
2508
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002509void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002510 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002511 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002512 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002513}
2514
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002515void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002516 if (DR->hasExplicitTemplateArgs())
2517 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 WL.push_back(DeclRefExprParts(DR, Parent));
2519}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002520void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2521 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002522 if (E->hasExplicitTemplateArgs())
2523 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 AddDeclarationNameInfo(E);
2525 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2526}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002527void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 unsigned size = WL.size();
2529 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002530 for (const auto *D : S->decls()) {
2531 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 isFirst = false;
2533 }
2534 if (size == WL.size())
2535 return;
2536 // Now reverse the entries we just added. This will match the DFS
2537 // ordering performed by the worklist.
2538 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2539 std::reverse(I, E);
2540}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002541void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002543 for (const DesignatedInitExpr::Designator &D :
2544 llvm::reverse(E->designators())) {
2545 if (D.isFieldDesignator()) {
2546 if (FieldDecl *Field = D.getField())
2547 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 continue;
2549 }
David Majnemerf7e36092016-06-23 00:15:04 +00002550 if (D.isArrayDesignator()) {
2551 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 continue;
2553 }
David Majnemerf7e36092016-06-23 00:15:04 +00002554 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2555 AddStmt(E->getArrayRangeEnd(D));
2556 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 }
2558}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002559void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 EnqueueChildren(E);
2561 AddTypeLoc(E->getTypeInfoAsWritten());
2562}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002563void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 AddStmt(FS->getBody());
2565 AddStmt(FS->getInc());
2566 AddStmt(FS->getCond());
2567 AddDecl(FS->getConditionVariable());
2568 AddStmt(FS->getInit());
2569}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002570void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2572}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002573void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 AddStmt(If->getElse());
2575 AddStmt(If->getThen());
2576 AddStmt(If->getCond());
2577 AddDecl(If->getConditionVariable());
2578}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002579void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 // We care about the syntactic form of the initializer list, only.
2581 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2582 IE = Syntactic;
2583 EnqueueChildren(IE);
2584}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002585void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 WL.push_back(MemberExprParts(M, Parent));
2587
2588 // If the base of the member access expression is an implicit 'this', don't
2589 // visit it.
2590 // FIXME: If we ever want to show these implicit accesses, this will be
2591 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002592 if (M->isImplicitAccess())
2593 return;
2594
2595 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002596 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002597 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2598 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2599 if (FD->isAnonymousStructOrUnion()) {
2600 AddStmt(SubME->getBase());
2601 return;
2602 }
2603 }
2604 }
2605
2606 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002607}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002608void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 AddTypeLoc(E->getEncodedTypeSourceInfo());
2610}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002611void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 EnqueueChildren(M);
2613 AddTypeLoc(M->getClassReceiverTypeInfo());
2614}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002615void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 // Visit the components of the offsetof expression.
2617 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 const OffsetOfNode &Node = E->getComponent(I-1);
2619 switch (Node.getKind()) {
2620 case OffsetOfNode::Array:
2621 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2622 break;
2623 case OffsetOfNode::Field:
2624 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2625 break;
2626 case OffsetOfNode::Identifier:
2627 case OffsetOfNode::Base:
2628 continue;
2629 }
2630 }
2631 // Visit the type into which we're computing the offset.
2632 AddTypeLoc(E->getTypeSourceInfo());
2633}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002634void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002635 if (E->hasExplicitTemplateArgs())
2636 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 WL.push_back(OverloadExprParts(E, Parent));
2638}
2639void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002640 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 EnqueueChildren(E);
2642 if (E->isArgumentType())
2643 AddTypeLoc(E->getArgumentTypeInfo());
2644}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002645void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 EnqueueChildren(S);
2647}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002648void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 AddStmt(S->getBody());
2650 AddStmt(S->getCond());
2651 AddDecl(S->getConditionVariable());
2652}
2653
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002654void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 AddStmt(W->getBody());
2656 AddStmt(W->getCond());
2657 AddDecl(W->getConditionVariable());
2658}
2659
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002660void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 for (unsigned I = E->getNumArgs(); I > 0; --I)
2662 AddTypeLoc(E->getArg(I-1));
2663}
2664
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002665void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 AddTypeLoc(E->getQueriedTypeSourceInfo());
2667}
2668
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002669void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 EnqueueChildren(E);
2671}
2672
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002673void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 VisitOverloadExpr(U);
2675 if (!U->isImplicitAccess())
2676 AddStmt(U->getBase());
2677}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002678void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 AddStmt(E->getSubExpr());
2680 AddTypeLoc(E->getWrittenTypeInfo());
2681}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002682void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 WL.push_back(SizeOfPackExprParts(E, Parent));
2684}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002685void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 // If the opaque value has a source expression, just transparently
2687 // visit that. This is useful for (e.g.) pseudo-object expressions.
2688 if (Expr *SourceExpr = E->getSourceExpr())
2689 return Visit(SourceExpr);
2690}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002691void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 AddStmt(E->getBody());
2693 WL.push_back(LambdaExprParts(E, Parent));
2694}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002695void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 // Treat the expression like its syntactic form.
2697 Visit(E->getSyntacticForm());
2698}
2699
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002700void EnqueueVisitor::VisitOMPExecutableDirective(
2701 const OMPExecutableDirective *D) {
2702 EnqueueChildren(D);
2703 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2704 E = D->clauses().end();
2705 I != E; ++I)
2706 EnqueueChildren(*I);
2707}
2708
Alexander Musman3aaab662014-08-19 11:27:13 +00002709void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2710 VisitOMPExecutableDirective(D);
2711}
2712
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002713void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2714 VisitOMPExecutableDirective(D);
2715}
2716
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002717void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002718 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002719}
2720
Alexey Bataevf29276e2014-06-18 04:14:57 +00002721void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002722 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002723}
2724
Alexander Musmanf82886e2014-09-18 05:12:34 +00002725void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2726 VisitOMPLoopDirective(D);
2727}
2728
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002729void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2730 VisitOMPExecutableDirective(D);
2731}
2732
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002733void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2734 VisitOMPExecutableDirective(D);
2735}
2736
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002737void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2738 VisitOMPExecutableDirective(D);
2739}
2740
Alexander Musman80c22892014-07-17 08:54:58 +00002741void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2742 VisitOMPExecutableDirective(D);
2743}
2744
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002745void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2746 VisitOMPExecutableDirective(D);
2747 AddDeclarationNameInfo(D);
2748}
2749
Alexey Bataev4acb8592014-07-07 13:01:15 +00002750void
2751EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002752 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002753}
2754
Alexander Musmane4e893b2014-09-23 09:33:00 +00002755void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2756 const OMPParallelForSimdDirective *D) {
2757 VisitOMPLoopDirective(D);
2758}
2759
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002760void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2761 const OMPParallelSectionsDirective *D) {
2762 VisitOMPExecutableDirective(D);
2763}
2764
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002765void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2766 VisitOMPExecutableDirective(D);
2767}
2768
Alexey Bataev68446b72014-07-18 07:47:19 +00002769void
2770EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2771 VisitOMPExecutableDirective(D);
2772}
2773
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002774void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2775 VisitOMPExecutableDirective(D);
2776}
2777
Alexey Bataev2df347a2014-07-18 10:17:07 +00002778void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2779 VisitOMPExecutableDirective(D);
2780}
2781
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002782void EnqueueVisitor::VisitOMPTaskgroupDirective(
2783 const OMPTaskgroupDirective *D) {
2784 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002785 if (const Expr *E = D->getReductionRef())
2786 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002787}
2788
Alexey Bataev6125da92014-07-21 11:26:11 +00002789void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2790 VisitOMPExecutableDirective(D);
2791}
2792
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002793void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2794 VisitOMPExecutableDirective(D);
2795}
2796
Alexey Bataev0162e452014-07-22 10:10:35 +00002797void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2798 VisitOMPExecutableDirective(D);
2799}
2800
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002801void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2802 VisitOMPExecutableDirective(D);
2803}
2804
Michael Wong65f367f2015-07-21 13:44:28 +00002805void EnqueueVisitor::VisitOMPTargetDataDirective(const
2806 OMPTargetDataDirective *D) {
2807 VisitOMPExecutableDirective(D);
2808}
2809
Samuel Antaodf67fc42016-01-19 19:15:56 +00002810void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2811 const OMPTargetEnterDataDirective *D) {
2812 VisitOMPExecutableDirective(D);
2813}
2814
Samuel Antao72590762016-01-19 20:04:50 +00002815void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2816 const OMPTargetExitDataDirective *D) {
2817 VisitOMPExecutableDirective(D);
2818}
2819
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002820void EnqueueVisitor::VisitOMPTargetParallelDirective(
2821 const OMPTargetParallelDirective *D) {
2822 VisitOMPExecutableDirective(D);
2823}
2824
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002825void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2826 const OMPTargetParallelForDirective *D) {
2827 VisitOMPLoopDirective(D);
2828}
2829
Alexey Bataev13314bf2014-10-09 04:18:56 +00002830void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2831 VisitOMPExecutableDirective(D);
2832}
2833
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002834void EnqueueVisitor::VisitOMPCancellationPointDirective(
2835 const OMPCancellationPointDirective *D) {
2836 VisitOMPExecutableDirective(D);
2837}
2838
Alexey Bataev80909872015-07-02 11:25:17 +00002839void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2840 VisitOMPExecutableDirective(D);
2841}
2842
Alexey Bataev49f6e782015-12-01 04:18:41 +00002843void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2844 VisitOMPLoopDirective(D);
2845}
2846
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002847void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2848 const OMPTaskLoopSimdDirective *D) {
2849 VisitOMPLoopDirective(D);
2850}
2851
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002852void EnqueueVisitor::VisitOMPDistributeDirective(
2853 const OMPDistributeDirective *D) {
2854 VisitOMPLoopDirective(D);
2855}
2856
Carlo Bertolli9925f152016-06-27 14:55:37 +00002857void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2858 const OMPDistributeParallelForDirective *D) {
2859 VisitOMPLoopDirective(D);
2860}
2861
Kelvin Li4a39add2016-07-05 05:00:15 +00002862void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2863 const OMPDistributeParallelForSimdDirective *D) {
2864 VisitOMPLoopDirective(D);
2865}
2866
Kelvin Li787f3fc2016-07-06 04:45:38 +00002867void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2868 const OMPDistributeSimdDirective *D) {
2869 VisitOMPLoopDirective(D);
2870}
2871
Kelvin Lia579b912016-07-14 02:54:56 +00002872void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2873 const OMPTargetParallelForSimdDirective *D) {
2874 VisitOMPLoopDirective(D);
2875}
2876
Kelvin Li986330c2016-07-20 22:57:10 +00002877void EnqueueVisitor::VisitOMPTargetSimdDirective(
2878 const OMPTargetSimdDirective *D) {
2879 VisitOMPLoopDirective(D);
2880}
2881
Kelvin Li02532872016-08-05 14:37:37 +00002882void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2883 const OMPTeamsDistributeDirective *D) {
2884 VisitOMPLoopDirective(D);
2885}
2886
Kelvin Li4e325f72016-10-25 12:50:55 +00002887void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2888 const OMPTeamsDistributeSimdDirective *D) {
2889 VisitOMPLoopDirective(D);
2890}
2891
Kelvin Li579e41c2016-11-30 23:51:03 +00002892void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2893 const OMPTeamsDistributeParallelForSimdDirective *D) {
2894 VisitOMPLoopDirective(D);
2895}
2896
Kelvin Li7ade93f2016-12-09 03:24:30 +00002897void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2898 const OMPTeamsDistributeParallelForDirective *D) {
2899 VisitOMPLoopDirective(D);
2900}
2901
Kelvin Libf594a52016-12-17 05:48:59 +00002902void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2903 const OMPTargetTeamsDirective *D) {
2904 VisitOMPExecutableDirective(D);
2905}
2906
Kelvin Li83c451e2016-12-25 04:52:54 +00002907void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2908 const OMPTargetTeamsDistributeDirective *D) {
2909 VisitOMPLoopDirective(D);
2910}
2911
Kelvin Li80e8f562016-12-29 22:16:30 +00002912void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2913 const OMPTargetTeamsDistributeParallelForDirective *D) {
2914 VisitOMPLoopDirective(D);
2915}
2916
Kelvin Li1851df52017-01-03 05:23:48 +00002917void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2918 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2919 VisitOMPLoopDirective(D);
2920}
2921
Kelvin Lida681182017-01-10 18:08:18 +00002922void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2923 const OMPTargetTeamsDistributeSimdDirective *D) {
2924 VisitOMPLoopDirective(D);
2925}
2926
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002927void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2929}
2930
2931bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2932 if (RegionOfInterest.isValid()) {
2933 SourceRange Range = getRawCursorExtent(C);
2934 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2935 return false;
2936 }
2937 return true;
2938}
2939
2940bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2941 while (!WL.empty()) {
2942 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002943 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002944
2945 // Set the Parent field, then back to its old value once we're done.
2946 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2947
2948 switch (LI.getKind()) {
2949 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002950 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 if (!D)
2952 continue;
2953
2954 // For now, perform default visitation for Decls.
2955 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2956 cast<DeclVisit>(&LI)->isFirst())))
2957 return true;
2958
2959 continue;
2960 }
2961 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002962 for (const TemplateArgumentLoc &Arg :
2963 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2964 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 return true;
2966 }
2967 continue;
2968 }
2969 case VisitorJob::TypeLocVisitKind: {
2970 // Perform default visitation for TypeLocs.
2971 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2972 return true;
2973 continue;
2974 }
2975 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002976 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002977 if (LabelStmt *stmt = LS->getStmt()) {
2978 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2979 TU))) {
2980 return true;
2981 }
2982 }
2983 continue;
2984 }
2985
2986 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2987 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2988 if (VisitNestedNameSpecifierLoc(V->get()))
2989 return true;
2990 continue;
2991 }
2992
2993 case VisitorJob::DeclarationNameInfoVisitKind: {
2994 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2995 ->get()))
2996 return true;
2997 continue;
2998 }
2999 case VisitorJob::MemberRefVisitKind: {
3000 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3001 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3002 return true;
3003 continue;
3004 }
3005 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003006 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 if (!S)
3008 continue;
3009
3010 // Update the current cursor.
3011 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3012 if (!IsInRegionOfInterest(Cursor))
3013 continue;
3014 switch (Visitor(Cursor, Parent, ClientData)) {
3015 case CXChildVisit_Break: return true;
3016 case CXChildVisit_Continue: break;
3017 case CXChildVisit_Recurse:
3018 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003019 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 EnqueueWorkList(WL, S);
3021 break;
3022 }
3023 continue;
3024 }
3025 case VisitorJob::MemberExprPartsKind: {
3026 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003027 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003028
3029 // Visit the nested-name-specifier
3030 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3031 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3032 return true;
3033
3034 // Visit the declaration name.
3035 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3036 return true;
3037
3038 // Visit the explicitly-specified template arguments, if any.
3039 if (M->hasExplicitTemplateArgs()) {
3040 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3041 *ArgEnd = Arg + M->getNumTemplateArgs();
3042 Arg != ArgEnd; ++Arg) {
3043 if (VisitTemplateArgumentLoc(*Arg))
3044 return true;
3045 }
3046 }
3047 continue;
3048 }
3049 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003050 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 // Visit nested-name-specifier, if present.
3052 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3053 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3054 return true;
3055 // Visit declaration name.
3056 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3057 return true;
3058 continue;
3059 }
3060 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003061 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 // Visit the nested-name-specifier.
3063 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3064 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3065 return true;
3066 // Visit the declaration name.
3067 if (VisitDeclarationNameInfo(O->getNameInfo()))
3068 return true;
3069 // Visit the overloaded declaration reference.
3070 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3071 return true;
3072 continue;
3073 }
3074 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003075 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 NamedDecl *Pack = E->getPack();
3077 if (isa<TemplateTypeParmDecl>(Pack)) {
3078 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3079 E->getPackLoc(), TU)))
3080 return true;
3081
3082 continue;
3083 }
3084
3085 if (isa<TemplateTemplateParmDecl>(Pack)) {
3086 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3087 E->getPackLoc(), TU)))
3088 return true;
3089
3090 continue;
3091 }
3092
3093 // Non-type template parameter packs and function parameter packs are
3094 // treated like DeclRefExpr cursors.
3095 continue;
3096 }
3097
3098 case VisitorJob::LambdaExprPartsKind: {
3099 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003100 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3102 CEnd = E->explicit_capture_end();
3103 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003104 // FIXME: Lambda init-captures.
3105 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003107
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3109 C->getLocation(),
3110 TU)))
3111 return true;
3112 }
3113
3114 // Visit parameters and return type, if present.
3115 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3116 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3117 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3118 // Visit the whole type.
3119 if (Visit(TL))
3120 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003121 } else if (FunctionProtoTypeLoc Proto =
3122 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003123 if (E->hasExplicitParameters()) {
3124 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003125 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3126 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 return true;
3128 } else {
3129 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003130 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 return true;
3132 }
3133 }
3134 }
3135 break;
3136 }
3137
3138 case VisitorJob::PostChildrenVisitKind:
3139 if (PostChildrenVisitor(Parent, ClientData))
3140 return true;
3141 break;
3142 }
3143 }
3144 return false;
3145}
3146
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003147bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003148 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003149 if (!WorkListFreeList.empty()) {
3150 WL = WorkListFreeList.back();
3151 WL->clear();
3152 WorkListFreeList.pop_back();
3153 }
3154 else {
3155 WL = new VisitorWorkList();
3156 WorkListCache.push_back(WL);
3157 }
3158 EnqueueWorkList(*WL, S);
3159 bool result = RunVisitorWorkList(*WL);
3160 WorkListFreeList.push_back(WL);
3161 return result;
3162}
3163
3164namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003165typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003166RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3167 const DeclarationNameInfo &NI, SourceRange QLoc,
3168 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3170 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3171 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3172
3173 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3174
3175 RefNamePieces Pieces;
3176
3177 if (WantQualifier && QLoc.isValid())
3178 Pieces.push_back(QLoc);
3179
3180 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3181 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003182
3183 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3184 Pieces.push_back(*TemplateArgsLoc);
3185
Guy Benyei11169dd2012-12-18 14:30:41 +00003186 if (Kind == DeclarationName::CXXOperatorName) {
3187 Pieces.push_back(SourceLocation::getFromRawEncoding(
3188 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3189 Pieces.push_back(SourceLocation::getFromRawEncoding(
3190 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3191 }
3192
3193 if (WantSinglePiece) {
3194 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3195 Pieces.clear();
3196 Pieces.push_back(R);
3197 }
3198
3199 return Pieces;
3200}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003201}
Guy Benyei11169dd2012-12-18 14:30:41 +00003202
3203//===----------------------------------------------------------------------===//
3204// Misc. API hooks.
3205//===----------------------------------------------------------------------===//
3206
Chad Rosier05c71aa2013-03-27 18:28:23 +00003207static void fatal_error_handler(void *user_data, const std::string& reason,
3208 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 // Write the result out to stderr avoiding errs() because raw_ostreams can
3210 // call report_fatal_error.
3211 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3212 ::abort();
3213}
3214
Chandler Carruth66660742014-06-27 16:37:27 +00003215namespace {
3216struct RegisterFatalErrorHandler {
3217 RegisterFatalErrorHandler() {
3218 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3219 }
3220};
3221}
3222
3223static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3224
Guy Benyei11169dd2012-12-18 14:30:41 +00003225CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3226 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 // We use crash recovery to make some of our APIs more reliable, implicitly
3228 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003229 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3230 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003231
Chandler Carruth66660742014-06-27 16:37:27 +00003232 // Look through the managed static to trigger construction of the managed
3233 // static which registers our fatal error handler. This ensures it is only
3234 // registered once.
3235 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003236
Adrian Prantlbc068582015-07-08 01:00:30 +00003237 // Initialize targets for clang module support.
3238 llvm::InitializeAllTargets();
3239 llvm::InitializeAllTargetMCs();
3240 llvm::InitializeAllAsmPrinters();
3241 llvm::InitializeAllAsmParsers();
3242
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003243 CIndexer *CIdxr = new CIndexer();
3244
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 if (excludeDeclarationsFromPCH)
3246 CIdxr->setOnlyLocalDecls();
3247 if (displayDiagnostics)
3248 CIdxr->setDisplayDiagnostics();
3249
3250 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3251 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3252 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3253 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3254 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3255 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3256
3257 return CIdxr;
3258}
3259
3260void clang_disposeIndex(CXIndex CIdx) {
3261 if (CIdx)
3262 delete static_cast<CIndexer *>(CIdx);
3263}
3264
3265void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3266 if (CIdx)
3267 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3268}
3269
3270unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3271 if (CIdx)
3272 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3273 return 0;
3274}
3275
Alex Lorenz08615792017-12-04 21:56:36 +00003276void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3277 const char *Path) {
3278 if (CIdx)
3279 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3280}
3281
Guy Benyei11169dd2012-12-18 14:30:41 +00003282void clang_toggleCrashRecovery(unsigned isEnabled) {
3283 if (isEnabled)
3284 llvm::CrashRecoveryContext::Enable();
3285 else
3286 llvm::CrashRecoveryContext::Disable();
3287}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003288
Guy Benyei11169dd2012-12-18 14:30:41 +00003289CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3290 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003291 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003292 enum CXErrorCode Result =
3293 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003294 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003295 assert((TU && Result == CXError_Success) ||
3296 (!TU && Result != CXError_Success));
3297 return TU;
3298}
3299
3300enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3301 const char *ast_filename,
3302 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003303 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003304 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003305
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003306 if (!CIdx || !ast_filename || !out_TU)
3307 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003308
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003309 LOG_FUNC_SECTION {
3310 *Log << ast_filename;
3311 }
3312
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3314 FileSystemOptions FileSystemOpts;
3315
Justin Bognerd512c1e2014-10-15 00:33:06 +00003316 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3317 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003318 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003319 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3320 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003321 FileSystemOpts, /*UseDebugInfo=*/false,
3322 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003323 /*CaptureDiagnostics=*/true,
3324 /*AllowPCHWithCompilerErrors=*/true,
3325 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003326 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003327 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003328}
3329
3330unsigned clang_defaultEditingTranslationUnitOptions() {
3331 return CXTranslationUnit_PrecompiledPreamble |
3332 CXTranslationUnit_CacheCompletionResults;
3333}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003334
Guy Benyei11169dd2012-12-18 14:30:41 +00003335CXTranslationUnit
3336clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3337 const char *source_filename,
3338 int num_command_line_args,
3339 const char * const *command_line_args,
3340 unsigned num_unsaved_files,
3341 struct CXUnsavedFile *unsaved_files) {
3342 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3343 return clang_parseTranslationUnit(CIdx, source_filename,
3344 command_line_args, num_command_line_args,
3345 unsaved_files, num_unsaved_files,
3346 Options);
3347}
3348
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003349static CXErrorCode
3350clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3351 const char *const *command_line_args,
3352 int num_command_line_args,
3353 ArrayRef<CXUnsavedFile> unsaved_files,
3354 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003355 // Set up the initial return values.
3356 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003357 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003358
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003359 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003360 if (!CIdx || !out_TU)
3361 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003362
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3364
3365 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3366 setThreadBackgroundPriority();
3367
3368 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003369 bool CreatePreambleOnFirstParse =
3370 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 // FIXME: Add a flag for modules.
3372 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003373 = (options & (CXTranslationUnit_Incomplete |
3374 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003375 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 = options & CXTranslationUnit_CacheCompletionResults;
3377 bool IncludeBriefCommentsInCodeCompletion
3378 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3379 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003380 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3382
3383 // Configure the diagnostics.
3384 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003385 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003386
Manuel Klimek016c0242016-03-01 10:56:19 +00003387 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003388 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003389
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 // Recover resources if we crash before exiting this function.
3391 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3392 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003393 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003394
Ahmed Charlesb8984322014-03-07 20:03:18 +00003395 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3396 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003397
3398 // Recover resources if we crash before exiting this function.
3399 llvm::CrashRecoveryContextCleanupRegistrar<
3400 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3401
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003402 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003403 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003404 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003405 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003406 }
3407
Ahmed Charlesb8984322014-03-07 20:03:18 +00003408 std::unique_ptr<std::vector<const char *>> Args(
3409 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003410
3411 // Recover resources if we crash before exiting this method.
3412 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3413 ArgsCleanup(Args.get());
3414
3415 // Since the Clang C library is primarily used by batch tools dealing with
3416 // (often very broken) source code, where spell-checking can have a
3417 // significant negative impact on performance (particularly when
3418 // precompiled headers are involved), we disable it by default.
3419 // Only do this if we haven't found a spell-checking-related argument.
3420 bool FoundSpellCheckingArgument = false;
3421 for (int I = 0; I != num_command_line_args; ++I) {
3422 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3423 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3424 FoundSpellCheckingArgument = true;
3425 break;
3426 }
3427 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003428 Args->insert(Args->end(), command_line_args,
3429 command_line_args + num_command_line_args);
3430
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003431 if (!FoundSpellCheckingArgument)
3432 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3433
Guy Benyei11169dd2012-12-18 14:30:41 +00003434 // The 'source_filename' argument is optional. If the caller does not
3435 // specify it then it is assumed that the source file is specified
3436 // in the actual argument list.
3437 // Put the source file after command_line_args otherwise if '-x' flag is
3438 // present it will be unused.
3439 if (source_filename)
3440 Args->push_back(source_filename);
3441
3442 // Do we need the detailed preprocessing record?
3443 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3444 Args->push_back("-Xclang");
3445 Args->push_back("-detailed-preprocessing-record");
3446 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003447
3448 // Suppress any editor placeholder diagnostics.
3449 Args->push_back("-fallow-editor-placeholders");
3450
Guy Benyei11169dd2012-12-18 14:30:41 +00003451 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003452 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003453 // Unless the user specified that they want the preamble on the first parse
3454 // set it up to be created on the first reparse. This makes the first parse
3455 // faster, trading for a slower (first) reparse.
3456 unsigned PrecompilePreambleAfterNParses =
3457 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003458
Alex Lorenz08615792017-12-04 21:56:36 +00003459 LibclangInvocationReporter InvocationReporter(
3460 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003461 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3462 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003463 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003464 Args->data(), Args->data() + Args->size(),
3465 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003466 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3467 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003468 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3469 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003470 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003471 /*UserFilesAreVolatile=*/true, ForSerialization,
3472 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3473 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003474
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003475 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003476 if (!Unit && !ErrUnit)
3477 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003478
Guy Benyei11169dd2012-12-18 14:30:41 +00003479 if (NumErrors != Diags->getClient()->getNumErrors()) {
3480 // Make sure to check that 'Unit' is non-NULL.
3481 if (CXXIdx->getDisplayDiagnostics())
3482 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3483 }
3484
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003485 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3486 return CXError_ASTReadError;
3487
David Blaikieea4395e2017-01-06 19:49:01 +00003488 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003489 if (CXTranslationUnitImpl *TU = *out_TU) {
3490 TU->ParsingOptions = options;
3491 TU->Arguments.reserve(Args->size());
3492 for (const char *Arg : *Args)
3493 TU->Arguments.push_back(Arg);
3494 return CXError_Success;
3495 }
3496 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003497}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003498
3499CXTranslationUnit
3500clang_parseTranslationUnit(CXIndex CIdx,
3501 const char *source_filename,
3502 const char *const *command_line_args,
3503 int num_command_line_args,
3504 struct CXUnsavedFile *unsaved_files,
3505 unsigned num_unsaved_files,
3506 unsigned options) {
3507 CXTranslationUnit TU;
3508 enum CXErrorCode Result = clang_parseTranslationUnit2(
3509 CIdx, source_filename, command_line_args, num_command_line_args,
3510 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003511 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003512 assert((TU && Result == CXError_Success) ||
3513 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003514 return TU;
3515}
3516
3517enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003518 CXIndex CIdx, const char *source_filename,
3519 const char *const *command_line_args, int num_command_line_args,
3520 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3521 unsigned options, CXTranslationUnit *out_TU) {
3522 SmallVector<const char *, 4> Args;
3523 Args.push_back("clang");
3524 Args.append(command_line_args, command_line_args + num_command_line_args);
3525 return clang_parseTranslationUnit2FullArgv(
3526 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3527 num_unsaved_files, options, out_TU);
3528}
3529
3530enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3531 CXIndex CIdx, const char *source_filename,
3532 const char *const *command_line_args, int num_command_line_args,
3533 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3534 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003535 LOG_FUNC_SECTION {
3536 *Log << source_filename << ": ";
3537 for (int i = 0; i != num_command_line_args; ++i)
3538 *Log << command_line_args[i] << " ";
3539 }
3540
Alp Toker9d85b182014-07-07 01:23:14 +00003541 if (num_unsaved_files && !unsaved_files)
3542 return CXError_InvalidArguments;
3543
Alp Toker5c532982014-07-07 22:42:03 +00003544 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003545 auto ParseTranslationUnitImpl = [=, &result] {
3546 result = clang_parseTranslationUnit_Impl(
3547 CIdx, source_filename, command_line_args, num_command_line_args,
3548 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3549 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003550
Guy Benyei11169dd2012-12-18 14:30:41 +00003551 llvm::CrashRecoveryContext CRC;
3552
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003553 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3555 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3556 fprintf(stderr, " 'command_line_args' : [");
3557 for (int i = 0; i != num_command_line_args; ++i) {
3558 if (i)
3559 fprintf(stderr, ", ");
3560 fprintf(stderr, "'%s'", command_line_args[i]);
3561 }
3562 fprintf(stderr, "],\n");
3563 fprintf(stderr, " 'unsaved_files' : [");
3564 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3565 if (i)
3566 fprintf(stderr, ", ");
3567 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3568 unsaved_files[i].Length);
3569 }
3570 fprintf(stderr, "],\n");
3571 fprintf(stderr, " 'options' : %d,\n", options);
3572 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003573
3574 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003575 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003576 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003577 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003578 }
Alp Toker5c532982014-07-07 22:42:03 +00003579
3580 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003581}
3582
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003583CXString clang_Type_getObjCEncoding(CXType CT) {
3584 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3585 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3586 std::string encoding;
3587 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3588 encoding);
3589
3590 return cxstring::createDup(encoding);
3591}
3592
3593static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3594 if (C.kind == CXCursor_MacroDefinition) {
3595 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3596 return MDR->getName();
3597 } else if (C.kind == CXCursor_MacroExpansion) {
3598 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3599 return ME.getName();
3600 }
3601 return nullptr;
3602}
3603
3604unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3605 const IdentifierInfo *II = getMacroIdentifier(C);
3606 if (!II) {
3607 return false;
3608 }
3609 ASTUnit *ASTU = getCursorASTUnit(C);
3610 Preprocessor &PP = ASTU->getPreprocessor();
3611 if (const MacroInfo *MI = PP.getMacroInfo(II))
3612 return MI->isFunctionLike();
3613 return false;
3614}
3615
3616unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3617 const IdentifierInfo *II = getMacroIdentifier(C);
3618 if (!II) {
3619 return false;
3620 }
3621 ASTUnit *ASTU = getCursorASTUnit(C);
3622 Preprocessor &PP = ASTU->getPreprocessor();
3623 if (const MacroInfo *MI = PP.getMacroInfo(II))
3624 return MI->isBuiltinMacro();
3625 return false;
3626}
3627
3628unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3629 const Decl *D = getCursorDecl(C);
3630 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3631 if (!FD) {
3632 return false;
3633 }
3634 return FD->isInlined();
3635}
3636
3637static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3638 if (callExpr->getNumArgs() != 1) {
3639 return nullptr;
3640 }
3641
3642 StringLiteral *S = nullptr;
3643 auto *arg = callExpr->getArg(0);
3644 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3645 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3646 auto *subExpr = I->getSubExprAsWritten();
3647
3648 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3649 return nullptr;
3650 }
3651
3652 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3653 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3654 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3655 } else {
3656 return nullptr;
3657 }
3658 return S;
3659}
3660
David Blaikie59272572016-04-13 18:23:33 +00003661struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003662 CXEvalResultKind EvalType;
3663 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003664 unsigned long long unsignedVal;
3665 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003666 double floatVal;
3667 char *stringVal;
3668 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003669 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003670 ~ExprEvalResult() {
3671 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3672 EvalType != CXEval_Int) {
3673 delete EvalData.stringVal;
3674 }
3675 }
3676};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003677
3678void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003679 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003680}
3681
3682CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3683 if (!E) {
3684 return CXEval_UnExposed;
3685 }
3686 return ((ExprEvalResult *)E)->EvalType;
3687}
3688
3689int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003690 return clang_EvalResult_getAsLongLong(E);
3691}
3692
3693long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003694 if (!E) {
3695 return 0;
3696 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003697 ExprEvalResult *Result = (ExprEvalResult*)E;
3698 if (Result->IsUnsignedInt)
3699 return Result->EvalData.unsignedVal;
3700 return Result->EvalData.intVal;
3701}
3702
3703unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3704 return ((ExprEvalResult *)E)->IsUnsignedInt;
3705}
3706
3707unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3708 if (!E) {
3709 return 0;
3710 }
3711
3712 ExprEvalResult *Result = (ExprEvalResult*)E;
3713 if (Result->IsUnsignedInt)
3714 return Result->EvalData.unsignedVal;
3715 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003716}
3717
3718double clang_EvalResult_getAsDouble(CXEvalResult E) {
3719 if (!E) {
3720 return 0;
3721 }
3722 return ((ExprEvalResult *)E)->EvalData.floatVal;
3723}
3724
3725const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3726 if (!E) {
3727 return nullptr;
3728 }
3729 return ((ExprEvalResult *)E)->EvalData.stringVal;
3730}
3731
3732static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3733 Expr::EvalResult ER;
3734 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003735 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003736 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003737
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003738 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003739 if (!expr->EvaluateAsRValue(ER, ctx))
3740 return nullptr;
3741
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003742 QualType rettype;
3743 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003744 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003745 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003746 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003747
David Blaikiebbc00882016-04-13 18:36:19 +00003748 if (ER.Val.isInt()) {
3749 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003750
3751 auto& val = ER.Val.getInt();
3752 if (val.isUnsigned()) {
3753 result->IsUnsignedInt = true;
3754 result->EvalData.unsignedVal = val.getZExtValue();
3755 } else {
3756 result->EvalData.intVal = val.getExtValue();
3757 }
3758
David Blaikiebbc00882016-04-13 18:36:19 +00003759 return result.release();
3760 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003761
David Blaikiebbc00882016-04-13 18:36:19 +00003762 if (ER.Val.isFloat()) {
3763 llvm::SmallVector<char, 100> Buffer;
3764 ER.Val.getFloat().toString(Buffer);
3765 std::string floatStr(Buffer.data(), Buffer.size());
3766 result->EvalType = CXEval_Float;
3767 bool ignored;
3768 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003769 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003770 llvm::APFloat::rmNearestTiesToEven, &ignored);
3771 result->EvalData.floatVal = apFloat.convertToDouble();
3772 return result.release();
3773 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003774
David Blaikiebbc00882016-04-13 18:36:19 +00003775 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3776 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3777 auto *subExpr = I->getSubExprAsWritten();
3778 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3779 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003780 const StringLiteral *StrE = nullptr;
3781 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003782 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003783
3784 if (ObjCExpr) {
3785 StrE = ObjCExpr->getString();
3786 result->EvalType = CXEval_ObjCStrLiteral;
3787 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003788 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003789 result->EvalType = CXEval_StrLiteral;
3790 }
3791
3792 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003793 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003794 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3795 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003796 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003797 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003798 }
3799 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3800 expr->getStmtClass() == Stmt::StringLiteralClass) {
3801 const StringLiteral *StrE = nullptr;
3802 const ObjCStringLiteral *ObjCExpr;
3803 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003804
David Blaikiebbc00882016-04-13 18:36:19 +00003805 if (ObjCExpr) {
3806 StrE = ObjCExpr->getString();
3807 result->EvalType = CXEval_ObjCStrLiteral;
3808 } else {
3809 StrE = cast<StringLiteral>(expr);
3810 result->EvalType = CXEval_StrLiteral;
3811 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003812
David Blaikiebbc00882016-04-13 18:36:19 +00003813 std::string strRef(StrE->getString().str());
3814 result->EvalData.stringVal = new char[strRef.size() + 1];
3815 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3816 result->EvalData.stringVal[strRef.size()] = '\0';
3817 return result.release();
3818 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003819
David Blaikiebbc00882016-04-13 18:36:19 +00003820 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3821 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003822
David Blaikiebbc00882016-04-13 18:36:19 +00003823 rettype = CC->getType();
3824 if (rettype.getAsString() == "CFStringRef" &&
3825 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003826
David Blaikiebbc00882016-04-13 18:36:19 +00003827 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3828 StringLiteral *S = getCFSTR_value(callExpr);
3829 if (S) {
3830 std::string strLiteral(S->getString().str());
3831 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003832
David Blaikiebbc00882016-04-13 18:36:19 +00003833 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3834 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3835 strLiteral.size());
3836 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003837 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003838 }
3839 }
3840
David Blaikiebbc00882016-04-13 18:36:19 +00003841 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3842 callExpr = static_cast<CallExpr *>(expr);
3843 rettype = callExpr->getCallReturnType(ctx);
3844
3845 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3846 return nullptr;
3847
3848 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3849 if (callExpr->getNumArgs() == 1 &&
3850 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3851 return nullptr;
3852 } else if (rettype.getAsString() == "CFStringRef") {
3853
3854 StringLiteral *S = getCFSTR_value(callExpr);
3855 if (S) {
3856 std::string strLiteral(S->getString().str());
3857 result->EvalType = CXEval_CFStr;
3858 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3859 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3860 strLiteral.size());
3861 result->EvalData.stringVal[strLiteral.size()] = '\0';
3862 return result.release();
3863 }
3864 }
3865 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3866 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3867 ValueDecl *V = D->getDecl();
3868 if (V->getKind() == Decl::Function) {
3869 std::string strName = V->getNameAsString();
3870 result->EvalType = CXEval_Other;
3871 result->EvalData.stringVal = new char[strName.size() + 1];
3872 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3873 result->EvalData.stringVal[strName.size()] = '\0';
3874 return result.release();
3875 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003876 }
3877
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003878 return nullptr;
3879}
3880
3881CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3882 const Decl *D = getCursorDecl(C);
3883 if (D) {
3884 const Expr *expr = nullptr;
3885 if (auto *Var = dyn_cast<VarDecl>(D)) {
3886 expr = Var->getInit();
3887 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3888 expr = Field->getInClassInitializer();
3889 }
3890 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003891 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3892 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003893 return nullptr;
3894 }
3895
3896 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3897 if (compoundStmt) {
3898 Expr *expr = nullptr;
3899 for (auto *bodyIterator : compoundStmt->body()) {
3900 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3901 break;
3902 }
3903 }
3904 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003905 return const_cast<CXEvalResult>(
3906 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003907 }
3908 return nullptr;
3909}
3910
3911unsigned clang_Cursor_hasAttrs(CXCursor C) {
3912 const Decl *D = getCursorDecl(C);
3913 if (!D) {
3914 return 0;
3915 }
3916
3917 if (D->hasAttrs()) {
3918 return 1;
3919 }
3920
3921 return 0;
3922}
Guy Benyei11169dd2012-12-18 14:30:41 +00003923unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3924 return CXSaveTranslationUnit_None;
3925}
3926
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003927static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3928 const char *FileName,
3929 unsigned options) {
3930 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003931 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3932 setThreadBackgroundPriority();
3933
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003934 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3935 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003936}
3937
3938int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3939 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003940 LOG_FUNC_SECTION {
3941 *Log << TU << ' ' << FileName;
3942 }
3943
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003944 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003945 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003946 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003947 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003948
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003949 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3951 if (!CXXUnit->hasSema())
3952 return CXSaveError_InvalidTU;
3953
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003954 CXSaveError result;
3955 auto SaveTranslationUnitImpl = [=, &result]() {
3956 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3957 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003958
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003959 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003960 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003961
3962 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3963 PrintLibclangResourceUsage(TU);
3964
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003965 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003966 }
3967
3968 // We have an AST that has invalid nodes due to compiler errors.
3969 // Use a crash recovery thread for protection.
3970
3971 llvm::CrashRecoveryContext CRC;
3972
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003973 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003974 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3975 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3976 fprintf(stderr, " 'options' : %d,\n", options);
3977 fprintf(stderr, "}\n");
3978
3979 return CXSaveError_Unknown;
3980
3981 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3982 PrintLibclangResourceUsage(TU);
3983 }
3984
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003985 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003986}
3987
3988void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3989 if (CTUnit) {
3990 // If the translation unit has been marked as unsafe to free, just discard
3991 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003992 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3993 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 return;
3995
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003996 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003997 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3999 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004000 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 delete CTUnit;
4002 }
4003}
4004
Erik Verbruggen346066b2017-05-30 14:25:54 +00004005unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4006 if (CTUnit) {
4007 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4008
4009 if (Unit && Unit->isUnsafeToFree())
4010 return false;
4011
4012 Unit->ResetForParse();
4013 return true;
4014 }
4015
4016 return false;
4017}
4018
Guy Benyei11169dd2012-12-18 14:30:41 +00004019unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4020 return CXReparse_None;
4021}
4022
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004023static CXErrorCode
4024clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4025 ArrayRef<CXUnsavedFile> unsaved_files,
4026 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004027 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004028 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004029 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004030 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004031 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004032
4033 // Reset the associated diagnostics.
4034 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004035 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004036
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004037 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4039 setThreadBackgroundPriority();
4040
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004041 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004043
4044 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4045 new std::vector<ASTUnit::RemappedFile>());
4046
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 // Recover resources if we crash before exiting this function.
4048 llvm::CrashRecoveryContextCleanupRegistrar<
4049 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004050
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004051 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004052 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004053 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004054 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004055 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004056
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004057 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4058 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004059 return CXError_Success;
4060 if (isASTReadError(CXXUnit))
4061 return CXError_ASTReadError;
4062 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004063}
4064
4065int clang_reparseTranslationUnit(CXTranslationUnit TU,
4066 unsigned num_unsaved_files,
4067 struct CXUnsavedFile *unsaved_files,
4068 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004069 LOG_FUNC_SECTION {
4070 *Log << TU;
4071 }
4072
Alp Toker9d85b182014-07-07 01:23:14 +00004073 if (num_unsaved_files && !unsaved_files)
4074 return CXError_InvalidArguments;
4075
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004076 CXErrorCode result;
4077 auto ReparseTranslationUnitImpl = [=, &result]() {
4078 result = clang_reparseTranslationUnit_Impl(
4079 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4080 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004081
Guy Benyei11169dd2012-12-18 14:30:41 +00004082 llvm::CrashRecoveryContext CRC;
4083
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004084 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004085 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004086 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004087 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004088 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4089 PrintLibclangResourceUsage(TU);
4090
Alp Toker5c532982014-07-07 22:42:03 +00004091 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004092}
4093
4094
4095CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004096 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004097 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004098 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004099 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004100
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004101 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004102 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004103}
4104
4105CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004106 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004107 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004108 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004109 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004110
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004111 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004112 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4113}
4114
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004115CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4116 if (isNotUsableTU(CTUnit)) {
4117 LOG_BAD_TU(CTUnit);
4118 return nullptr;
4119 }
4120
4121 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4122 impl->TranslationUnit = CTUnit;
4123 return impl;
4124}
4125
4126CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4127 if (!TargetInfo)
4128 return cxstring::createEmpty();
4129
4130 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4131 assert(!isNotUsableTU(CTUnit) &&
4132 "Unexpected unusable translation unit in TargetInfo");
4133
4134 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4135 std::string Triple =
4136 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4137 return cxstring::createDup(Triple);
4138}
4139
4140int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4141 if (!TargetInfo)
4142 return -1;
4143
4144 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4145 assert(!isNotUsableTU(CTUnit) &&
4146 "Unexpected unusable translation unit in TargetInfo");
4147
4148 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4149 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4150}
4151
4152void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4153 if (!TargetInfo)
4154 return;
4155
4156 delete TargetInfo;
4157}
4158
Guy Benyei11169dd2012-12-18 14:30:41 +00004159//===----------------------------------------------------------------------===//
4160// CXFile Operations.
4161//===----------------------------------------------------------------------===//
4162
Guy Benyei11169dd2012-12-18 14:30:41 +00004163CXString clang_getFileName(CXFile SFile) {
4164 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004165 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004166
4167 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004168 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004169}
4170
4171time_t clang_getFileTime(CXFile SFile) {
4172 if (!SFile)
4173 return 0;
4174
4175 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4176 return FEnt->getModificationTime();
4177}
4178
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004179CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004180 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004181 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004182 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004183 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004184
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004185 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004186
4187 FileManager &FMgr = CXXUnit->getFileManager();
4188 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4189}
4190
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004191const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4192 size_t *size) {
4193 if (isNotUsableTU(TU)) {
4194 LOG_BAD_TU(TU);
4195 return nullptr;
4196 }
4197
4198 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4199 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4200 bool Invalid = true;
4201 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4202 if (Invalid) {
4203 if (size)
4204 *size = 0;
4205 return nullptr;
4206 }
4207 if (size)
4208 *size = buf->getBufferSize();
4209 return buf->getBufferStart();
4210}
4211
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004212unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4213 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004214 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004215 LOG_BAD_TU(TU);
4216 return 0;
4217 }
4218
4219 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004220 return 0;
4221
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004222 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004223 FileEntry *FEnt = static_cast<FileEntry *>(file);
4224 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4225 .isFileMultipleIncludeGuarded(FEnt);
4226}
4227
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004228int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4229 if (!file || !outID)
4230 return 1;
4231
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004232 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004233 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4234 outID->data[0] = ID.getDevice();
4235 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004236 outID->data[2] = FEnt->getModificationTime();
4237 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004238}
4239
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004240int clang_File_isEqual(CXFile file1, CXFile file2) {
4241 if (file1 == file2)
4242 return true;
4243
4244 if (!file1 || !file2)
4245 return false;
4246
4247 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4248 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4249 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4250}
4251
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004252CXString clang_File_tryGetRealPathName(CXFile SFile) {
4253 if (!SFile)
4254 return cxstring::createNull();
4255
4256 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4257 return cxstring::createRef(FEnt->tryGetRealPathName());
4258}
4259
Guy Benyei11169dd2012-12-18 14:30:41 +00004260//===----------------------------------------------------------------------===//
4261// CXCursor Operations.
4262//===----------------------------------------------------------------------===//
4263
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004264static const Decl *getDeclFromExpr(const Stmt *E) {
4265 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 return getDeclFromExpr(CE->getSubExpr());
4267
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004268 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004270 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004272 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004274 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 if (PRE->isExplicitProperty())
4276 return PRE->getExplicitProperty();
4277 // It could be messaging both getter and setter as in:
4278 // ++myobj.myprop;
4279 // in which case prefer to associate the setter since it is less obvious
4280 // from inspecting the source that the setter is going to get called.
4281 if (PRE->isMessagingSetter())
4282 return PRE->getImplicitPropertySetter();
4283 return PRE->getImplicitPropertyGetter();
4284 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004285 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004287 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 if (Expr *Src = OVE->getSourceExpr())
4289 return getDeclFromExpr(Src);
4290
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004291 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004293 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 if (!CE->isElidable())
4295 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004296 if (const CXXInheritedCtorInitExpr *CE =
4297 dyn_cast<CXXInheritedCtorInitExpr>(E))
4298 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004299 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 return OME->getMethodDecl();
4301
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004302 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004304 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4306 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004307 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4309 isa<ParmVarDecl>(SizeOfPack->getPack()))
4310 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004311
4312 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004313}
4314
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004315static SourceLocation getLocationFromExpr(const Expr *E) {
4316 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 return getLocationFromExpr(CE->getSubExpr());
4318
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004319 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004321 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004323 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004325 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004327 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004329 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 return PropRef->getLocation();
4331
4332 return E->getLocStart();
4333}
4334
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004335extern "C" {
4336
Guy Benyei11169dd2012-12-18 14:30:41 +00004337unsigned clang_visitChildren(CXCursor parent,
4338 CXCursorVisitor visitor,
4339 CXClientData client_data) {
4340 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4341 /*VisitPreprocessorLast=*/false);
4342 return CursorVis.VisitChildren(parent);
4343}
4344
4345#ifndef __has_feature
4346#define __has_feature(x) 0
4347#endif
4348#if __has_feature(blocks)
4349typedef enum CXChildVisitResult
4350 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4351
4352static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4353 CXClientData client_data) {
4354 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4355 return block(cursor, parent);
4356}
4357#else
4358// If we are compiled with a compiler that doesn't have native blocks support,
4359// define and call the block manually, so the
4360typedef struct _CXChildVisitResult
4361{
4362 void *isa;
4363 int flags;
4364 int reserved;
4365 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4366 CXCursor);
4367} *CXCursorVisitorBlock;
4368
4369static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4370 CXClientData client_data) {
4371 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4372 return block->invoke(block, cursor, parent);
4373}
4374#endif
4375
4376
4377unsigned clang_visitChildrenWithBlock(CXCursor parent,
4378 CXCursorVisitorBlock block) {
4379 return clang_visitChildren(parent, visitWithBlock, block);
4380}
4381
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004382static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004384 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004385
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004386 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004388 if (const ObjCPropertyImplDecl *PropImpl =
4389 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004391 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004392
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004393 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004395 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004396
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004397 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 }
4399
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004400 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004401 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004402
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004403 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4405 // and returns different names. NamedDecl returns the class name and
4406 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004407 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004408
4409 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004410 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004411
4412 SmallString<1024> S;
4413 llvm::raw_svector_ostream os(S);
4414 ND->printName(os);
4415
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004416 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004417}
4418
4419CXString clang_getCursorSpelling(CXCursor C) {
4420 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004421 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004422
4423 if (clang_isReference(C.kind)) {
4424 switch (C.kind) {
4425 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004426 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004427 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 }
4429 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004430 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004431 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 }
4433 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004434 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004436 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 }
4438 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004439 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004440 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 }
4442 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004443 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 assert(Type && "Missing type decl");
4445
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004446 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 getAsString());
4448 }
4449 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004450 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 assert(Template && "Missing template decl");
4452
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004453 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 }
4455
4456 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004457 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 assert(NS && "Missing namespace decl");
4459
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004460 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 }
4462
4463 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004464 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 assert(Field && "Missing member decl");
4466
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004467 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 }
4469
4470 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004471 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 assert(Label && "Missing label");
4473
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004474 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 }
4476
4477 case CXCursor_OverloadedDeclRef: {
4478 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004479 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4480 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004481 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004482 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004484 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004485 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004486 OverloadedTemplateStorage *Ovl
4487 = Storage.get<OverloadedTemplateStorage*>();
4488 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004489 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004490 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 }
4492
4493 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004494 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 assert(Var && "Missing variable decl");
4496
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004497 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 }
4499
4500 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004501 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 }
4503 }
4504
4505 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004506 const Expr *E = getCursorExpr(C);
4507
4508 if (C.kind == CXCursor_ObjCStringLiteral ||
4509 C.kind == CXCursor_StringLiteral) {
4510 const StringLiteral *SLit;
4511 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4512 SLit = OSL->getString();
4513 } else {
4514 SLit = cast<StringLiteral>(E);
4515 }
4516 SmallString<256> Buf;
4517 llvm::raw_svector_ostream OS(Buf);
4518 SLit->outputString(OS);
4519 return cxstring::createDup(OS.str());
4520 }
4521
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004522 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 if (D)
4524 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004525 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004526 }
4527
4528 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004529 const Stmt *S = getCursorStmt(C);
4530 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004531 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004532
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004533 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 }
4535
4536 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004537 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 ->getNameStart());
4539
4540 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004541 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 ->getNameStart());
4543
4544 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004545 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004546
4547 if (clang_isDeclaration(C.kind))
4548 return getDeclSpelling(getCursorDecl(C));
4549
4550 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004551 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004552 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 }
4554
4555 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004556 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004557 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 }
4559
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004560 if (C.kind == CXCursor_PackedAttr) {
4561 return cxstring::createRef("packed");
4562 }
4563
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004564 if (C.kind == CXCursor_VisibilityAttr) {
4565 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4566 switch (AA->getVisibility()) {
4567 case VisibilityAttr::VisibilityType::Default:
4568 return cxstring::createRef("default");
4569 case VisibilityAttr::VisibilityType::Hidden:
4570 return cxstring::createRef("hidden");
4571 case VisibilityAttr::VisibilityType::Protected:
4572 return cxstring::createRef("protected");
4573 }
4574 llvm_unreachable("unknown visibility type");
4575 }
4576
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004577 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004578}
4579
4580CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4581 unsigned pieceIndex,
4582 unsigned options) {
4583 if (clang_Cursor_isNull(C))
4584 return clang_getNullRange();
4585
4586 ASTContext &Ctx = getCursorContext(C);
4587
4588 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004589 const Stmt *S = getCursorStmt(C);
4590 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 if (pieceIndex > 0)
4592 return clang_getNullRange();
4593 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4594 }
4595
4596 return clang_getNullRange();
4597 }
4598
4599 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004600 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4602 if (pieceIndex >= ME->getNumSelectorLocs())
4603 return clang_getNullRange();
4604 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4605 }
4606 }
4607
4608 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4609 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004610 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4612 if (pieceIndex >= MD->getNumSelectorLocs())
4613 return clang_getNullRange();
4614 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4615 }
4616 }
4617
4618 if (C.kind == CXCursor_ObjCCategoryDecl ||
4619 C.kind == CXCursor_ObjCCategoryImplDecl) {
4620 if (pieceIndex > 0)
4621 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004622 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4624 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004625 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4627 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4628 }
4629
4630 if (C.kind == CXCursor_ModuleImportDecl) {
4631 if (pieceIndex > 0)
4632 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004633 if (const ImportDecl *ImportD =
4634 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4636 if (!Locs.empty())
4637 return cxloc::translateSourceRange(Ctx,
4638 SourceRange(Locs.front(), Locs.back()));
4639 }
4640 return clang_getNullRange();
4641 }
4642
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004643 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004644 C.kind == CXCursor_ConversionFunction ||
4645 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004646 if (pieceIndex > 0)
4647 return clang_getNullRange();
4648 if (const FunctionDecl *FD =
4649 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4650 DeclarationNameInfo FunctionName = FD->getNameInfo();
4651 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4652 }
4653 return clang_getNullRange();
4654 }
4655
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 // FIXME: A CXCursor_InclusionDirective should give the location of the
4657 // filename, but we don't keep track of this.
4658
4659 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4660 // but we don't keep track of this.
4661
4662 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4663 // but we don't keep track of this.
4664
4665 // Default handling, give the location of the cursor.
4666
4667 if (pieceIndex > 0)
4668 return clang_getNullRange();
4669
4670 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4671 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4672 return cxloc::translateSourceRange(Ctx, Loc);
4673}
4674
Eli Bendersky44a206f2014-07-31 18:04:56 +00004675CXString clang_Cursor_getMangling(CXCursor C) {
4676 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4677 return cxstring::createEmpty();
4678
Eli Bendersky44a206f2014-07-31 18:04:56 +00004679 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004680 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004681 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4682 return cxstring::createEmpty();
4683
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004684 ASTContext &Ctx = D->getASTContext();
4685 index::CodegenNameGenerator CGNameGen(Ctx);
4686 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004687}
4688
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004689CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4690 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4691 return nullptr;
4692
4693 const Decl *D = getCursorDecl(C);
4694 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4695 return nullptr;
4696
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004697 ASTContext &Ctx = D->getASTContext();
4698 index::CodegenNameGenerator CGNameGen(Ctx);
4699 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004700 return cxstring::createSet(Manglings);
4701}
4702
Dave Lee1a532c92017-09-22 16:58:57 +00004703CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4704 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4705 return nullptr;
4706
4707 const Decl *D = getCursorDecl(C);
4708 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4709 return nullptr;
4710
4711 ASTContext &Ctx = D->getASTContext();
4712 index::CodegenNameGenerator CGNameGen(Ctx);
4713 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4714 return cxstring::createSet(Manglings);
4715}
4716
Jonathan Coe45ef5032018-01-16 10:19:56 +00004717CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4718 if (clang_Cursor_isNull(C))
4719 return 0;
4720 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4721}
4722
4723void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4724 if (Policy)
4725 delete static_cast<PrintingPolicy *>(Policy);
4726}
4727
4728unsigned
4729clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4730 enum CXPrintingPolicyProperty Property) {
4731 if (!Policy)
4732 return 0;
4733
4734 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4735 switch (Property) {
4736 case CXPrintingPolicy_Indentation:
4737 return P->Indentation;
4738 case CXPrintingPolicy_SuppressSpecifiers:
4739 return P->SuppressSpecifiers;
4740 case CXPrintingPolicy_SuppressTagKeyword:
4741 return P->SuppressTagKeyword;
4742 case CXPrintingPolicy_IncludeTagDefinition:
4743 return P->IncludeTagDefinition;
4744 case CXPrintingPolicy_SuppressScope:
4745 return P->SuppressScope;
4746 case CXPrintingPolicy_SuppressUnwrittenScope:
4747 return P->SuppressUnwrittenScope;
4748 case CXPrintingPolicy_SuppressInitializers:
4749 return P->SuppressInitializers;
4750 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4751 return P->ConstantArraySizeAsWritten;
4752 case CXPrintingPolicy_AnonymousTagLocations:
4753 return P->AnonymousTagLocations;
4754 case CXPrintingPolicy_SuppressStrongLifetime:
4755 return P->SuppressStrongLifetime;
4756 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4757 return P->SuppressLifetimeQualifiers;
4758 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4759 return P->SuppressTemplateArgsInCXXConstructors;
4760 case CXPrintingPolicy_Bool:
4761 return P->Bool;
4762 case CXPrintingPolicy_Restrict:
4763 return P->Restrict;
4764 case CXPrintingPolicy_Alignof:
4765 return P->Alignof;
4766 case CXPrintingPolicy_UnderscoreAlignof:
4767 return P->UnderscoreAlignof;
4768 case CXPrintingPolicy_UseVoidForZeroParams:
4769 return P->UseVoidForZeroParams;
4770 case CXPrintingPolicy_TerseOutput:
4771 return P->TerseOutput;
4772 case CXPrintingPolicy_PolishForDeclaration:
4773 return P->PolishForDeclaration;
4774 case CXPrintingPolicy_Half:
4775 return P->Half;
4776 case CXPrintingPolicy_MSWChar:
4777 return P->MSWChar;
4778 case CXPrintingPolicy_IncludeNewlines:
4779 return P->IncludeNewlines;
4780 case CXPrintingPolicy_MSVCFormatting:
4781 return P->MSVCFormatting;
4782 case CXPrintingPolicy_ConstantsAsWritten:
4783 return P->ConstantsAsWritten;
4784 case CXPrintingPolicy_SuppressImplicitBase:
4785 return P->SuppressImplicitBase;
4786 case CXPrintingPolicy_FullyQualifiedName:
4787 return P->FullyQualifiedName;
4788 }
4789
4790 assert(false && "Invalid CXPrintingPolicyProperty");
4791 return 0;
4792}
4793
4794void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4795 enum CXPrintingPolicyProperty Property,
4796 unsigned Value) {
4797 if (!Policy)
4798 return;
4799
4800 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4801 switch (Property) {
4802 case CXPrintingPolicy_Indentation:
4803 P->Indentation = Value;
4804 return;
4805 case CXPrintingPolicy_SuppressSpecifiers:
4806 P->SuppressSpecifiers = Value;
4807 return;
4808 case CXPrintingPolicy_SuppressTagKeyword:
4809 P->SuppressTagKeyword = Value;
4810 return;
4811 case CXPrintingPolicy_IncludeTagDefinition:
4812 P->IncludeTagDefinition = Value;
4813 return;
4814 case CXPrintingPolicy_SuppressScope:
4815 P->SuppressScope = Value;
4816 return;
4817 case CXPrintingPolicy_SuppressUnwrittenScope:
4818 P->SuppressUnwrittenScope = Value;
4819 return;
4820 case CXPrintingPolicy_SuppressInitializers:
4821 P->SuppressInitializers = Value;
4822 return;
4823 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4824 P->ConstantArraySizeAsWritten = Value;
4825 return;
4826 case CXPrintingPolicy_AnonymousTagLocations:
4827 P->AnonymousTagLocations = Value;
4828 return;
4829 case CXPrintingPolicy_SuppressStrongLifetime:
4830 P->SuppressStrongLifetime = Value;
4831 return;
4832 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4833 P->SuppressLifetimeQualifiers = Value;
4834 return;
4835 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4836 P->SuppressTemplateArgsInCXXConstructors = Value;
4837 return;
4838 case CXPrintingPolicy_Bool:
4839 P->Bool = Value;
4840 return;
4841 case CXPrintingPolicy_Restrict:
4842 P->Restrict = Value;
4843 return;
4844 case CXPrintingPolicy_Alignof:
4845 P->Alignof = Value;
4846 return;
4847 case CXPrintingPolicy_UnderscoreAlignof:
4848 P->UnderscoreAlignof = Value;
4849 return;
4850 case CXPrintingPolicy_UseVoidForZeroParams:
4851 P->UseVoidForZeroParams = Value;
4852 return;
4853 case CXPrintingPolicy_TerseOutput:
4854 P->TerseOutput = Value;
4855 return;
4856 case CXPrintingPolicy_PolishForDeclaration:
4857 P->PolishForDeclaration = Value;
4858 return;
4859 case CXPrintingPolicy_Half:
4860 P->Half = Value;
4861 return;
4862 case CXPrintingPolicy_MSWChar:
4863 P->MSWChar = Value;
4864 return;
4865 case CXPrintingPolicy_IncludeNewlines:
4866 P->IncludeNewlines = Value;
4867 return;
4868 case CXPrintingPolicy_MSVCFormatting:
4869 P->MSVCFormatting = Value;
4870 return;
4871 case CXPrintingPolicy_ConstantsAsWritten:
4872 P->ConstantsAsWritten = Value;
4873 return;
4874 case CXPrintingPolicy_SuppressImplicitBase:
4875 P->SuppressImplicitBase = Value;
4876 return;
4877 case CXPrintingPolicy_FullyQualifiedName:
4878 P->FullyQualifiedName = Value;
4879 return;
4880 }
4881
4882 assert(false && "Invalid CXPrintingPolicyProperty");
4883}
4884
4885CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4886 if (clang_Cursor_isNull(C))
4887 return cxstring::createEmpty();
4888
4889 if (clang_isDeclaration(C.kind)) {
4890 const Decl *D = getCursorDecl(C);
4891 if (!D)
4892 return cxstring::createEmpty();
4893
4894 SmallString<128> Str;
4895 llvm::raw_svector_ostream OS(Str);
4896 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4897 D->print(OS, UserPolicy ? *UserPolicy
4898 : getCursorContext(C).getPrintingPolicy());
4899
4900 return cxstring::createDup(OS.str());
4901 }
4902
4903 return cxstring::createEmpty();
4904}
4905
Guy Benyei11169dd2012-12-18 14:30:41 +00004906CXString clang_getCursorDisplayName(CXCursor C) {
4907 if (!clang_isDeclaration(C.kind))
4908 return clang_getCursorSpelling(C);
4909
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004910 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004912 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004913
4914 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004915 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004916 D = FunTmpl->getTemplatedDecl();
4917
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004918 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 SmallString<64> Str;
4920 llvm::raw_svector_ostream OS(Str);
4921 OS << *Function;
4922 if (Function->getPrimaryTemplate())
4923 OS << "<>";
4924 OS << "(";
4925 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4926 if (I)
4927 OS << ", ";
4928 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4929 }
4930
4931 if (Function->isVariadic()) {
4932 if (Function->getNumParams())
4933 OS << ", ";
4934 OS << "...";
4935 }
4936 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004937 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 }
4939
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004940 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004941 SmallString<64> Str;
4942 llvm::raw_svector_ostream OS(Str);
4943 OS << *ClassTemplate;
4944 OS << "<";
4945 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4946 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4947 if (I)
4948 OS << ", ";
4949
4950 NamedDecl *Param = Params->getParam(I);
4951 if (Param->getIdentifier()) {
4952 OS << Param->getIdentifier()->getName();
4953 continue;
4954 }
4955
4956 // There is no parameter name, which makes this tricky. Try to come up
4957 // with something useful that isn't too long.
4958 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4959 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4960 else if (NonTypeTemplateParmDecl *NTTP
4961 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4962 OS << NTTP->getType().getAsString(Policy);
4963 else
4964 OS << "template<...> class";
4965 }
4966
4967 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004968 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004969 }
4970
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004971 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004972 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4973 // If the type was explicitly written, use that.
4974 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004975 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004976
Benjamin Kramer9170e912013-02-22 15:46:01 +00004977 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004978 llvm::raw_svector_ostream OS(Str);
4979 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00004980 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
4981 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004982 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 }
4984
4985 return clang_getCursorSpelling(C);
4986}
4987
4988CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4989 switch (Kind) {
4990 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004991 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004992 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004993 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004994 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004995 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004996 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004997 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004999 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005000 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005001 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005002 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005003 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005005 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005007 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005008 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005009 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005011 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005013 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005015 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005017 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005019 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005021 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005023 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005025 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005027 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005029 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005031 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005033 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005035 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005037 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005039 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005041 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005043 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005045 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005047 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005049 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005051 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005053 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005055 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005057 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005059 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005061 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005063 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005065 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005067 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005068 case CXCursor_OMPArraySectionExpr:
5069 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005071 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005073 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005075 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005077 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005079 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005081 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005083 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005085 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005087 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005089 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005091 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005093 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005097 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005101 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005120 case CXCursor_ObjCAvailabilityCheckExpr:
5121 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005122 case CXCursor_ObjCSelfExpr:
5123 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005212 case CXCursor_SEHLeaveStmt:
5213 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005242 case CXCursor_PackedAttr:
5243 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005244 case CXCursor_PureAttr:
5245 return cxstring::createRef("attribute(pure)");
5246 case CXCursor_ConstAttr:
5247 return cxstring::createRef("attribute(const)");
5248 case CXCursor_NoDuplicateAttr:
5249 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005250 case CXCursor_CUDAConstantAttr:
5251 return cxstring::createRef("attribute(constant)");
5252 case CXCursor_CUDADeviceAttr:
5253 return cxstring::createRef("attribute(device)");
5254 case CXCursor_CUDAGlobalAttr:
5255 return cxstring::createRef("attribute(global)");
5256 case CXCursor_CUDAHostAttr:
5257 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005258 case CXCursor_CUDASharedAttr:
5259 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005260 case CXCursor_VisibilityAttr:
5261 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005262 case CXCursor_DLLExport:
5263 return cxstring::createRef("attribute(dllexport)");
5264 case CXCursor_DLLImport:
5265 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005277 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005297 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005307 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005309 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005311 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005313 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005314 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005315 return cxstring::createRef("OMPParallelDirective");
5316 case CXCursor_OMPSimdDirective:
5317 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005318 case CXCursor_OMPForDirective:
5319 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005320 case CXCursor_OMPForSimdDirective:
5321 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005322 case CXCursor_OMPSectionsDirective:
5323 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005324 case CXCursor_OMPSectionDirective:
5325 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005326 case CXCursor_OMPSingleDirective:
5327 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005328 case CXCursor_OMPMasterDirective:
5329 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005330 case CXCursor_OMPCriticalDirective:
5331 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005332 case CXCursor_OMPParallelForDirective:
5333 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005334 case CXCursor_OMPParallelForSimdDirective:
5335 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005336 case CXCursor_OMPParallelSectionsDirective:
5337 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005338 case CXCursor_OMPTaskDirective:
5339 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005340 case CXCursor_OMPTaskyieldDirective:
5341 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005342 case CXCursor_OMPBarrierDirective:
5343 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005344 case CXCursor_OMPTaskwaitDirective:
5345 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005346 case CXCursor_OMPTaskgroupDirective:
5347 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005348 case CXCursor_OMPFlushDirective:
5349 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005350 case CXCursor_OMPOrderedDirective:
5351 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005352 case CXCursor_OMPAtomicDirective:
5353 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005354 case CXCursor_OMPTargetDirective:
5355 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005356 case CXCursor_OMPTargetDataDirective:
5357 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005358 case CXCursor_OMPTargetEnterDataDirective:
5359 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005360 case CXCursor_OMPTargetExitDataDirective:
5361 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005362 case CXCursor_OMPTargetParallelDirective:
5363 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005364 case CXCursor_OMPTargetParallelForDirective:
5365 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005366 case CXCursor_OMPTargetUpdateDirective:
5367 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005368 case CXCursor_OMPTeamsDirective:
5369 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005370 case CXCursor_OMPCancellationPointDirective:
5371 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005372 case CXCursor_OMPCancelDirective:
5373 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005374 case CXCursor_OMPTaskLoopDirective:
5375 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005376 case CXCursor_OMPTaskLoopSimdDirective:
5377 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005378 case CXCursor_OMPDistributeDirective:
5379 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005380 case CXCursor_OMPDistributeParallelForDirective:
5381 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005382 case CXCursor_OMPDistributeParallelForSimdDirective:
5383 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005384 case CXCursor_OMPDistributeSimdDirective:
5385 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005386 case CXCursor_OMPTargetParallelForSimdDirective:
5387 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005388 case CXCursor_OMPTargetSimdDirective:
5389 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005390 case CXCursor_OMPTeamsDistributeDirective:
5391 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005392 case CXCursor_OMPTeamsDistributeSimdDirective:
5393 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005394 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5395 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005396 case CXCursor_OMPTeamsDistributeParallelForDirective:
5397 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005398 case CXCursor_OMPTargetTeamsDirective:
5399 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005400 case CXCursor_OMPTargetTeamsDistributeDirective:
5401 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005402 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5403 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005404 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5405 return cxstring::createRef(
5406 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005407 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5408 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005409 case CXCursor_OverloadCandidate:
5410 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005411 case CXCursor_TypeAliasTemplateDecl:
5412 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005413 case CXCursor_StaticAssert:
5414 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005415 case CXCursor_FriendDecl:
5416 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005417 }
5418
5419 llvm_unreachable("Unhandled CXCursorKind");
5420}
5421
5422struct GetCursorData {
5423 SourceLocation TokenBeginLoc;
5424 bool PointsAtMacroArgExpansion;
5425 bool VisitedObjCPropertyImplDecl;
5426 SourceLocation VisitedDeclaratorDeclStartLoc;
5427 CXCursor &BestCursor;
5428
5429 GetCursorData(SourceManager &SM,
5430 SourceLocation tokenBegin, CXCursor &outputCursor)
5431 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5432 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5433 VisitedObjCPropertyImplDecl = false;
5434 }
5435};
5436
5437static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5438 CXCursor parent,
5439 CXClientData client_data) {
5440 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5441 CXCursor *BestCursor = &Data->BestCursor;
5442
5443 // If we point inside a macro argument we should provide info of what the
5444 // token is so use the actual cursor, don't replace it with a macro expansion
5445 // cursor.
5446 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5447 return CXChildVisit_Recurse;
5448
5449 if (clang_isDeclaration(cursor.kind)) {
5450 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005451 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5453 if (MD->isImplicit())
5454 return CXChildVisit_Break;
5455
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005456 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005457 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5458 // Check that when we have multiple @class references in the same line,
5459 // that later ones do not override the previous ones.
5460 // If we have:
5461 // @class Foo, Bar;
5462 // source ranges for both start at '@', so 'Bar' will end up overriding
5463 // 'Foo' even though the cursor location was at 'Foo'.
5464 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5465 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005466 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005467 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5468 if (PrevID != ID &&
5469 !PrevID->isThisDeclarationADefinition() &&
5470 !ID->isThisDeclarationADefinition())
5471 return CXChildVisit_Break;
5472 }
5473
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005474 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005475 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5476 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5477 // Check that when we have multiple declarators in the same line,
5478 // that later ones do not override the previous ones.
5479 // If we have:
5480 // int Foo, Bar;
5481 // source ranges for both start at 'int', so 'Bar' will end up overriding
5482 // 'Foo' even though the cursor location was at 'Foo'.
5483 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5484 return CXChildVisit_Break;
5485 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5486
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005487 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005488 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5489 (void)PropImp;
5490 // Check that when we have multiple @synthesize in the same line,
5491 // that later ones do not override the previous ones.
5492 // If we have:
5493 // @synthesize Foo, Bar;
5494 // source ranges for both start at '@', so 'Bar' will end up overriding
5495 // 'Foo' even though the cursor location was at 'Foo'.
5496 if (Data->VisitedObjCPropertyImplDecl)
5497 return CXChildVisit_Break;
5498 Data->VisitedObjCPropertyImplDecl = true;
5499 }
5500 }
5501
5502 if (clang_isExpression(cursor.kind) &&
5503 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005504 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005505 // Avoid having the cursor of an expression replace the declaration cursor
5506 // when the expression source range overlaps the declaration range.
5507 // This can happen for C++ constructor expressions whose range generally
5508 // include the variable declaration, e.g.:
5509 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5510 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5511 D->getLocation() == Data->TokenBeginLoc)
5512 return CXChildVisit_Break;
5513 }
5514 }
5515
5516 // If our current best cursor is the construction of a temporary object,
5517 // don't replace that cursor with a type reference, because we want
5518 // clang_getCursor() to point at the constructor.
5519 if (clang_isExpression(BestCursor->kind) &&
5520 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5521 cursor.kind == CXCursor_TypeRef) {
5522 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5523 // as having the actual point on the type reference.
5524 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5525 return CXChildVisit_Recurse;
5526 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005527
5528 // If we already have an Objective-C superclass reference, don't
5529 // update it further.
5530 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5531 return CXChildVisit_Break;
5532
Guy Benyei11169dd2012-12-18 14:30:41 +00005533 *BestCursor = cursor;
5534 return CXChildVisit_Recurse;
5535}
5536
5537CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005538 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005539 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005540 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005541 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005542
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005543 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005544 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5545
5546 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5547 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5548
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005549 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005550 CXFile SearchFile;
5551 unsigned SearchLine, SearchColumn;
5552 CXFile ResultFile;
5553 unsigned ResultLine, ResultColumn;
5554 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5555 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5556 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005557
5558 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5559 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005560 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005561 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005562 SearchFileName = clang_getFileName(SearchFile);
5563 ResultFileName = clang_getFileName(ResultFile);
5564 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5565 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005566 *Log << llvm::format("(%s:%d:%d) = %s",
5567 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5568 clang_getCString(KindSpelling))
5569 << llvm::format("(%s:%d:%d):%s%s",
5570 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5571 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005572 clang_disposeString(SearchFileName);
5573 clang_disposeString(ResultFileName);
5574 clang_disposeString(KindSpelling);
5575 clang_disposeString(USR);
5576
5577 CXCursor Definition = clang_getCursorDefinition(Result);
5578 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5579 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5580 CXString DefinitionKindSpelling
5581 = clang_getCursorKindSpelling(Definition.kind);
5582 CXFile DefinitionFile;
5583 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005584 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005585 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005586 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005587 *Log << llvm::format(" -> %s(%s:%d:%d)",
5588 clang_getCString(DefinitionKindSpelling),
5589 clang_getCString(DefinitionFileName),
5590 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005591 clang_disposeString(DefinitionFileName);
5592 clang_disposeString(DefinitionKindSpelling);
5593 }
5594 }
5595
5596 return Result;
5597}
5598
5599CXCursor clang_getNullCursor(void) {
5600 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5601}
5602
5603unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005604 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5605 // can't set consistently. For example, when visiting a DeclStmt we will set
5606 // it but we don't set it on the result of clang_getCursorDefinition for
5607 // a reference of the same declaration.
5608 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5609 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5610 // to provide that kind of info.
5611 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005612 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005613 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005614 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005615
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 return X == Y;
5617}
5618
5619unsigned clang_hashCursor(CXCursor C) {
5620 unsigned Index = 0;
5621 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5622 Index = 1;
5623
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005624 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005625 std::make_pair(C.kind, C.data[Index]));
5626}
5627
5628unsigned clang_isInvalid(enum CXCursorKind K) {
5629 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5630}
5631
5632unsigned clang_isDeclaration(enum CXCursorKind K) {
5633 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005634 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5635}
5636
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005637unsigned clang_isInvalidDeclaration(CXCursor C) {
5638 if (clang_isDeclaration(C.kind)) {
5639 if (const Decl *D = getCursorDecl(C))
5640 return D->isInvalidDecl();
5641 }
5642
5643 return 0;
5644}
5645
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005646unsigned clang_isReference(enum CXCursorKind K) {
5647 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5648}
Guy Benyei11169dd2012-12-18 14:30:41 +00005649
5650unsigned clang_isExpression(enum CXCursorKind K) {
5651 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5652}
5653
5654unsigned clang_isStatement(enum CXCursorKind K) {
5655 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5656}
5657
5658unsigned clang_isAttribute(enum CXCursorKind K) {
5659 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5660}
5661
5662unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5663 return K == CXCursor_TranslationUnit;
5664}
5665
5666unsigned clang_isPreprocessing(enum CXCursorKind K) {
5667 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5668}
5669
5670unsigned clang_isUnexposed(enum CXCursorKind K) {
5671 switch (K) {
5672 case CXCursor_UnexposedDecl:
5673 case CXCursor_UnexposedExpr:
5674 case CXCursor_UnexposedStmt:
5675 case CXCursor_UnexposedAttr:
5676 return true;
5677 default:
5678 return false;
5679 }
5680}
5681
5682CXCursorKind clang_getCursorKind(CXCursor C) {
5683 return C.kind;
5684}
5685
5686CXSourceLocation clang_getCursorLocation(CXCursor C) {
5687 if (clang_isReference(C.kind)) {
5688 switch (C.kind) {
5689 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005690 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005691 = getCursorObjCSuperClassRef(C);
5692 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5693 }
5694
5695 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005696 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005697 = getCursorObjCProtocolRef(C);
5698 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5699 }
5700
5701 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005702 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005703 = getCursorObjCClassRef(C);
5704 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5705 }
5706
5707 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005708 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005709 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5710 }
5711
5712 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005713 std::pair<const TemplateDecl *, SourceLocation> P =
5714 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005715 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5716 }
5717
5718 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005719 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005720 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5721 }
5722
5723 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005724 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005725 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5726 }
5727
5728 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005729 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005730 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5731 }
5732
5733 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005734 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005735 if (!BaseSpec)
5736 return clang_getNullLocation();
5737
5738 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5739 return cxloc::translateSourceLocation(getCursorContext(C),
5740 TSInfo->getTypeLoc().getBeginLoc());
5741
5742 return cxloc::translateSourceLocation(getCursorContext(C),
5743 BaseSpec->getLocStart());
5744 }
5745
5746 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005747 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005748 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5749 }
5750
5751 case CXCursor_OverloadedDeclRef:
5752 return cxloc::translateSourceLocation(getCursorContext(C),
5753 getCursorOverloadedDeclRef(C).second);
5754
5755 default:
5756 // FIXME: Need a way to enumerate all non-reference cases.
5757 llvm_unreachable("Missed a reference kind");
5758 }
5759 }
5760
5761 if (clang_isExpression(C.kind))
5762 return cxloc::translateSourceLocation(getCursorContext(C),
5763 getLocationFromExpr(getCursorExpr(C)));
5764
5765 if (clang_isStatement(C.kind))
5766 return cxloc::translateSourceLocation(getCursorContext(C),
5767 getCursorStmt(C)->getLocStart());
5768
5769 if (C.kind == CXCursor_PreprocessingDirective) {
5770 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5771 return cxloc::translateSourceLocation(getCursorContext(C), L);
5772 }
5773
5774 if (C.kind == CXCursor_MacroExpansion) {
5775 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005776 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005777 return cxloc::translateSourceLocation(getCursorContext(C), L);
5778 }
5779
5780 if (C.kind == CXCursor_MacroDefinition) {
5781 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5782 return cxloc::translateSourceLocation(getCursorContext(C), L);
5783 }
5784
5785 if (C.kind == CXCursor_InclusionDirective) {
5786 SourceLocation L
5787 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5788 return cxloc::translateSourceLocation(getCursorContext(C), L);
5789 }
5790
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005791 if (clang_isAttribute(C.kind)) {
5792 SourceLocation L
5793 = cxcursor::getCursorAttr(C)->getLocation();
5794 return cxloc::translateSourceLocation(getCursorContext(C), L);
5795 }
5796
Guy Benyei11169dd2012-12-18 14:30:41 +00005797 if (!clang_isDeclaration(C.kind))
5798 return clang_getNullLocation();
5799
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005800 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005801 if (!D)
5802 return clang_getNullLocation();
5803
5804 SourceLocation Loc = D->getLocation();
5805 // FIXME: Multiple variables declared in a single declaration
5806 // currently lack the information needed to correctly determine their
5807 // ranges when accounting for the type-specifier. We use context
5808 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5809 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005810 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005811 if (!cxcursor::isFirstInDeclGroup(C))
5812 Loc = VD->getLocation();
5813 }
5814
5815 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005816 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005817 Loc = MD->getSelectorStartLoc();
5818
5819 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5820}
5821
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005822} // end extern "C"
5823
Guy Benyei11169dd2012-12-18 14:30:41 +00005824CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5825 assert(TU);
5826
5827 // Guard against an invalid SourceLocation, or we may assert in one
5828 // of the following calls.
5829 if (SLoc.isInvalid())
5830 return clang_getNullCursor();
5831
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005832 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005833
5834 // Translate the given source location to make it point at the beginning of
5835 // the token under the cursor.
5836 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5837 CXXUnit->getASTContext().getLangOpts());
5838
5839 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5840 if (SLoc.isValid()) {
5841 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5842 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5843 /*VisitPreprocessorLast=*/true,
5844 /*VisitIncludedEntities=*/false,
5845 SourceLocation(SLoc));
5846 CursorVis.visitFileRegion();
5847 }
5848
5849 return Result;
5850}
5851
5852static SourceRange getRawCursorExtent(CXCursor C) {
5853 if (clang_isReference(C.kind)) {
5854 switch (C.kind) {
5855 case CXCursor_ObjCSuperClassRef:
5856 return getCursorObjCSuperClassRef(C).second;
5857
5858 case CXCursor_ObjCProtocolRef:
5859 return getCursorObjCProtocolRef(C).second;
5860
5861 case CXCursor_ObjCClassRef:
5862 return getCursorObjCClassRef(C).second;
5863
5864 case CXCursor_TypeRef:
5865 return getCursorTypeRef(C).second;
5866
5867 case CXCursor_TemplateRef:
5868 return getCursorTemplateRef(C).second;
5869
5870 case CXCursor_NamespaceRef:
5871 return getCursorNamespaceRef(C).second;
5872
5873 case CXCursor_MemberRef:
5874 return getCursorMemberRef(C).second;
5875
5876 case CXCursor_CXXBaseSpecifier:
5877 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5878
5879 case CXCursor_LabelRef:
5880 return getCursorLabelRef(C).second;
5881
5882 case CXCursor_OverloadedDeclRef:
5883 return getCursorOverloadedDeclRef(C).second;
5884
5885 case CXCursor_VariableRef:
5886 return getCursorVariableRef(C).second;
5887
5888 default:
5889 // FIXME: Need a way to enumerate all non-reference cases.
5890 llvm_unreachable("Missed a reference kind");
5891 }
5892 }
5893
5894 if (clang_isExpression(C.kind))
5895 return getCursorExpr(C)->getSourceRange();
5896
5897 if (clang_isStatement(C.kind))
5898 return getCursorStmt(C)->getSourceRange();
5899
5900 if (clang_isAttribute(C.kind))
5901 return getCursorAttr(C)->getRange();
5902
5903 if (C.kind == CXCursor_PreprocessingDirective)
5904 return cxcursor::getCursorPreprocessingDirective(C);
5905
5906 if (C.kind == CXCursor_MacroExpansion) {
5907 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005908 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005909 return TU->mapRangeFromPreamble(Range);
5910 }
5911
5912 if (C.kind == CXCursor_MacroDefinition) {
5913 ASTUnit *TU = getCursorASTUnit(C);
5914 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5915 return TU->mapRangeFromPreamble(Range);
5916 }
5917
5918 if (C.kind == CXCursor_InclusionDirective) {
5919 ASTUnit *TU = getCursorASTUnit(C);
5920 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5921 return TU->mapRangeFromPreamble(Range);
5922 }
5923
5924 if (C.kind == CXCursor_TranslationUnit) {
5925 ASTUnit *TU = getCursorASTUnit(C);
5926 FileID MainID = TU->getSourceManager().getMainFileID();
5927 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5928 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5929 return SourceRange(Start, End);
5930 }
5931
5932 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005933 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005934 if (!D)
5935 return SourceRange();
5936
5937 SourceRange R = D->getSourceRange();
5938 // FIXME: Multiple variables declared in a single declaration
5939 // currently lack the information needed to correctly determine their
5940 // ranges when accounting for the type-specifier. We use context
5941 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5942 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005943 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005944 if (!cxcursor::isFirstInDeclGroup(C))
5945 R.setBegin(VD->getLocation());
5946 }
5947 return R;
5948 }
5949 return SourceRange();
5950}
5951
5952/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5953/// the decl-specifier-seq for declarations.
5954static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5955 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005956 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005957 if (!D)
5958 return SourceRange();
5959
5960 SourceRange R = D->getSourceRange();
5961
5962 // Adjust the start of the location for declarations preceded by
5963 // declaration specifiers.
5964 SourceLocation StartLoc;
5965 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5966 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5967 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005968 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005969 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5970 StartLoc = TI->getTypeLoc().getLocStart();
5971 }
5972
5973 if (StartLoc.isValid() && R.getBegin().isValid() &&
5974 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5975 R.setBegin(StartLoc);
5976
5977 // FIXME: Multiple variables declared in a single declaration
5978 // currently lack the information needed to correctly determine their
5979 // ranges when accounting for the type-specifier. We use context
5980 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5981 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005982 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005983 if (!cxcursor::isFirstInDeclGroup(C))
5984 R.setBegin(VD->getLocation());
5985 }
5986
5987 return R;
5988 }
5989
5990 return getRawCursorExtent(C);
5991}
5992
Guy Benyei11169dd2012-12-18 14:30:41 +00005993CXSourceRange clang_getCursorExtent(CXCursor C) {
5994 SourceRange R = getRawCursorExtent(C);
5995 if (R.isInvalid())
5996 return clang_getNullRange();
5997
5998 return cxloc::translateSourceRange(getCursorContext(C), R);
5999}
6000
6001CXCursor clang_getCursorReferenced(CXCursor C) {
6002 if (clang_isInvalid(C.kind))
6003 return clang_getNullCursor();
6004
6005 CXTranslationUnit tu = getCursorTU(C);
6006 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006007 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006008 if (!D)
6009 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006010 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006011 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006012 if (const ObjCPropertyImplDecl *PropImpl =
6013 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006014 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6015 return MakeCXCursor(Property, tu);
6016
6017 return C;
6018 }
6019
6020 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006021 const Expr *E = getCursorExpr(C);
6022 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006023 if (D) {
6024 CXCursor declCursor = MakeCXCursor(D, tu);
6025 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6026 declCursor);
6027 return declCursor;
6028 }
6029
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006030 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006031 return MakeCursorOverloadedDeclRef(Ovl, tu);
6032
6033 return clang_getNullCursor();
6034 }
6035
6036 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006037 const Stmt *S = getCursorStmt(C);
6038 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 if (LabelDecl *label = Goto->getLabel())
6040 if (LabelStmt *labelS = label->getStmt())
6041 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6042
6043 return clang_getNullCursor();
6044 }
Richard Smith66a81862015-05-04 02:25:31 +00006045
Guy Benyei11169dd2012-12-18 14:30:41 +00006046 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006047 if (const MacroDefinitionRecord *Def =
6048 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006049 return MakeMacroDefinitionCursor(Def, tu);
6050 }
6051
6052 if (!clang_isReference(C.kind))
6053 return clang_getNullCursor();
6054
6055 switch (C.kind) {
6056 case CXCursor_ObjCSuperClassRef:
6057 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6058
6059 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006060 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6061 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006062 return MakeCXCursor(Def, tu);
6063
6064 return MakeCXCursor(Prot, tu);
6065 }
6066
6067 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006068 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6069 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006070 return MakeCXCursor(Def, tu);
6071
6072 return MakeCXCursor(Class, tu);
6073 }
6074
6075 case CXCursor_TypeRef:
6076 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6077
6078 case CXCursor_TemplateRef:
6079 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6080
6081 case CXCursor_NamespaceRef:
6082 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6083
6084 case CXCursor_MemberRef:
6085 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6086
6087 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006088 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6090 tu ));
6091 }
6092
6093 case CXCursor_LabelRef:
6094 // FIXME: We end up faking the "parent" declaration here because we
6095 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006096 return MakeCXCursor(getCursorLabelRef(C).first,
6097 cxtu::getASTUnit(tu)->getASTContext()
6098 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006099 tu);
6100
6101 case CXCursor_OverloadedDeclRef:
6102 return C;
6103
6104 case CXCursor_VariableRef:
6105 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6106
6107 default:
6108 // We would prefer to enumerate all non-reference cursor kinds here.
6109 llvm_unreachable("Unhandled reference cursor kind");
6110 }
6111}
6112
6113CXCursor clang_getCursorDefinition(CXCursor C) {
6114 if (clang_isInvalid(C.kind))
6115 return clang_getNullCursor();
6116
6117 CXTranslationUnit TU = getCursorTU(C);
6118
6119 bool WasReference = false;
6120 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6121 C = clang_getCursorReferenced(C);
6122 WasReference = true;
6123 }
6124
6125 if (C.kind == CXCursor_MacroExpansion)
6126 return clang_getCursorReferenced(C);
6127
6128 if (!clang_isDeclaration(C.kind))
6129 return clang_getNullCursor();
6130
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006131 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006132 if (!D)
6133 return clang_getNullCursor();
6134
6135 switch (D->getKind()) {
6136 // Declaration kinds that don't really separate the notions of
6137 // declaration and definition.
6138 case Decl::Namespace:
6139 case Decl::Typedef:
6140 case Decl::TypeAlias:
6141 case Decl::TypeAliasTemplate:
6142 case Decl::TemplateTypeParm:
6143 case Decl::EnumConstant:
6144 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006145 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006146 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006147 case Decl::IndirectField:
6148 case Decl::ObjCIvar:
6149 case Decl::ObjCAtDefsField:
6150 case Decl::ImplicitParam:
6151 case Decl::ParmVar:
6152 case Decl::NonTypeTemplateParm:
6153 case Decl::TemplateTemplateParm:
6154 case Decl::ObjCCategoryImpl:
6155 case Decl::ObjCImplementation:
6156 case Decl::AccessSpec:
6157 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006158 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006159 case Decl::ObjCPropertyImpl:
6160 case Decl::FileScopeAsm:
6161 case Decl::StaticAssert:
6162 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006163 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006164 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 case Decl::Label: // FIXME: Is this right??
6166 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006167 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006168 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006169 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006170 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006171 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006172 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006173 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006174 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006175 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006176 return C;
6177
6178 // Declaration kinds that don't make any sense here, but are
6179 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006180 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006182 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006183 break;
6184
6185 // Declaration kinds for which the definition is not resolvable.
6186 case Decl::UnresolvedUsingTypename:
6187 case Decl::UnresolvedUsingValue:
6188 break;
6189
6190 case Decl::UsingDirective:
6191 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6192 TU);
6193
6194 case Decl::NamespaceAlias:
6195 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6196
6197 case Decl::Enum:
6198 case Decl::Record:
6199 case Decl::CXXRecord:
6200 case Decl::ClassTemplateSpecialization:
6201 case Decl::ClassTemplatePartialSpecialization:
6202 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6203 return MakeCXCursor(Def, TU);
6204 return clang_getNullCursor();
6205
6206 case Decl::Function:
6207 case Decl::CXXMethod:
6208 case Decl::CXXConstructor:
6209 case Decl::CXXDestructor:
6210 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006211 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006212 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006213 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 return clang_getNullCursor();
6215 }
6216
Larisse Voufo39a1e502013-08-06 01:03:05 +00006217 case Decl::Var:
6218 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006219 case Decl::VarTemplatePartialSpecialization:
6220 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006221 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006222 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006223 return MakeCXCursor(Def, TU);
6224 return clang_getNullCursor();
6225 }
6226
6227 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006228 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6230 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6231 return clang_getNullCursor();
6232 }
6233
6234 case Decl::ClassTemplate: {
6235 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6236 ->getDefinition())
6237 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6238 TU);
6239 return clang_getNullCursor();
6240 }
6241
Larisse Voufo39a1e502013-08-06 01:03:05 +00006242 case Decl::VarTemplate: {
6243 if (VarDecl *Def =
6244 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6245 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6246 return clang_getNullCursor();
6247 }
6248
Guy Benyei11169dd2012-12-18 14:30:41 +00006249 case Decl::Using:
6250 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6251 D->getLocation(), TU);
6252
6253 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006254 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006255 return clang_getCursorDefinition(
6256 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6257 TU));
6258
6259 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006260 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006261 if (Method->isThisDeclarationADefinition())
6262 return C;
6263
6264 // Dig out the method definition in the associated
6265 // @implementation, if we have it.
6266 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006267 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006268 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6269 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6270 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6271 Method->isInstanceMethod()))
6272 if (Def->isThisDeclarationADefinition())
6273 return MakeCXCursor(Def, TU);
6274
6275 return clang_getNullCursor();
6276 }
6277
6278 case Decl::ObjCCategory:
6279 if (ObjCCategoryImplDecl *Impl
6280 = cast<ObjCCategoryDecl>(D)->getImplementation())
6281 return MakeCXCursor(Impl, TU);
6282 return clang_getNullCursor();
6283
6284 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006285 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006286 return MakeCXCursor(Def, TU);
6287 return clang_getNullCursor();
6288
6289 case Decl::ObjCInterface: {
6290 // There are two notions of a "definition" for an Objective-C
6291 // class: the interface and its implementation. When we resolved a
6292 // reference to an Objective-C class, produce the @interface as
6293 // the definition; when we were provided with the interface,
6294 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006295 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006296 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006297 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 return MakeCXCursor(Def, TU);
6299 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6300 return MakeCXCursor(Impl, TU);
6301 return clang_getNullCursor();
6302 }
6303
6304 case Decl::ObjCProperty:
6305 // FIXME: We don't really know where to find the
6306 // ObjCPropertyImplDecls that implement this property.
6307 return clang_getNullCursor();
6308
6309 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006310 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006311 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006312 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006313 return MakeCXCursor(Def, TU);
6314
6315 return clang_getNullCursor();
6316
6317 case Decl::Friend:
6318 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6319 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6320 return clang_getNullCursor();
6321
6322 case Decl::FriendTemplate:
6323 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6324 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6325 return clang_getNullCursor();
6326 }
6327
6328 return clang_getNullCursor();
6329}
6330
6331unsigned clang_isCursorDefinition(CXCursor C) {
6332 if (!clang_isDeclaration(C.kind))
6333 return 0;
6334
6335 return clang_getCursorDefinition(C) == C;
6336}
6337
6338CXCursor clang_getCanonicalCursor(CXCursor C) {
6339 if (!clang_isDeclaration(C.kind))
6340 return C;
6341
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006342 if (const Decl *D = getCursorDecl(C)) {
6343 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006344 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6345 return MakeCXCursor(CatD, getCursorTU(C));
6346
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006347 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6348 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 return MakeCXCursor(IFD, getCursorTU(C));
6350
6351 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6352 }
6353
6354 return C;
6355}
6356
6357int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6358 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6359}
6360
6361unsigned clang_getNumOverloadedDecls(CXCursor C) {
6362 if (C.kind != CXCursor_OverloadedDeclRef)
6363 return 0;
6364
6365 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006366 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006367 return E->getNumDecls();
6368
6369 if (OverloadedTemplateStorage *S
6370 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6371 return S->size();
6372
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006373 const Decl *D = Storage.get<const Decl *>();
6374 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 return Using->shadow_size();
6376
6377 return 0;
6378}
6379
6380CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6381 if (cursor.kind != CXCursor_OverloadedDeclRef)
6382 return clang_getNullCursor();
6383
6384 if (index >= clang_getNumOverloadedDecls(cursor))
6385 return clang_getNullCursor();
6386
6387 CXTranslationUnit TU = getCursorTU(cursor);
6388 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006389 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 return MakeCXCursor(E->decls_begin()[index], TU);
6391
6392 if (OverloadedTemplateStorage *S
6393 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6394 return MakeCXCursor(S->begin()[index], TU);
6395
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006396 const Decl *D = Storage.get<const Decl *>();
6397 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006398 // FIXME: This is, unfortunately, linear time.
6399 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6400 std::advance(Pos, index);
6401 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6402 }
6403
6404 return clang_getNullCursor();
6405}
6406
6407void clang_getDefinitionSpellingAndExtent(CXCursor C,
6408 const char **startBuf,
6409 const char **endBuf,
6410 unsigned *startLine,
6411 unsigned *startColumn,
6412 unsigned *endLine,
6413 unsigned *endColumn) {
6414 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006415 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006416 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6417
6418 SourceManager &SM = FD->getASTContext().getSourceManager();
6419 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6420 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6421 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6422 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6423 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6424 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6425}
6426
6427
6428CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6429 unsigned PieceIndex) {
6430 RefNamePieces Pieces;
6431
6432 switch (C.kind) {
6433 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006434 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006435 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6436 E->getQualifierLoc().getSourceRange());
6437 break;
6438
6439 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006440 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6441 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6442 Pieces =
6443 buildPieces(NameFlags, false, E->getNameInfo(),
6444 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6445 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006446 break;
6447
6448 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006449 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006450 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006451 const Expr *Callee = OCE->getCallee();
6452 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006453 Callee = ICE->getSubExpr();
6454
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006455 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006456 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6457 DRE->getQualifierLoc().getSourceRange());
6458 }
6459 break;
6460
6461 default:
6462 break;
6463 }
6464
6465 if (Pieces.empty()) {
6466 if (PieceIndex == 0)
6467 return clang_getCursorExtent(C);
6468 } else if (PieceIndex < Pieces.size()) {
6469 SourceRange R = Pieces[PieceIndex];
6470 if (R.isValid())
6471 return cxloc::translateSourceRange(getCursorContext(C), R);
6472 }
6473
6474 return clang_getNullRange();
6475}
6476
6477void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006478 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6479 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006480}
6481
6482void clang_executeOnThread(void (*fn)(void*), void *user_data,
6483 unsigned stack_size) {
6484 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6485}
6486
Guy Benyei11169dd2012-12-18 14:30:41 +00006487//===----------------------------------------------------------------------===//
6488// Token-based Operations.
6489//===----------------------------------------------------------------------===//
6490
6491/* CXToken layout:
6492 * int_data[0]: a CXTokenKind
6493 * int_data[1]: starting token location
6494 * int_data[2]: token length
6495 * int_data[3]: reserved
6496 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6497 * otherwise unused.
6498 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006499CXTokenKind clang_getTokenKind(CXToken CXTok) {
6500 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6501}
6502
6503CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6504 switch (clang_getTokenKind(CXTok)) {
6505 case CXToken_Identifier:
6506 case CXToken_Keyword:
6507 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006508 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006509 ->getNameStart());
6510
6511 case CXToken_Literal: {
6512 // We have stashed the starting pointer in the ptr_data field. Use it.
6513 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006514 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006515 }
6516
6517 case CXToken_Punctuation:
6518 case CXToken_Comment:
6519 break;
6520 }
6521
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006522 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006523 LOG_BAD_TU(TU);
6524 return cxstring::createEmpty();
6525 }
6526
Guy Benyei11169dd2012-12-18 14:30:41 +00006527 // We have to find the starting buffer pointer the hard way, by
6528 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006529 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006531 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006532
6533 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6534 std::pair<FileID, unsigned> LocInfo
6535 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6536 bool Invalid = false;
6537 StringRef Buffer
6538 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6539 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006540 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006541
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006542 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006543}
6544
6545CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006546 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006547 LOG_BAD_TU(TU);
6548 return clang_getNullLocation();
6549 }
6550
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006551 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006552 if (!CXXUnit)
6553 return clang_getNullLocation();
6554
6555 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6556 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6557}
6558
6559CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006560 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006561 LOG_BAD_TU(TU);
6562 return clang_getNullRange();
6563 }
6564
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006565 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006566 if (!CXXUnit)
6567 return clang_getNullRange();
6568
6569 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6570 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6571}
6572
6573static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6574 SmallVectorImpl<CXToken> &CXTokens) {
6575 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6576 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006577 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006578 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006579 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006580
6581 // Cannot tokenize across files.
6582 if (BeginLocInfo.first != EndLocInfo.first)
6583 return;
6584
6585 // Create a lexer
6586 bool Invalid = false;
6587 StringRef Buffer
6588 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6589 if (Invalid)
6590 return;
6591
6592 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6593 CXXUnit->getASTContext().getLangOpts(),
6594 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6595 Lex.SetCommentRetentionState(true);
6596
6597 // Lex tokens until we hit the end of the range.
6598 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6599 Token Tok;
6600 bool previousWasAt = false;
6601 do {
6602 // Lex the next token
6603 Lex.LexFromRawLexer(Tok);
6604 if (Tok.is(tok::eof))
6605 break;
6606
6607 // Initialize the CXToken.
6608 CXToken CXTok;
6609
6610 // - Common fields
6611 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6612 CXTok.int_data[2] = Tok.getLength();
6613 CXTok.int_data[3] = 0;
6614
6615 // - Kind-specific fields
6616 if (Tok.isLiteral()) {
6617 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006618 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006619 } else if (Tok.is(tok::raw_identifier)) {
6620 // Lookup the identifier to determine whether we have a keyword.
6621 IdentifierInfo *II
6622 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6623
6624 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6625 CXTok.int_data[0] = CXToken_Keyword;
6626 }
6627 else {
6628 CXTok.int_data[0] = Tok.is(tok::identifier)
6629 ? CXToken_Identifier
6630 : CXToken_Keyword;
6631 }
6632 CXTok.ptr_data = II;
6633 } else if (Tok.is(tok::comment)) {
6634 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006635 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006636 } else {
6637 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006638 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006639 }
6640 CXTokens.push_back(CXTok);
6641 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006642 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006643}
6644
6645void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6646 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006647 LOG_FUNC_SECTION {
6648 *Log << TU << ' ' << Range;
6649 }
6650
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006652 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006653 if (NumTokens)
6654 *NumTokens = 0;
6655
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006656 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006657 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006658 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006659 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006660
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006661 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006662 if (!CXXUnit || !Tokens || !NumTokens)
6663 return;
6664
6665 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6666
6667 SourceRange R = cxloc::translateCXSourceRange(Range);
6668 if (R.isInvalid())
6669 return;
6670
6671 SmallVector<CXToken, 32> CXTokens;
6672 getTokens(CXXUnit, R, CXTokens);
6673
6674 if (CXTokens.empty())
6675 return;
6676
Serge Pavlov52525732018-02-21 02:02:39 +00006677 *Tokens = static_cast<CXToken *>(
6678 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006679 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6680 *NumTokens = CXTokens.size();
6681}
6682
6683void clang_disposeTokens(CXTranslationUnit TU,
6684 CXToken *Tokens, unsigned NumTokens) {
6685 free(Tokens);
6686}
6687
Guy Benyei11169dd2012-12-18 14:30:41 +00006688//===----------------------------------------------------------------------===//
6689// Token annotation APIs.
6690//===----------------------------------------------------------------------===//
6691
Guy Benyei11169dd2012-12-18 14:30:41 +00006692static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6693 CXCursor parent,
6694 CXClientData client_data);
6695static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6696 CXClientData client_data);
6697
6698namespace {
6699class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006700 CXToken *Tokens;
6701 CXCursor *Cursors;
6702 unsigned NumTokens;
6703 unsigned TokIdx;
6704 unsigned PreprocessingTokIdx;
6705 CursorVisitor AnnotateVis;
6706 SourceManager &SrcMgr;
6707 bool HasContextSensitiveKeywords;
6708
6709 struct PostChildrenInfo {
6710 CXCursor Cursor;
6711 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006712 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006713 unsigned BeforeChildrenTokenIdx;
6714 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006715 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006716
6717 CXToken &getTok(unsigned Idx) {
6718 assert(Idx < NumTokens);
6719 return Tokens[Idx];
6720 }
6721 const CXToken &getTok(unsigned Idx) const {
6722 assert(Idx < NumTokens);
6723 return Tokens[Idx];
6724 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 bool MoreTokens() const { return TokIdx < NumTokens; }
6726 unsigned NextToken() const { return TokIdx; }
6727 void AdvanceToken() { ++TokIdx; }
6728 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006729 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006730 }
6731 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006732 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006733 }
6734 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006735 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 }
6737
6738 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006739 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006740 SourceRange);
6741
6742public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006743 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006744 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006745 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006746 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006747 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006748 AnnotateTokensVisitor, this,
6749 /*VisitPreprocessorLast=*/true,
6750 /*VisitIncludedEntities=*/false,
6751 RegionOfInterest,
6752 /*VisitDeclsOnly=*/false,
6753 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006754 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 HasContextSensitiveKeywords(false) { }
6756
6757 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6758 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6759 bool postVisitChildren(CXCursor cursor);
6760 void AnnotateTokens();
6761
6762 /// \brief Determine whether the annotator saw any cursors that have
6763 /// context-sensitive keywords.
6764 bool hasContextSensitiveKeywords() const {
6765 return HasContextSensitiveKeywords;
6766 }
6767
6768 ~AnnotateTokensWorker() {
6769 assert(PostChildrenInfos.empty());
6770 }
6771};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006772}
Guy Benyei11169dd2012-12-18 14:30:41 +00006773
6774void AnnotateTokensWorker::AnnotateTokens() {
6775 // Walk the AST within the region of interest, annotating tokens
6776 // along the way.
6777 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006778}
Guy Benyei11169dd2012-12-18 14:30:41 +00006779
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006780static inline void updateCursorAnnotation(CXCursor &Cursor,
6781 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006782 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006783 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006784 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006785}
6786
6787/// \brief It annotates and advances tokens with a cursor until the comparison
6788//// between the cursor location and the source range is the same as
6789/// \arg compResult.
6790///
6791/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6792/// Pass RangeOverlap to annotate tokens inside a range.
6793void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6794 RangeComparisonResult compResult,
6795 SourceRange range) {
6796 while (MoreTokens()) {
6797 const unsigned I = NextToken();
6798 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006799 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6800 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006801
6802 SourceLocation TokLoc = GetTokenLoc(I);
6803 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006804 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006805 AdvanceToken();
6806 continue;
6807 }
6808 break;
6809 }
6810}
6811
6812/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006813/// \returns true if it advanced beyond all macro tokens, false otherwise.
6814bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006815 CXCursor updateC,
6816 RangeComparisonResult compResult,
6817 SourceRange range) {
6818 assert(MoreTokens());
6819 assert(isFunctionMacroToken(NextToken()) &&
6820 "Should be called only for macro arg tokens");
6821
6822 // This works differently than annotateAndAdvanceTokens; because expanded
6823 // macro arguments can have arbitrary translation-unit source order, we do not
6824 // advance the token index one by one until a token fails the range test.
6825 // We only advance once past all of the macro arg tokens if all of them
6826 // pass the range test. If one of them fails we keep the token index pointing
6827 // at the start of the macro arg tokens so that the failing token will be
6828 // annotated by a subsequent annotation try.
6829
6830 bool atLeastOneCompFail = false;
6831
6832 unsigned I = NextToken();
6833 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6834 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6835 if (TokLoc.isFileID())
6836 continue; // not macro arg token, it's parens or comma.
6837 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6838 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6839 Cursors[I] = updateC;
6840 } else
6841 atLeastOneCompFail = true;
6842 }
6843
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006844 if (atLeastOneCompFail)
6845 return false;
6846
6847 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6848 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006849}
6850
6851enum CXChildVisitResult
6852AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 SourceRange cursorRange = getRawCursorExtent(cursor);
6854 if (cursorRange.isInvalid())
6855 return CXChildVisit_Recurse;
6856
6857 if (!HasContextSensitiveKeywords) {
6858 // Objective-C properties can have context-sensitive keywords.
6859 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006860 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006861 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6862 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6863 }
6864 // Objective-C methods can have context-sensitive keywords.
6865 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6866 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006867 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006868 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6869 if (Method->getObjCDeclQualifier())
6870 HasContextSensitiveKeywords = true;
6871 else {
David Majnemer59f77922016-06-24 04:05:48 +00006872 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006873 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006874 HasContextSensitiveKeywords = true;
6875 break;
6876 }
6877 }
6878 }
6879 }
6880 }
6881 // C++ methods can have context-sensitive keywords.
6882 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006883 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006884 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6885 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6886 HasContextSensitiveKeywords = true;
6887 }
6888 }
6889 // C++ classes can have context-sensitive keywords.
6890 else if (cursor.kind == CXCursor_StructDecl ||
6891 cursor.kind == CXCursor_ClassDecl ||
6892 cursor.kind == CXCursor_ClassTemplate ||
6893 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006894 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006895 if (D->hasAttr<FinalAttr>())
6896 HasContextSensitiveKeywords = true;
6897 }
6898 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006899
6900 // Don't override a property annotation with its getter/setter method.
6901 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6902 parent.kind == CXCursor_ObjCPropertyDecl)
6903 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006904
6905 if (clang_isPreprocessing(cursor.kind)) {
6906 // Items in the preprocessing record are kept separate from items in
6907 // declarations, so we keep a separate token index.
6908 unsigned SavedTokIdx = TokIdx;
6909 TokIdx = PreprocessingTokIdx;
6910
6911 // Skip tokens up until we catch up to the beginning of the preprocessing
6912 // entry.
6913 while (MoreTokens()) {
6914 const unsigned I = NextToken();
6915 SourceLocation TokLoc = GetTokenLoc(I);
6916 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6917 case RangeBefore:
6918 AdvanceToken();
6919 continue;
6920 case RangeAfter:
6921 case RangeOverlap:
6922 break;
6923 }
6924 break;
6925 }
6926
6927 // Look at all of the tokens within this range.
6928 while (MoreTokens()) {
6929 const unsigned I = NextToken();
6930 SourceLocation TokLoc = GetTokenLoc(I);
6931 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6932 case RangeBefore:
6933 llvm_unreachable("Infeasible");
6934 case RangeAfter:
6935 break;
6936 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006937 // For macro expansions, just note where the beginning of the macro
6938 // expansion occurs.
6939 if (cursor.kind == CXCursor_MacroExpansion) {
6940 if (TokLoc == cursorRange.getBegin())
6941 Cursors[I] = cursor;
6942 AdvanceToken();
6943 break;
6944 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006945 // We may have already annotated macro names inside macro definitions.
6946 if (Cursors[I].kind != CXCursor_MacroExpansion)
6947 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006948 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 continue;
6950 }
6951 break;
6952 }
6953
6954 // Save the preprocessing token index; restore the non-preprocessing
6955 // token index.
6956 PreprocessingTokIdx = TokIdx;
6957 TokIdx = SavedTokIdx;
6958 return CXChildVisit_Recurse;
6959 }
6960
6961 if (cursorRange.isInvalid())
6962 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006963
6964 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006965 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006966 const enum CXCursorKind K = clang_getCursorKind(parent);
6967 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006968 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6969 // Attributes are annotated out-of-order, skip tokens until we reach it.
6970 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006971 ? clang_getNullCursor() : parent;
6972
6973 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6974
6975 // Avoid having the cursor of an expression "overwrite" the annotation of the
6976 // variable declaration that it belongs to.
6977 // This can happen for C++ constructor expressions whose range generally
6978 // include the variable declaration, e.g.:
6979 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006980 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006981 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006982 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 const unsigned I = NextToken();
6984 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6985 E->getLocStart() == D->getLocation() &&
6986 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006987 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006988 AdvanceToken();
6989 }
6990 }
6991 }
6992
6993 // Before recursing into the children keep some state that we are going
6994 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6995 // extra work after the child nodes are visited.
6996 // Note that we don't call VisitChildren here to avoid traversing statements
6997 // code-recursively which can blow the stack.
6998
6999 PostChildrenInfo Info;
7000 Info.Cursor = cursor;
7001 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007002 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007003 Info.BeforeChildrenTokenIdx = NextToken();
7004 PostChildrenInfos.push_back(Info);
7005
7006 return CXChildVisit_Recurse;
7007}
7008
7009bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7010 if (PostChildrenInfos.empty())
7011 return false;
7012 const PostChildrenInfo &Info = PostChildrenInfos.back();
7013 if (!clang_equalCursors(Info.Cursor, cursor))
7014 return false;
7015
7016 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7017 const unsigned AfterChildren = NextToken();
7018 SourceRange cursorRange = Info.CursorRange;
7019
7020 // Scan the tokens that are at the end of the cursor, but are not captured
7021 // but the child cursors.
7022 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7023
7024 // Scan the tokens that are at the beginning of the cursor, but are not
7025 // capture by the child cursors.
7026 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7027 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7028 break;
7029
7030 Cursors[I] = cursor;
7031 }
7032
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007033 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7034 // encountered the attribute cursor.
7035 if (clang_isAttribute(cursor.kind))
7036 TokIdx = Info.BeforeReachingCursorIdx;
7037
Guy Benyei11169dd2012-12-18 14:30:41 +00007038 PostChildrenInfos.pop_back();
7039 return false;
7040}
7041
7042static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7043 CXCursor parent,
7044 CXClientData client_data) {
7045 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7046}
7047
7048static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7049 CXClientData client_data) {
7050 return static_cast<AnnotateTokensWorker*>(client_data)->
7051 postVisitChildren(cursor);
7052}
7053
7054namespace {
7055
7056/// \brief Uses the macro expansions in the preprocessing record to find
7057/// and mark tokens that are macro arguments. This info is used by the
7058/// AnnotateTokensWorker.
7059class MarkMacroArgTokensVisitor {
7060 SourceManager &SM;
7061 CXToken *Tokens;
7062 unsigned NumTokens;
7063 unsigned CurIdx;
7064
7065public:
7066 MarkMacroArgTokensVisitor(SourceManager &SM,
7067 CXToken *tokens, unsigned numTokens)
7068 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7069
7070 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7071 if (cursor.kind != CXCursor_MacroExpansion)
7072 return CXChildVisit_Continue;
7073
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007074 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007075 if (macroRange.getBegin() == macroRange.getEnd())
7076 return CXChildVisit_Continue; // it's not a function macro.
7077
7078 for (; CurIdx < NumTokens; ++CurIdx) {
7079 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7080 macroRange.getBegin()))
7081 break;
7082 }
7083
7084 if (CurIdx == NumTokens)
7085 return CXChildVisit_Break;
7086
7087 for (; CurIdx < NumTokens; ++CurIdx) {
7088 SourceLocation tokLoc = getTokenLoc(CurIdx);
7089 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7090 break;
7091
7092 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7093 }
7094
7095 if (CurIdx == NumTokens)
7096 return CXChildVisit_Break;
7097
7098 return CXChildVisit_Continue;
7099 }
7100
7101private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007102 CXToken &getTok(unsigned Idx) {
7103 assert(Idx < NumTokens);
7104 return Tokens[Idx];
7105 }
7106 const CXToken &getTok(unsigned Idx) const {
7107 assert(Idx < NumTokens);
7108 return Tokens[Idx];
7109 }
7110
Guy Benyei11169dd2012-12-18 14:30:41 +00007111 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007112 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007113 }
7114
7115 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7116 // The third field is reserved and currently not used. Use it here
7117 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007118 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007119 }
7120};
7121
7122} // end anonymous namespace
7123
7124static CXChildVisitResult
7125MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7126 CXClientData client_data) {
7127 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7128 parent);
7129}
7130
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007131/// \brief Used by \c annotatePreprocessorTokens.
7132/// \returns true if lexing was finished, false otherwise.
7133static bool lexNext(Lexer &Lex, Token &Tok,
7134 unsigned &NextIdx, unsigned NumTokens) {
7135 if (NextIdx >= NumTokens)
7136 return true;
7137
7138 ++NextIdx;
7139 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007140 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007141}
7142
Guy Benyei11169dd2012-12-18 14:30:41 +00007143static void annotatePreprocessorTokens(CXTranslationUnit TU,
7144 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007145 CXCursor *Cursors,
7146 CXToken *Tokens,
7147 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007148 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007149
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007150 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007151 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7152 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007153 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007154 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007155 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007156
7157 if (BeginLocInfo.first != EndLocInfo.first)
7158 return;
7159
7160 StringRef Buffer;
7161 bool Invalid = false;
7162 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7163 if (Buffer.empty() || Invalid)
7164 return;
7165
7166 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7167 CXXUnit->getASTContext().getLangOpts(),
7168 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7169 Buffer.end());
7170 Lex.SetCommentRetentionState(true);
7171
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007172 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007173 // Lex tokens in raw mode until we hit the end of the range, to avoid
7174 // entering #includes or expanding macros.
7175 while (true) {
7176 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007177 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7178 break;
7179 unsigned TokIdx = NextIdx-1;
7180 assert(Tok.getLocation() ==
7181 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007182
7183 reprocess:
7184 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007185 // We have found a preprocessing directive. Annotate the tokens
7186 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007187 //
7188 // FIXME: Some simple tests here could identify macro definitions and
7189 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007190
7191 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007192 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7193 break;
7194
Craig Topper69186e72014-06-08 08:38:04 +00007195 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007196 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007197 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7198 break;
7199
7200 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007201 IdentifierInfo &II =
7202 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007203 SourceLocation MappedTokLoc =
7204 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7205 MI = getMacroInfo(II, MappedTokLoc, TU);
7206 }
7207 }
7208
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007209 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007210 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007211 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7212 finished = true;
7213 break;
7214 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007215 // If we are in a macro definition, check if the token was ever a
7216 // macro name and annotate it if that's the case.
7217 if (MI) {
7218 SourceLocation SaveLoc = Tok.getLocation();
7219 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007220 MacroDefinitionRecord *MacroDef =
7221 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007222 Tok.setLocation(SaveLoc);
7223 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007224 Cursors[NextIdx - 1] =
7225 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007226 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007227 } while (!Tok.isAtStartOfLine());
7228
7229 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7230 assert(TokIdx <= LastIdx);
7231 SourceLocation EndLoc =
7232 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7233 CXCursor Cursor =
7234 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7235
7236 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007237 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007238
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007239 if (finished)
7240 break;
7241 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007242 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007243 }
7244}
7245
7246// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007247static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7248 CXToken *Tokens, unsigned NumTokens,
7249 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007250 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007251 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7252 setThreadBackgroundPriority();
7253
7254 // Determine the region of interest, which contains all of the tokens.
7255 SourceRange RegionOfInterest;
7256 RegionOfInterest.setBegin(
7257 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7258 RegionOfInterest.setEnd(
7259 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7260 Tokens[NumTokens-1])));
7261
Guy Benyei11169dd2012-12-18 14:30:41 +00007262 // Relex the tokens within the source range to look for preprocessing
7263 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007264 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007265
7266 // If begin location points inside a macro argument, set it to the expansion
7267 // location so we can have the full context when annotating semantically.
7268 {
7269 SourceManager &SM = CXXUnit->getSourceManager();
7270 SourceLocation Loc =
7271 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7272 if (Loc.isMacroID())
7273 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7274 }
7275
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7277 // Search and mark tokens that are macro argument expansions.
7278 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7279 Tokens, NumTokens);
7280 CursorVisitor MacroArgMarker(TU,
7281 MarkMacroArgTokensVisitorDelegate, &Visitor,
7282 /*VisitPreprocessorLast=*/true,
7283 /*VisitIncludedEntities=*/false,
7284 RegionOfInterest);
7285 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7286 }
7287
7288 // Annotate all of the source locations in the region of interest that map to
7289 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007290 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007291
7292 // FIXME: We use a ridiculous stack size here because the data-recursion
7293 // algorithm uses a large stack frame than the non-data recursive version,
7294 // and AnnotationTokensWorker currently transforms the data-recursion
7295 // algorithm back into a traditional recursion by explicitly calling
7296 // VisitChildren(). We will need to remove this explicit recursive call.
7297 W.AnnotateTokens();
7298
7299 // If we ran into any entities that involve context-sensitive keywords,
7300 // take another pass through the tokens to mark them as such.
7301 if (W.hasContextSensitiveKeywords()) {
7302 for (unsigned I = 0; I != NumTokens; ++I) {
7303 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7304 continue;
7305
7306 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7307 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007308 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7310 if (Property->getPropertyAttributesAsWritten() != 0 &&
7311 llvm::StringSwitch<bool>(II->getName())
7312 .Case("readonly", true)
7313 .Case("assign", true)
7314 .Case("unsafe_unretained", true)
7315 .Case("readwrite", true)
7316 .Case("retain", true)
7317 .Case("copy", true)
7318 .Case("nonatomic", true)
7319 .Case("atomic", true)
7320 .Case("getter", true)
7321 .Case("setter", true)
7322 .Case("strong", true)
7323 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007324 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007325 .Default(false))
7326 Tokens[I].int_data[0] = CXToken_Keyword;
7327 }
7328 continue;
7329 }
7330
7331 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7332 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7333 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7334 if (llvm::StringSwitch<bool>(II->getName())
7335 .Case("in", true)
7336 .Case("out", true)
7337 .Case("inout", true)
7338 .Case("oneway", true)
7339 .Case("bycopy", true)
7340 .Case("byref", true)
7341 .Default(false))
7342 Tokens[I].int_data[0] = CXToken_Keyword;
7343 continue;
7344 }
7345
7346 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7347 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7348 Tokens[I].int_data[0] = CXToken_Keyword;
7349 continue;
7350 }
7351 }
7352 }
7353}
7354
Guy Benyei11169dd2012-12-18 14:30:41 +00007355void clang_annotateTokens(CXTranslationUnit TU,
7356 CXToken *Tokens, unsigned NumTokens,
7357 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007358 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007359 LOG_BAD_TU(TU);
7360 return;
7361 }
7362 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007363 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007364 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007365 }
7366
7367 LOG_FUNC_SECTION {
7368 *Log << TU << ' ';
7369 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7370 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7371 *Log << clang_getRange(bloc, eloc);
7372 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007373
7374 // Any token we don't specifically annotate will have a NULL cursor.
7375 CXCursor C = clang_getNullCursor();
7376 for (unsigned I = 0; I != NumTokens; ++I)
7377 Cursors[I] = C;
7378
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007379 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007380 if (!CXXUnit)
7381 return;
7382
7383 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007384
7385 auto AnnotateTokensImpl = [=]() {
7386 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7387 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007388 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007389 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007390 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7391 }
7392}
7393
Guy Benyei11169dd2012-12-18 14:30:41 +00007394//===----------------------------------------------------------------------===//
7395// Operations for querying linkage of a cursor.
7396//===----------------------------------------------------------------------===//
7397
Guy Benyei11169dd2012-12-18 14:30:41 +00007398CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7399 if (!clang_isDeclaration(cursor.kind))
7400 return CXLinkage_Invalid;
7401
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007402 const Decl *D = cxcursor::getCursorDecl(cursor);
7403 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007404 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007405 case NoLinkage:
7406 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007407 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007408 case InternalLinkage: return CXLinkage_Internal;
7409 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007410 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007411 case ExternalLinkage: return CXLinkage_External;
7412 };
7413
7414 return CXLinkage_Invalid;
7415}
Guy Benyei11169dd2012-12-18 14:30:41 +00007416
7417//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007418// Operations for querying visibility of a cursor.
7419//===----------------------------------------------------------------------===//
7420
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007421CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7422 if (!clang_isDeclaration(cursor.kind))
7423 return CXVisibility_Invalid;
7424
7425 const Decl *D = cxcursor::getCursorDecl(cursor);
7426 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7427 switch (ND->getVisibility()) {
7428 case HiddenVisibility: return CXVisibility_Hidden;
7429 case ProtectedVisibility: return CXVisibility_Protected;
7430 case DefaultVisibility: return CXVisibility_Default;
7431 };
7432
7433 return CXVisibility_Invalid;
7434}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007435
7436//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007437// Operations for querying language of a cursor.
7438//===----------------------------------------------------------------------===//
7439
7440static CXLanguageKind getDeclLanguage(const Decl *D) {
7441 if (!D)
7442 return CXLanguage_C;
7443
7444 switch (D->getKind()) {
7445 default:
7446 break;
7447 case Decl::ImplicitParam:
7448 case Decl::ObjCAtDefsField:
7449 case Decl::ObjCCategory:
7450 case Decl::ObjCCategoryImpl:
7451 case Decl::ObjCCompatibleAlias:
7452 case Decl::ObjCImplementation:
7453 case Decl::ObjCInterface:
7454 case Decl::ObjCIvar:
7455 case Decl::ObjCMethod:
7456 case Decl::ObjCProperty:
7457 case Decl::ObjCPropertyImpl:
7458 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007459 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007460 return CXLanguage_ObjC;
7461 case Decl::CXXConstructor:
7462 case Decl::CXXConversion:
7463 case Decl::CXXDestructor:
7464 case Decl::CXXMethod:
7465 case Decl::CXXRecord:
7466 case Decl::ClassTemplate:
7467 case Decl::ClassTemplatePartialSpecialization:
7468 case Decl::ClassTemplateSpecialization:
7469 case Decl::Friend:
7470 case Decl::FriendTemplate:
7471 case Decl::FunctionTemplate:
7472 case Decl::LinkageSpec:
7473 case Decl::Namespace:
7474 case Decl::NamespaceAlias:
7475 case Decl::NonTypeTemplateParm:
7476 case Decl::StaticAssert:
7477 case Decl::TemplateTemplateParm:
7478 case Decl::TemplateTypeParm:
7479 case Decl::UnresolvedUsingTypename:
7480 case Decl::UnresolvedUsingValue:
7481 case Decl::Using:
7482 case Decl::UsingDirective:
7483 case Decl::UsingShadow:
7484 return CXLanguage_CPlusPlus;
7485 }
7486
7487 return CXLanguage_C;
7488}
7489
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007490static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7491 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007492 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007493
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007494 switch (D->getAvailability()) {
7495 case AR_Available:
7496 case AR_NotYetIntroduced:
7497 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007498 return getCursorAvailabilityForDecl(
7499 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007500 return CXAvailability_Available;
7501
7502 case AR_Deprecated:
7503 return CXAvailability_Deprecated;
7504
7505 case AR_Unavailable:
7506 return CXAvailability_NotAvailable;
7507 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007508
7509 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007510}
7511
Guy Benyei11169dd2012-12-18 14:30:41 +00007512enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7513 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007514 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7515 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007516
7517 return CXAvailability_Available;
7518}
7519
7520static CXVersion convertVersion(VersionTuple In) {
7521 CXVersion Out = { -1, -1, -1 };
7522 if (In.empty())
7523 return Out;
7524
7525 Out.Major = In.getMajor();
7526
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007527 Optional<unsigned> Minor = In.getMinor();
7528 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007529 Out.Minor = *Minor;
7530 else
7531 return Out;
7532
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007533 Optional<unsigned> Subminor = In.getSubminor();
7534 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007535 Out.Subminor = *Subminor;
7536
7537 return Out;
7538}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007539
Alex Lorenz1345ea22017-06-12 19:06:30 +00007540static void getCursorPlatformAvailabilityForDecl(
7541 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7542 int *always_unavailable, CXString *unavailable_message,
7543 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007544 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007545 for (auto A : D->attrs()) {
7546 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007547 HadAvailAttr = true;
7548 if (always_deprecated)
7549 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007550 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007551 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007552 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007553 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007554 continue;
7555 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007556
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007557 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007558 HadAvailAttr = true;
7559 if (always_unavailable)
7560 *always_unavailable = 1;
7561 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007562 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007563 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7564 }
7565 continue;
7566 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007567
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007568 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007569 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007570 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007571 }
7572 }
7573
7574 if (!HadAvailAttr)
7575 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7576 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007577 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7578 deprecated_message, always_unavailable, unavailable_message,
7579 AvailabilityAttrs);
7580
7581 if (AvailabilityAttrs.empty())
7582 return;
7583
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007584 llvm::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7585 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7586 return LHS->getPlatform()->getName() <
7587 RHS->getPlatform()->getName();
Alex Lorenz1345ea22017-06-12 19:06:30 +00007588 });
7589 ASTContext &Ctx = D->getASTContext();
7590 auto It = std::unique(
7591 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7592 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7593 if (LHS->getPlatform() != RHS->getPlatform())
7594 return false;
7595
7596 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7597 LHS->getDeprecated() == RHS->getDeprecated() &&
7598 LHS->getObsoleted() == RHS->getObsoleted() &&
7599 LHS->getMessage() == RHS->getMessage() &&
7600 LHS->getReplacement() == RHS->getReplacement())
7601 return true;
7602
7603 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7604 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7605 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7606 return false;
7607
7608 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7609 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7610
7611 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7612 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7613 if (LHS->getMessage().empty())
7614 LHS->setMessage(Ctx, RHS->getMessage());
7615 if (LHS->getReplacement().empty())
7616 LHS->setReplacement(Ctx, RHS->getReplacement());
7617 }
7618
7619 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7620 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7621 if (LHS->getMessage().empty())
7622 LHS->setMessage(Ctx, RHS->getMessage());
7623 if (LHS->getReplacement().empty())
7624 LHS->setReplacement(Ctx, RHS->getReplacement());
7625 }
7626
7627 return true;
7628 });
7629 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007630}
7631
Alex Lorenz1345ea22017-06-12 19:06:30 +00007632int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007633 CXString *deprecated_message,
7634 int *always_unavailable,
7635 CXString *unavailable_message,
7636 CXPlatformAvailability *availability,
7637 int availability_size) {
7638 if (always_deprecated)
7639 *always_deprecated = 0;
7640 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007641 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007642 if (always_unavailable)
7643 *always_unavailable = 0;
7644 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007645 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007646
Guy Benyei11169dd2012-12-18 14:30:41 +00007647 if (!clang_isDeclaration(cursor.kind))
7648 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007649
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007650 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007651 if (!D)
7652 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007653
Alex Lorenz1345ea22017-06-12 19:06:30 +00007654 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7655 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7656 always_unavailable, unavailable_message,
7657 AvailabilityAttrs);
7658 for (const auto &Avail :
7659 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7660 .take_front(availability_size))) {
7661 availability[Avail.index()].Platform =
7662 cxstring::createDup(Avail.value()->getPlatform()->getName());
7663 availability[Avail.index()].Introduced =
7664 convertVersion(Avail.value()->getIntroduced());
7665 availability[Avail.index()].Deprecated =
7666 convertVersion(Avail.value()->getDeprecated());
7667 availability[Avail.index()].Obsoleted =
7668 convertVersion(Avail.value()->getObsoleted());
7669 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7670 availability[Avail.index()].Message =
7671 cxstring::createDup(Avail.value()->getMessage());
7672 }
7673
7674 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007675}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007676
Guy Benyei11169dd2012-12-18 14:30:41 +00007677void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7678 clang_disposeString(availability->Platform);
7679 clang_disposeString(availability->Message);
7680}
7681
7682CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7683 if (clang_isDeclaration(cursor.kind))
7684 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7685
7686 return CXLanguage_Invalid;
7687}
7688
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007689CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7690 const Decl *D = cxcursor::getCursorDecl(cursor);
7691 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7692 switch (VD->getTLSKind()) {
7693 case VarDecl::TLS_None:
7694 return CXTLS_None;
7695 case VarDecl::TLS_Dynamic:
7696 return CXTLS_Dynamic;
7697 case VarDecl::TLS_Static:
7698 return CXTLS_Static;
7699 }
7700 }
7701
7702 return CXTLS_None;
7703}
7704
Guy Benyei11169dd2012-12-18 14:30:41 +00007705 /// \brief If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007706 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007707 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007708static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007709 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007710 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007711
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007712 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007713 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7714 return FunTmpl;
7715
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007716 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007717 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7718 return ClassTmpl;
7719
7720 return D;
7721}
7722
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007723
7724enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7725 StorageClass sc = SC_None;
7726 const Decl *D = getCursorDecl(C);
7727 if (D) {
7728 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7729 sc = FD->getStorageClass();
7730 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7731 sc = VD->getStorageClass();
7732 } else {
7733 return CX_SC_Invalid;
7734 }
7735 } else {
7736 return CX_SC_Invalid;
7737 }
7738 switch (sc) {
7739 case SC_None:
7740 return CX_SC_None;
7741 case SC_Extern:
7742 return CX_SC_Extern;
7743 case SC_Static:
7744 return CX_SC_Static;
7745 case SC_PrivateExtern:
7746 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007747 case SC_Auto:
7748 return CX_SC_Auto;
7749 case SC_Register:
7750 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007751 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007752 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007753}
7754
Guy Benyei11169dd2012-12-18 14:30:41 +00007755CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7756 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007757 if (const Decl *D = getCursorDecl(cursor)) {
7758 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007759 if (!DC)
7760 return clang_getNullCursor();
7761
7762 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7763 getCursorTU(cursor));
7764 }
7765 }
7766
7767 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007768 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007769 return MakeCXCursor(D, getCursorTU(cursor));
7770 }
7771
7772 return clang_getNullCursor();
7773}
7774
7775CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7776 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007777 if (const Decl *D = getCursorDecl(cursor)) {
7778 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007779 if (!DC)
7780 return clang_getNullCursor();
7781
7782 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7783 getCursorTU(cursor));
7784 }
7785 }
7786
7787 // FIXME: Note that we can't easily compute the lexical context of a
7788 // statement or expression, so we return nothing.
7789 return clang_getNullCursor();
7790}
7791
7792CXFile clang_getIncludedFile(CXCursor cursor) {
7793 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007794 return nullptr;
7795
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007796 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007797 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007798}
7799
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007800unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7801 if (C.kind != CXCursor_ObjCPropertyDecl)
7802 return CXObjCPropertyAttr_noattr;
7803
7804 unsigned Result = CXObjCPropertyAttr_noattr;
7805 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7806 ObjCPropertyDecl::PropertyAttributeKind Attr =
7807 PD->getPropertyAttributesAsWritten();
7808
7809#define SET_CXOBJCPROP_ATTR(A) \
7810 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7811 Result |= CXObjCPropertyAttr_##A
7812 SET_CXOBJCPROP_ATTR(readonly);
7813 SET_CXOBJCPROP_ATTR(getter);
7814 SET_CXOBJCPROP_ATTR(assign);
7815 SET_CXOBJCPROP_ATTR(readwrite);
7816 SET_CXOBJCPROP_ATTR(retain);
7817 SET_CXOBJCPROP_ATTR(copy);
7818 SET_CXOBJCPROP_ATTR(nonatomic);
7819 SET_CXOBJCPROP_ATTR(setter);
7820 SET_CXOBJCPROP_ATTR(atomic);
7821 SET_CXOBJCPROP_ATTR(weak);
7822 SET_CXOBJCPROP_ATTR(strong);
7823 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007824 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007825#undef SET_CXOBJCPROP_ATTR
7826
7827 return Result;
7828}
7829
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007830unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7831 if (!clang_isDeclaration(C.kind))
7832 return CXObjCDeclQualifier_None;
7833
7834 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7835 const Decl *D = getCursorDecl(C);
7836 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7837 QT = MD->getObjCDeclQualifier();
7838 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7839 QT = PD->getObjCDeclQualifier();
7840 if (QT == Decl::OBJC_TQ_None)
7841 return CXObjCDeclQualifier_None;
7842
7843 unsigned Result = CXObjCDeclQualifier_None;
7844 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7845 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7846 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7847 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7848 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7849 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7850
7851 return Result;
7852}
7853
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007854unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7855 if (!clang_isDeclaration(C.kind))
7856 return 0;
7857
7858 const Decl *D = getCursorDecl(C);
7859 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7860 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7861 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7862 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7863
7864 return 0;
7865}
7866
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007867unsigned clang_Cursor_isVariadic(CXCursor C) {
7868 if (!clang_isDeclaration(C.kind))
7869 return 0;
7870
7871 const Decl *D = getCursorDecl(C);
7872 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7873 return FD->isVariadic();
7874 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7875 return MD->isVariadic();
7876
7877 return 0;
7878}
7879
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007880unsigned clang_Cursor_isExternalSymbol(CXCursor C,
7881 CXString *language, CXString *definedIn,
7882 unsigned *isGenerated) {
7883 if (!clang_isDeclaration(C.kind))
7884 return 0;
7885
7886 const Decl *D = getCursorDecl(C);
7887
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00007888 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007889 if (language)
7890 *language = cxstring::createDup(attr->getLanguage());
7891 if (definedIn)
7892 *definedIn = cxstring::createDup(attr->getDefinedIn());
7893 if (isGenerated)
7894 *isGenerated = attr->getGeneratedDeclaration();
7895 return 1;
7896 }
7897 return 0;
7898}
7899
Guy Benyei11169dd2012-12-18 14:30:41 +00007900CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7901 if (!clang_isDeclaration(C.kind))
7902 return clang_getNullRange();
7903
7904 const Decl *D = getCursorDecl(C);
7905 ASTContext &Context = getCursorContext(C);
7906 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7907 if (!RC)
7908 return clang_getNullRange();
7909
7910 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7911}
7912
7913CXString clang_Cursor_getRawCommentText(CXCursor C) {
7914 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007915 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007916
7917 const Decl *D = getCursorDecl(C);
7918 ASTContext &Context = getCursorContext(C);
7919 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7920 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7921 StringRef();
7922
7923 // Don't duplicate the string because RawText points directly into source
7924 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007925 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007926}
7927
7928CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7929 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007930 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007931
7932 const Decl *D = getCursorDecl(C);
7933 const ASTContext &Context = getCursorContext(C);
7934 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7935
7936 if (RC) {
7937 StringRef BriefText = RC->getBriefText(Context);
7938
7939 // Don't duplicate the string because RawComment ensures that this memory
7940 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007941 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007942 }
7943
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007944 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007945}
7946
Guy Benyei11169dd2012-12-18 14:30:41 +00007947CXModule clang_Cursor_getModule(CXCursor C) {
7948 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007949 if (const ImportDecl *ImportD =
7950 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007951 return ImportD->getImportedModule();
7952 }
7953
Craig Topper69186e72014-06-08 08:38:04 +00007954 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007955}
7956
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007957CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7958 if (isNotUsableTU(TU)) {
7959 LOG_BAD_TU(TU);
7960 return nullptr;
7961 }
7962 if (!File)
7963 return nullptr;
7964 FileEntry *FE = static_cast<FileEntry *>(File);
7965
7966 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7967 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7968 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7969
Richard Smithfeb54b62014-10-23 02:01:19 +00007970 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007971}
7972
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007973CXFile clang_Module_getASTFile(CXModule CXMod) {
7974 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007975 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007976 Module *Mod = static_cast<Module*>(CXMod);
7977 return const_cast<FileEntry *>(Mod->getASTFile());
7978}
7979
Guy Benyei11169dd2012-12-18 14:30:41 +00007980CXModule clang_Module_getParent(CXModule CXMod) {
7981 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007982 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007983 Module *Mod = static_cast<Module*>(CXMod);
7984 return Mod->Parent;
7985}
7986
7987CXString clang_Module_getName(CXModule CXMod) {
7988 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007989 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007990 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007991 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007992}
7993
7994CXString clang_Module_getFullName(CXModule CXMod) {
7995 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007996 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007997 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007998 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007999}
8000
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008001int clang_Module_isSystem(CXModule CXMod) {
8002 if (!CXMod)
8003 return 0;
8004 Module *Mod = static_cast<Module*>(CXMod);
8005 return Mod->IsSystem;
8006}
8007
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008008unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8009 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008010 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008011 LOG_BAD_TU(TU);
8012 return 0;
8013 }
8014 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008015 return 0;
8016 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008017 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8018 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8019 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008020}
8021
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008022CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8023 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008024 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008025 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008026 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008027 }
8028 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008029 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008031 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008032
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008033 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8034 if (Index < TopHeaders.size())
8035 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008036
Craig Topper69186e72014-06-08 08:38:04 +00008037 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008038}
8039
Guy Benyei11169dd2012-12-18 14:30:41 +00008040//===----------------------------------------------------------------------===//
8041// C++ AST instrospection.
8042//===----------------------------------------------------------------------===//
8043
Jonathan Coe29565352016-04-27 12:48:25 +00008044unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8045 if (!clang_isDeclaration(C.kind))
8046 return 0;
8047
8048 const Decl *D = cxcursor::getCursorDecl(C);
8049 const CXXConstructorDecl *Constructor =
8050 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8051 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8052}
8053
8054unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8055 if (!clang_isDeclaration(C.kind))
8056 return 0;
8057
8058 const Decl *D = cxcursor::getCursorDecl(C);
8059 const CXXConstructorDecl *Constructor =
8060 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8061 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8062}
8063
8064unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8065 if (!clang_isDeclaration(C.kind))
8066 return 0;
8067
8068 const Decl *D = cxcursor::getCursorDecl(C);
8069 const CXXConstructorDecl *Constructor =
8070 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8071 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8072}
8073
8074unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8075 if (!clang_isDeclaration(C.kind))
8076 return 0;
8077
8078 const Decl *D = cxcursor::getCursorDecl(C);
8079 const CXXConstructorDecl *Constructor =
8080 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8081 // Passing 'false' excludes constructors marked 'explicit'.
8082 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8083}
8084
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008085unsigned clang_CXXField_isMutable(CXCursor C) {
8086 if (!clang_isDeclaration(C.kind))
8087 return 0;
8088
8089 if (const auto D = cxcursor::getCursorDecl(C))
8090 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8091 return FD->isMutable() ? 1 : 0;
8092 return 0;
8093}
8094
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008095unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8096 if (!clang_isDeclaration(C.kind))
8097 return 0;
8098
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008099 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008100 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008101 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008102 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8103}
8104
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008105unsigned clang_CXXMethod_isConst(CXCursor C) {
8106 if (!clang_isDeclaration(C.kind))
8107 return 0;
8108
8109 const Decl *D = cxcursor::getCursorDecl(C);
8110 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008111 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008112 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
8113}
8114
Jonathan Coe29565352016-04-27 12:48:25 +00008115unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8116 if (!clang_isDeclaration(C.kind))
8117 return 0;
8118
8119 const Decl *D = cxcursor::getCursorDecl(C);
8120 const CXXMethodDecl *Method =
8121 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8122 return (Method && Method->isDefaulted()) ? 1 : 0;
8123}
8124
Guy Benyei11169dd2012-12-18 14:30:41 +00008125unsigned clang_CXXMethod_isStatic(CXCursor C) {
8126 if (!clang_isDeclaration(C.kind))
8127 return 0;
8128
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008129 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008130 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008131 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008132 return (Method && Method->isStatic()) ? 1 : 0;
8133}
8134
8135unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8136 if (!clang_isDeclaration(C.kind))
8137 return 0;
8138
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008139 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008140 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008141 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008142 return (Method && Method->isVirtual()) ? 1 : 0;
8143}
Guy Benyei11169dd2012-12-18 14:30:41 +00008144
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008145unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8146 if (!clang_isDeclaration(C.kind))
8147 return 0;
8148
8149 const auto *D = cxcursor::getCursorDecl(C);
8150 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8151 if (RD)
8152 RD = RD->getDefinition();
8153 return (RD && RD->isAbstract()) ? 1 : 0;
8154}
8155
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008156unsigned clang_EnumDecl_isScoped(CXCursor C) {
8157 if (!clang_isDeclaration(C.kind))
8158 return 0;
8159
8160 const Decl *D = cxcursor::getCursorDecl(C);
8161 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8162 return (Enum && Enum->isScoped()) ? 1 : 0;
8163}
8164
Guy Benyei11169dd2012-12-18 14:30:41 +00008165//===----------------------------------------------------------------------===//
8166// Attribute introspection.
8167//===----------------------------------------------------------------------===//
8168
Guy Benyei11169dd2012-12-18 14:30:41 +00008169CXType clang_getIBOutletCollectionType(CXCursor C) {
8170 if (C.kind != CXCursor_IBOutletCollectionAttr)
8171 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8172
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008173 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008174 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8175
8176 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8177}
Guy Benyei11169dd2012-12-18 14:30:41 +00008178
8179//===----------------------------------------------------------------------===//
8180// Inspecting memory usage.
8181//===----------------------------------------------------------------------===//
8182
8183typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8184
8185static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8186 enum CXTUResourceUsageKind k,
8187 unsigned long amount) {
8188 CXTUResourceUsageEntry entry = { k, amount };
8189 entries.push_back(entry);
8190}
8191
Guy Benyei11169dd2012-12-18 14:30:41 +00008192const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8193 const char *str = "";
8194 switch (kind) {
8195 case CXTUResourceUsage_AST:
8196 str = "ASTContext: expressions, declarations, and types";
8197 break;
8198 case CXTUResourceUsage_Identifiers:
8199 str = "ASTContext: identifiers";
8200 break;
8201 case CXTUResourceUsage_Selectors:
8202 str = "ASTContext: selectors";
8203 break;
8204 case CXTUResourceUsage_GlobalCompletionResults:
8205 str = "Code completion: cached global results";
8206 break;
8207 case CXTUResourceUsage_SourceManagerContentCache:
8208 str = "SourceManager: content cache allocator";
8209 break;
8210 case CXTUResourceUsage_AST_SideTables:
8211 str = "ASTContext: side tables";
8212 break;
8213 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8214 str = "SourceManager: malloc'ed memory buffers";
8215 break;
8216 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8217 str = "SourceManager: mmap'ed memory buffers";
8218 break;
8219 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8220 str = "ExternalASTSource: malloc'ed memory buffers";
8221 break;
8222 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8223 str = "ExternalASTSource: mmap'ed memory buffers";
8224 break;
8225 case CXTUResourceUsage_Preprocessor:
8226 str = "Preprocessor: malloc'ed memory";
8227 break;
8228 case CXTUResourceUsage_PreprocessingRecord:
8229 str = "Preprocessor: PreprocessingRecord";
8230 break;
8231 case CXTUResourceUsage_SourceManager_DataStructures:
8232 str = "SourceManager: data structures and tables";
8233 break;
8234 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8235 str = "Preprocessor: header search tables";
8236 break;
8237 }
8238 return str;
8239}
8240
8241CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008242 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008243 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008244 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008245 return usage;
8246 }
8247
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008248 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008249 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 ASTContext &astContext = astUnit->getASTContext();
8251
8252 // How much memory is used by AST nodes and types?
8253 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8254 (unsigned long) astContext.getASTAllocatedMemory());
8255
8256 // How much memory is used by identifiers?
8257 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8258 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8259
8260 // How much memory is used for selectors?
8261 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8262 (unsigned long) astContext.Selectors.getTotalMemory());
8263
8264 // How much memory is used by ASTContext's side tables?
8265 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8266 (unsigned long) astContext.getSideTableAllocatedMemory());
8267
8268 // How much memory is used for caching global code completion results?
8269 unsigned long completionBytes = 0;
8270 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008271 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008272 completionBytes = completionAllocator->getTotalMemory();
8273 }
8274 createCXTUResourceUsageEntry(*entries,
8275 CXTUResourceUsage_GlobalCompletionResults,
8276 completionBytes);
8277
8278 // How much memory is being used by SourceManager's content cache?
8279 createCXTUResourceUsageEntry(*entries,
8280 CXTUResourceUsage_SourceManagerContentCache,
8281 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8282
8283 // How much memory is being used by the MemoryBuffer's in SourceManager?
8284 const SourceManager::MemoryBufferSizes &srcBufs =
8285 astUnit->getSourceManager().getMemoryBufferSizes();
8286
8287 createCXTUResourceUsageEntry(*entries,
8288 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8289 (unsigned long) srcBufs.malloc_bytes);
8290 createCXTUResourceUsageEntry(*entries,
8291 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8292 (unsigned long) srcBufs.mmap_bytes);
8293 createCXTUResourceUsageEntry(*entries,
8294 CXTUResourceUsage_SourceManager_DataStructures,
8295 (unsigned long) astContext.getSourceManager()
8296 .getDataStructureSizes());
8297
8298 // How much memory is being used by the ExternalASTSource?
8299 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8300 const ExternalASTSource::MemoryBufferSizes &sizes =
8301 esrc->getMemoryBufferSizes();
8302
8303 createCXTUResourceUsageEntry(*entries,
8304 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8305 (unsigned long) sizes.malloc_bytes);
8306 createCXTUResourceUsageEntry(*entries,
8307 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8308 (unsigned long) sizes.mmap_bytes);
8309 }
8310
8311 // How much memory is being used by the Preprocessor?
8312 Preprocessor &pp = astUnit->getPreprocessor();
8313 createCXTUResourceUsageEntry(*entries,
8314 CXTUResourceUsage_Preprocessor,
8315 pp.getTotalMemory());
8316
8317 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8318 createCXTUResourceUsageEntry(*entries,
8319 CXTUResourceUsage_PreprocessingRecord,
8320 pRec->getTotalMemory());
8321 }
8322
8323 createCXTUResourceUsageEntry(*entries,
8324 CXTUResourceUsage_Preprocessor_HeaderSearch,
8325 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008326
Guy Benyei11169dd2012-12-18 14:30:41 +00008327 CXTUResourceUsage usage = { (void*) entries.get(),
8328 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008329 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008330 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008331 return usage;
8332}
8333
8334void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8335 if (usage.data)
8336 delete (MemUsageEntries*) usage.data;
8337}
8338
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008339CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8340 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008341 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008342 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008343
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008344 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008345 LOG_BAD_TU(TU);
8346 return skipped;
8347 }
8348
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008349 if (!file)
8350 return skipped;
8351
8352 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8353 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8354 if (!ppRec)
8355 return skipped;
8356
8357 ASTContext &Ctx = astUnit->getASTContext();
8358 SourceManager &sm = Ctx.getSourceManager();
8359 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8360 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008361 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008362
8363 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8364 std::vector<SourceRange> wantedRanges;
8365 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8366 i != ei; ++i) {
8367 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8368 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008369 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8370 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008371 }
8372
8373 skipped->count = wantedRanges.size();
8374 skipped->ranges = new CXSourceRange[skipped->count];
8375 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8376 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8377
8378 return skipped;
8379}
8380
Cameron Desrochersd8091282016-08-18 15:43:55 +00008381CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8382 CXSourceRangeList *skipped = new CXSourceRangeList;
8383 skipped->count = 0;
8384 skipped->ranges = nullptr;
8385
8386 if (isNotUsableTU(TU)) {
8387 LOG_BAD_TU(TU);
8388 return skipped;
8389 }
8390
8391 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8392 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8393 if (!ppRec)
8394 return skipped;
8395
8396 ASTContext &Ctx = astUnit->getASTContext();
8397
8398 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8399
8400 skipped->count = SkippedRanges.size();
8401 skipped->ranges = new CXSourceRange[skipped->count];
8402 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8403 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8404
8405 return skipped;
8406}
8407
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008408void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8409 if (ranges) {
8410 delete[] ranges->ranges;
8411 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008412 }
8413}
8414
Guy Benyei11169dd2012-12-18 14:30:41 +00008415void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8416 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8417 for (unsigned I = 0; I != Usage.numEntries; ++I)
8418 fprintf(stderr, " %s: %lu\n",
8419 clang_getTUResourceUsageName(Usage.entries[I].kind),
8420 Usage.entries[I].amount);
8421
8422 clang_disposeCXTUResourceUsage(Usage);
8423}
8424
8425//===----------------------------------------------------------------------===//
8426// Misc. utility functions.
8427//===----------------------------------------------------------------------===//
8428
8429/// Default to using an 8 MB stack size on "safety" threads.
8430static unsigned SafetyStackThreadSize = 8 << 20;
8431
8432namespace clang {
8433
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008434bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008435 unsigned Size) {
8436 if (!Size)
8437 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008438 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008439 return CRC.RunSafelyOnThread(Fn, Size);
8440 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008441}
8442
8443unsigned GetSafetyThreadStackSize() {
8444 return SafetyStackThreadSize;
8445}
8446
8447void SetSafetyThreadStackSize(unsigned Value) {
8448 SafetyStackThreadSize = Value;
8449}
8450
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008451}
Guy Benyei11169dd2012-12-18 14:30:41 +00008452
8453void clang::setThreadBackgroundPriority() {
8454 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8455 return;
8456
Alp Toker1a86ad22014-07-06 06:24:00 +00008457#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008458 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8459#endif
8460}
8461
8462void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8463 if (!Unit)
8464 return;
8465
8466 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8467 DEnd = Unit->stored_diag_end();
8468 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008469 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008470 CXString Msg = clang_formatDiagnostic(&Diag,
8471 clang_defaultDiagnosticDisplayOptions());
8472 fprintf(stderr, "%s\n", clang_getCString(Msg));
8473 clang_disposeString(Msg);
8474 }
8475#ifdef LLVM_ON_WIN32
8476 // On Windows, force a flush, since there may be multiple copies of
8477 // stderr and stdout in the file system, all with different buffers
8478 // but writing to the same device.
8479 fflush(stderr);
8480#endif
8481}
8482
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008483MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8484 SourceLocation MacroDefLoc,
8485 CXTranslationUnit TU){
8486 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008487 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008488 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008489 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008490
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008491 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008492 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008493 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008494 if (MD) {
8495 for (MacroDirective::DefInfo
8496 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8497 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8498 return Def.getMacroInfo();
8499 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008500 }
8501
Craig Topper69186e72014-06-08 08:38:04 +00008502 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008503}
8504
Richard Smith66a81862015-05-04 02:25:31 +00008505const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008506 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008507 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008508 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008509 const IdentifierInfo *II = MacroDef->getName();
8510 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008511 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008512
8513 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8514}
8515
Richard Smith66a81862015-05-04 02:25:31 +00008516MacroDefinitionRecord *
8517cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8518 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008519 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008520 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008521 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008522 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008523
8524 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008525 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008526 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8527 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008528 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008529
8530 // Check that the token is inside the definition and not its argument list.
8531 SourceManager &SM = Unit->getSourceManager();
8532 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008533 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008534 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008535 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008536
8537 Preprocessor &PP = Unit->getPreprocessor();
8538 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8539 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008540 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008541
Alp Toker2d57cea2014-05-17 04:53:25 +00008542 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008543 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008544 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008545
8546 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008547 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008548 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008549
Richard Smith20e883e2015-04-29 23:20:19 +00008550 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008551 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008552 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008553
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008554 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008555}
8556
Richard Smith66a81862015-05-04 02:25:31 +00008557MacroDefinitionRecord *
8558cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8559 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008560 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008561 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008562
8563 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008564 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008565 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008566 Preprocessor &PP = Unit->getPreprocessor();
8567 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008568 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008569 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8570 Token Tok;
8571 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008572 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008573
8574 return checkForMacroInMacroDefinition(MI, Tok, TU);
8575}
8576
Guy Benyei11169dd2012-12-18 14:30:41 +00008577CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008578 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008579}
8580
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008581Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8582 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008583 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008584 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008585 if (Unit->isMainFileAST())
8586 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008587 return *this;
8588 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008589 } else {
8590 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008591 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008592 return *this;
8593}
8594
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008595Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8596 *this << FE->getName();
8597 return *this;
8598}
8599
8600Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8601 CXString cursorName = clang_getCursorDisplayName(cursor);
8602 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8603 clang_disposeString(cursorName);
8604 return *this;
8605}
8606
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008607Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8608 CXFile File;
8609 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008610 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008611 CXString FileName = clang_getFileName(File);
8612 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8613 clang_disposeString(FileName);
8614 return *this;
8615}
8616
8617Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8618 CXSourceLocation BLoc = clang_getRangeStart(range);
8619 CXSourceLocation ELoc = clang_getRangeEnd(range);
8620
8621 CXFile BFile;
8622 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008623 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008624
8625 CXFile EFile;
8626 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008627 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008628
8629 CXString BFileName = clang_getFileName(BFile);
8630 if (BFile == EFile) {
8631 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8632 BLine, BColumn, ELine, EColumn);
8633 } else {
8634 CXString EFileName = clang_getFileName(EFile);
8635 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8636 BLine, BColumn)
8637 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8638 ELine, EColumn);
8639 clang_disposeString(EFileName);
8640 }
8641 clang_disposeString(BFileName);
8642 return *this;
8643}
8644
8645Logger &cxindex::Logger::operator<<(CXString Str) {
8646 *this << clang_getCString(Str);
8647 return *this;
8648}
8649
8650Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8651 LogOS << Fmt;
8652 return *this;
8653}
8654
Chandler Carruth37ad2582014-06-27 15:14:39 +00008655static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8656
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008657cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008658 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008659
8660 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8661
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008662 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008663 OS << "[libclang:" << Name << ':';
8664
Alp Toker1a86ad22014-07-06 06:24:00 +00008665#ifdef USE_DARWIN_THREADS
8666 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008667 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8668 OS << tid << ':';
8669#endif
8670
8671 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8672 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008673 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008674
8675 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008676 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008677 OS << "--------------------------------------------------\n";
8678 }
8679}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008680
8681#ifdef CLANG_TOOL_EXTRA_BUILD
8682// This anchor is used to force the linker to link the clang-tidy plugin.
8683extern volatile int ClangTidyPluginAnchorSource;
8684static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8685 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008686
8687// This anchor is used to force the linker to link the clang-include-fixer
8688// plugin.
8689extern volatile int ClangIncludeFixerPluginAnchorSource;
8690static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8691 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008692#endif