blob: 791b475975437a42a516e4564aef75f8dcf5344e [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.
1042 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001043 [&SM](Decl *A, Decl *B) {
1044 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())
1799 if (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
2596 // real field that that we are interested in.
2597 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
Guy Benyei11169dd2012-12-18 14:30:41 +00004252//===----------------------------------------------------------------------===//
4253// CXCursor Operations.
4254//===----------------------------------------------------------------------===//
4255
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004256static const Decl *getDeclFromExpr(const Stmt *E) {
4257 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 return getDeclFromExpr(CE->getSubExpr());
4259
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004260 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004261 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004262 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004264 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004266 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 if (PRE->isExplicitProperty())
4268 return PRE->getExplicitProperty();
4269 // It could be messaging both getter and setter as in:
4270 // ++myobj.myprop;
4271 // in which case prefer to associate the setter since it is less obvious
4272 // from inspecting the source that the setter is going to get called.
4273 if (PRE->isMessagingSetter())
4274 return PRE->getImplicitPropertySetter();
4275 return PRE->getImplicitPropertyGetter();
4276 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004277 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004279 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004280 if (Expr *Src = OVE->getSourceExpr())
4281 return getDeclFromExpr(Src);
4282
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004283 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004285 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 if (!CE->isElidable())
4287 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004288 if (const CXXInheritedCtorInitExpr *CE =
4289 dyn_cast<CXXInheritedCtorInitExpr>(E))
4290 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004291 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 return OME->getMethodDecl();
4293
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004294 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004296 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4298 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004299 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4301 isa<ParmVarDecl>(SizeOfPack->getPack()))
4302 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004303
4304 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004305}
4306
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004307static SourceLocation getLocationFromExpr(const Expr *E) {
4308 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 return getLocationFromExpr(CE->getSubExpr());
4310
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004311 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004313 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004315 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004317 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004318 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004319 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004321 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 return PropRef->getLocation();
4323
4324 return E->getLocStart();
4325}
4326
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004327extern "C" {
4328
Guy Benyei11169dd2012-12-18 14:30:41 +00004329unsigned clang_visitChildren(CXCursor parent,
4330 CXCursorVisitor visitor,
4331 CXClientData client_data) {
4332 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4333 /*VisitPreprocessorLast=*/false);
4334 return CursorVis.VisitChildren(parent);
4335}
4336
4337#ifndef __has_feature
4338#define __has_feature(x) 0
4339#endif
4340#if __has_feature(blocks)
4341typedef enum CXChildVisitResult
4342 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4343
4344static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4345 CXClientData client_data) {
4346 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4347 return block(cursor, parent);
4348}
4349#else
4350// If we are compiled with a compiler that doesn't have native blocks support,
4351// define and call the block manually, so the
4352typedef struct _CXChildVisitResult
4353{
4354 void *isa;
4355 int flags;
4356 int reserved;
4357 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4358 CXCursor);
4359} *CXCursorVisitorBlock;
4360
4361static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4362 CXClientData client_data) {
4363 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4364 return block->invoke(block, cursor, parent);
4365}
4366#endif
4367
4368
4369unsigned clang_visitChildrenWithBlock(CXCursor parent,
4370 CXCursorVisitorBlock block) {
4371 return clang_visitChildren(parent, visitWithBlock, block);
4372}
4373
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004374static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004376 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004377
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004378 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004380 if (const ObjCPropertyImplDecl *PropImpl =
4381 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004383 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004384
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004385 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004386 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004387 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004388
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004389 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 }
4391
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004392 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004393 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004394
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004395 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4397 // and returns different names. NamedDecl returns the class name and
4398 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004399 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004400
4401 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004402 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004403
4404 SmallString<1024> S;
4405 llvm::raw_svector_ostream os(S);
4406 ND->printName(os);
4407
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004408 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004409}
4410
4411CXString clang_getCursorSpelling(CXCursor C) {
4412 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004413 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004414
4415 if (clang_isReference(C.kind)) {
4416 switch (C.kind) {
4417 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004418 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004419 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 }
4421 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004422 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004423 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 }
4425 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004426 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004428 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 }
4430 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004431 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004432 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 }
4434 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004435 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 assert(Type && "Missing type decl");
4437
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004438 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 getAsString());
4440 }
4441 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004442 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 assert(Template && "Missing template decl");
4444
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004445 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 }
4447
4448 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004449 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 assert(NS && "Missing namespace decl");
4451
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004452 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 }
4454
4455 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004456 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 assert(Field && "Missing member decl");
4458
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004459 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 }
4461
4462 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004463 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 assert(Label && "Missing label");
4465
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004466 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 }
4468
4469 case CXCursor_OverloadedDeclRef: {
4470 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004471 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4472 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004473 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004474 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004476 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004477 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 OverloadedTemplateStorage *Ovl
4479 = Storage.get<OverloadedTemplateStorage*>();
4480 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004481 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004482 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 }
4484
4485 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004486 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 assert(Var && "Missing variable decl");
4488
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004489 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 }
4491
4492 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004493 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 }
4495 }
4496
4497 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004498 const Expr *E = getCursorExpr(C);
4499
4500 if (C.kind == CXCursor_ObjCStringLiteral ||
4501 C.kind == CXCursor_StringLiteral) {
4502 const StringLiteral *SLit;
4503 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4504 SLit = OSL->getString();
4505 } else {
4506 SLit = cast<StringLiteral>(E);
4507 }
4508 SmallString<256> Buf;
4509 llvm::raw_svector_ostream OS(Buf);
4510 SLit->outputString(OS);
4511 return cxstring::createDup(OS.str());
4512 }
4513
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004514 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 if (D)
4516 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004517 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 }
4519
4520 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004521 const Stmt *S = getCursorStmt(C);
4522 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004523 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004524
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004525 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004526 }
4527
4528 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004529 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004530 ->getNameStart());
4531
4532 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004533 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 ->getNameStart());
4535
4536 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004537 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004538
4539 if (clang_isDeclaration(C.kind))
4540 return getDeclSpelling(getCursorDecl(C));
4541
4542 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004543 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004544 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 }
4546
4547 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004548 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004549 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 }
4551
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004552 if (C.kind == CXCursor_PackedAttr) {
4553 return cxstring::createRef("packed");
4554 }
4555
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004556 if (C.kind == CXCursor_VisibilityAttr) {
4557 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4558 switch (AA->getVisibility()) {
4559 case VisibilityAttr::VisibilityType::Default:
4560 return cxstring::createRef("default");
4561 case VisibilityAttr::VisibilityType::Hidden:
4562 return cxstring::createRef("hidden");
4563 case VisibilityAttr::VisibilityType::Protected:
4564 return cxstring::createRef("protected");
4565 }
4566 llvm_unreachable("unknown visibility type");
4567 }
4568
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004569 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004570}
4571
4572CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4573 unsigned pieceIndex,
4574 unsigned options) {
4575 if (clang_Cursor_isNull(C))
4576 return clang_getNullRange();
4577
4578 ASTContext &Ctx = getCursorContext(C);
4579
4580 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004581 const Stmt *S = getCursorStmt(C);
4582 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 if (pieceIndex > 0)
4584 return clang_getNullRange();
4585 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4586 }
4587
4588 return clang_getNullRange();
4589 }
4590
4591 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004592 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4594 if (pieceIndex >= ME->getNumSelectorLocs())
4595 return clang_getNullRange();
4596 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4597 }
4598 }
4599
4600 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4601 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004602 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4604 if (pieceIndex >= MD->getNumSelectorLocs())
4605 return clang_getNullRange();
4606 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4607 }
4608 }
4609
4610 if (C.kind == CXCursor_ObjCCategoryDecl ||
4611 C.kind == CXCursor_ObjCCategoryImplDecl) {
4612 if (pieceIndex > 0)
4613 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004614 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4616 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004617 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4619 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4620 }
4621
4622 if (C.kind == CXCursor_ModuleImportDecl) {
4623 if (pieceIndex > 0)
4624 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004625 if (const ImportDecl *ImportD =
4626 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4628 if (!Locs.empty())
4629 return cxloc::translateSourceRange(Ctx,
4630 SourceRange(Locs.front(), Locs.back()));
4631 }
4632 return clang_getNullRange();
4633 }
4634
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004635 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004636 C.kind == CXCursor_ConversionFunction ||
4637 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004638 if (pieceIndex > 0)
4639 return clang_getNullRange();
4640 if (const FunctionDecl *FD =
4641 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4642 DeclarationNameInfo FunctionName = FD->getNameInfo();
4643 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4644 }
4645 return clang_getNullRange();
4646 }
4647
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 // FIXME: A CXCursor_InclusionDirective should give the location of the
4649 // filename, but we don't keep track of this.
4650
4651 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4652 // but we don't keep track of this.
4653
4654 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4655 // but we don't keep track of this.
4656
4657 // Default handling, give the location of the cursor.
4658
4659 if (pieceIndex > 0)
4660 return clang_getNullRange();
4661
4662 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4663 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4664 return cxloc::translateSourceRange(Ctx, Loc);
4665}
4666
Eli Bendersky44a206f2014-07-31 18:04:56 +00004667CXString clang_Cursor_getMangling(CXCursor C) {
4668 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4669 return cxstring::createEmpty();
4670
Eli Bendersky44a206f2014-07-31 18:04:56 +00004671 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004672 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004673 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4674 return cxstring::createEmpty();
4675
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004676 ASTContext &Ctx = D->getASTContext();
4677 index::CodegenNameGenerator CGNameGen(Ctx);
4678 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004679}
4680
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004681CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4682 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4683 return nullptr;
4684
4685 const Decl *D = getCursorDecl(C);
4686 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4687 return nullptr;
4688
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004689 ASTContext &Ctx = D->getASTContext();
4690 index::CodegenNameGenerator CGNameGen(Ctx);
4691 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004692 return cxstring::createSet(Manglings);
4693}
4694
Dave Lee1a532c92017-09-22 16:58:57 +00004695CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4696 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4697 return nullptr;
4698
4699 const Decl *D = getCursorDecl(C);
4700 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4701 return nullptr;
4702
4703 ASTContext &Ctx = D->getASTContext();
4704 index::CodegenNameGenerator CGNameGen(Ctx);
4705 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4706 return cxstring::createSet(Manglings);
4707}
4708
Jonathan Coe45ef5032018-01-16 10:19:56 +00004709CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4710 if (clang_Cursor_isNull(C))
4711 return 0;
4712 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4713}
4714
4715void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4716 if (Policy)
4717 delete static_cast<PrintingPolicy *>(Policy);
4718}
4719
4720unsigned
4721clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4722 enum CXPrintingPolicyProperty Property) {
4723 if (!Policy)
4724 return 0;
4725
4726 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4727 switch (Property) {
4728 case CXPrintingPolicy_Indentation:
4729 return P->Indentation;
4730 case CXPrintingPolicy_SuppressSpecifiers:
4731 return P->SuppressSpecifiers;
4732 case CXPrintingPolicy_SuppressTagKeyword:
4733 return P->SuppressTagKeyword;
4734 case CXPrintingPolicy_IncludeTagDefinition:
4735 return P->IncludeTagDefinition;
4736 case CXPrintingPolicy_SuppressScope:
4737 return P->SuppressScope;
4738 case CXPrintingPolicy_SuppressUnwrittenScope:
4739 return P->SuppressUnwrittenScope;
4740 case CXPrintingPolicy_SuppressInitializers:
4741 return P->SuppressInitializers;
4742 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4743 return P->ConstantArraySizeAsWritten;
4744 case CXPrintingPolicy_AnonymousTagLocations:
4745 return P->AnonymousTagLocations;
4746 case CXPrintingPolicy_SuppressStrongLifetime:
4747 return P->SuppressStrongLifetime;
4748 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4749 return P->SuppressLifetimeQualifiers;
4750 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4751 return P->SuppressTemplateArgsInCXXConstructors;
4752 case CXPrintingPolicy_Bool:
4753 return P->Bool;
4754 case CXPrintingPolicy_Restrict:
4755 return P->Restrict;
4756 case CXPrintingPolicy_Alignof:
4757 return P->Alignof;
4758 case CXPrintingPolicy_UnderscoreAlignof:
4759 return P->UnderscoreAlignof;
4760 case CXPrintingPolicy_UseVoidForZeroParams:
4761 return P->UseVoidForZeroParams;
4762 case CXPrintingPolicy_TerseOutput:
4763 return P->TerseOutput;
4764 case CXPrintingPolicy_PolishForDeclaration:
4765 return P->PolishForDeclaration;
4766 case CXPrintingPolicy_Half:
4767 return P->Half;
4768 case CXPrintingPolicy_MSWChar:
4769 return P->MSWChar;
4770 case CXPrintingPolicy_IncludeNewlines:
4771 return P->IncludeNewlines;
4772 case CXPrintingPolicy_MSVCFormatting:
4773 return P->MSVCFormatting;
4774 case CXPrintingPolicy_ConstantsAsWritten:
4775 return P->ConstantsAsWritten;
4776 case CXPrintingPolicy_SuppressImplicitBase:
4777 return P->SuppressImplicitBase;
4778 case CXPrintingPolicy_FullyQualifiedName:
4779 return P->FullyQualifiedName;
4780 }
4781
4782 assert(false && "Invalid CXPrintingPolicyProperty");
4783 return 0;
4784}
4785
4786void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4787 enum CXPrintingPolicyProperty Property,
4788 unsigned Value) {
4789 if (!Policy)
4790 return;
4791
4792 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4793 switch (Property) {
4794 case CXPrintingPolicy_Indentation:
4795 P->Indentation = Value;
4796 return;
4797 case CXPrintingPolicy_SuppressSpecifiers:
4798 P->SuppressSpecifiers = Value;
4799 return;
4800 case CXPrintingPolicy_SuppressTagKeyword:
4801 P->SuppressTagKeyword = Value;
4802 return;
4803 case CXPrintingPolicy_IncludeTagDefinition:
4804 P->IncludeTagDefinition = Value;
4805 return;
4806 case CXPrintingPolicy_SuppressScope:
4807 P->SuppressScope = Value;
4808 return;
4809 case CXPrintingPolicy_SuppressUnwrittenScope:
4810 P->SuppressUnwrittenScope = Value;
4811 return;
4812 case CXPrintingPolicy_SuppressInitializers:
4813 P->SuppressInitializers = Value;
4814 return;
4815 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4816 P->ConstantArraySizeAsWritten = Value;
4817 return;
4818 case CXPrintingPolicy_AnonymousTagLocations:
4819 P->AnonymousTagLocations = Value;
4820 return;
4821 case CXPrintingPolicy_SuppressStrongLifetime:
4822 P->SuppressStrongLifetime = Value;
4823 return;
4824 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4825 P->SuppressLifetimeQualifiers = Value;
4826 return;
4827 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4828 P->SuppressTemplateArgsInCXXConstructors = Value;
4829 return;
4830 case CXPrintingPolicy_Bool:
4831 P->Bool = Value;
4832 return;
4833 case CXPrintingPolicy_Restrict:
4834 P->Restrict = Value;
4835 return;
4836 case CXPrintingPolicy_Alignof:
4837 P->Alignof = Value;
4838 return;
4839 case CXPrintingPolicy_UnderscoreAlignof:
4840 P->UnderscoreAlignof = Value;
4841 return;
4842 case CXPrintingPolicy_UseVoidForZeroParams:
4843 P->UseVoidForZeroParams = Value;
4844 return;
4845 case CXPrintingPolicy_TerseOutput:
4846 P->TerseOutput = Value;
4847 return;
4848 case CXPrintingPolicy_PolishForDeclaration:
4849 P->PolishForDeclaration = Value;
4850 return;
4851 case CXPrintingPolicy_Half:
4852 P->Half = Value;
4853 return;
4854 case CXPrintingPolicy_MSWChar:
4855 P->MSWChar = Value;
4856 return;
4857 case CXPrintingPolicy_IncludeNewlines:
4858 P->IncludeNewlines = Value;
4859 return;
4860 case CXPrintingPolicy_MSVCFormatting:
4861 P->MSVCFormatting = Value;
4862 return;
4863 case CXPrintingPolicy_ConstantsAsWritten:
4864 P->ConstantsAsWritten = Value;
4865 return;
4866 case CXPrintingPolicy_SuppressImplicitBase:
4867 P->SuppressImplicitBase = Value;
4868 return;
4869 case CXPrintingPolicy_FullyQualifiedName:
4870 P->FullyQualifiedName = Value;
4871 return;
4872 }
4873
4874 assert(false && "Invalid CXPrintingPolicyProperty");
4875}
4876
4877CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4878 if (clang_Cursor_isNull(C))
4879 return cxstring::createEmpty();
4880
4881 if (clang_isDeclaration(C.kind)) {
4882 const Decl *D = getCursorDecl(C);
4883 if (!D)
4884 return cxstring::createEmpty();
4885
4886 SmallString<128> Str;
4887 llvm::raw_svector_ostream OS(Str);
4888 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4889 D->print(OS, UserPolicy ? *UserPolicy
4890 : getCursorContext(C).getPrintingPolicy());
4891
4892 return cxstring::createDup(OS.str());
4893 }
4894
4895 return cxstring::createEmpty();
4896}
4897
Guy Benyei11169dd2012-12-18 14:30:41 +00004898CXString clang_getCursorDisplayName(CXCursor C) {
4899 if (!clang_isDeclaration(C.kind))
4900 return clang_getCursorSpelling(C);
4901
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004902 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004904 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004905
4906 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004907 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 D = FunTmpl->getTemplatedDecl();
4909
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004910 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 SmallString<64> Str;
4912 llvm::raw_svector_ostream OS(Str);
4913 OS << *Function;
4914 if (Function->getPrimaryTemplate())
4915 OS << "<>";
4916 OS << "(";
4917 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4918 if (I)
4919 OS << ", ";
4920 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4921 }
4922
4923 if (Function->isVariadic()) {
4924 if (Function->getNumParams())
4925 OS << ", ";
4926 OS << "...";
4927 }
4928 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004929 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 }
4931
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004932 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 SmallString<64> Str;
4934 llvm::raw_svector_ostream OS(Str);
4935 OS << *ClassTemplate;
4936 OS << "<";
4937 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4938 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4939 if (I)
4940 OS << ", ";
4941
4942 NamedDecl *Param = Params->getParam(I);
4943 if (Param->getIdentifier()) {
4944 OS << Param->getIdentifier()->getName();
4945 continue;
4946 }
4947
4948 // There is no parameter name, which makes this tricky. Try to come up
4949 // with something useful that isn't too long.
4950 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4951 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4952 else if (NonTypeTemplateParmDecl *NTTP
4953 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4954 OS << NTTP->getType().getAsString(Policy);
4955 else
4956 OS << "template<...> class";
4957 }
4958
4959 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004960 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 }
4962
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004963 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4965 // If the type was explicitly written, use that.
4966 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004967 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004968
Benjamin Kramer9170e912013-02-22 15:46:01 +00004969 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004970 llvm::raw_svector_ostream OS(Str);
4971 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00004972 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
4973 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004974 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 }
4976
4977 return clang_getCursorSpelling(C);
4978}
4979
4980CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4981 switch (Kind) {
4982 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004983 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004985 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004987 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004989 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004991 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004992 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004993 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004994 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004995 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004996 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004997 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004999 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005000 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005001 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005002 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005003 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005005 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005007 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005008 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005009 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005011 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005013 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005015 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005017 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005019 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005021 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005023 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005025 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005027 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005029 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005031 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005033 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005035 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005037 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005039 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005041 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005043 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005045 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005047 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005049 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005051 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005053 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005055 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005057 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005059 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005060 case CXCursor_OMPArraySectionExpr:
5061 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005063 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005065 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005067 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005069 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005071 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005073 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005075 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005077 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005079 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005081 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005083 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005085 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005087 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005089 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005091 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005093 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005097 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005101 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005112 case CXCursor_ObjCAvailabilityCheckExpr:
5113 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005114 case CXCursor_ObjCSelfExpr:
5115 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005204 case CXCursor_SEHLeaveStmt:
5205 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005234 case CXCursor_PackedAttr:
5235 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005236 case CXCursor_PureAttr:
5237 return cxstring::createRef("attribute(pure)");
5238 case CXCursor_ConstAttr:
5239 return cxstring::createRef("attribute(const)");
5240 case CXCursor_NoDuplicateAttr:
5241 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005242 case CXCursor_CUDAConstantAttr:
5243 return cxstring::createRef("attribute(constant)");
5244 case CXCursor_CUDADeviceAttr:
5245 return cxstring::createRef("attribute(device)");
5246 case CXCursor_CUDAGlobalAttr:
5247 return cxstring::createRef("attribute(global)");
5248 case CXCursor_CUDAHostAttr:
5249 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005250 case CXCursor_CUDASharedAttr:
5251 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005252 case CXCursor_VisibilityAttr:
5253 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005254 case CXCursor_DLLExport:
5255 return cxstring::createRef("attribute(dllexport)");
5256 case CXCursor_DLLImport:
5257 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005265 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005277 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005297 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005306 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005307 return cxstring::createRef("OMPParallelDirective");
5308 case CXCursor_OMPSimdDirective:
5309 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005310 case CXCursor_OMPForDirective:
5311 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005312 case CXCursor_OMPForSimdDirective:
5313 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005314 case CXCursor_OMPSectionsDirective:
5315 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005316 case CXCursor_OMPSectionDirective:
5317 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005318 case CXCursor_OMPSingleDirective:
5319 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005320 case CXCursor_OMPMasterDirective:
5321 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005322 case CXCursor_OMPCriticalDirective:
5323 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005324 case CXCursor_OMPParallelForDirective:
5325 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005326 case CXCursor_OMPParallelForSimdDirective:
5327 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005328 case CXCursor_OMPParallelSectionsDirective:
5329 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005330 case CXCursor_OMPTaskDirective:
5331 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005332 case CXCursor_OMPTaskyieldDirective:
5333 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005334 case CXCursor_OMPBarrierDirective:
5335 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005336 case CXCursor_OMPTaskwaitDirective:
5337 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005338 case CXCursor_OMPTaskgroupDirective:
5339 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005340 case CXCursor_OMPFlushDirective:
5341 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005342 case CXCursor_OMPOrderedDirective:
5343 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005344 case CXCursor_OMPAtomicDirective:
5345 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005346 case CXCursor_OMPTargetDirective:
5347 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005348 case CXCursor_OMPTargetDataDirective:
5349 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005350 case CXCursor_OMPTargetEnterDataDirective:
5351 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005352 case CXCursor_OMPTargetExitDataDirective:
5353 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005354 case CXCursor_OMPTargetParallelDirective:
5355 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005356 case CXCursor_OMPTargetParallelForDirective:
5357 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005358 case CXCursor_OMPTargetUpdateDirective:
5359 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005360 case CXCursor_OMPTeamsDirective:
5361 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005362 case CXCursor_OMPCancellationPointDirective:
5363 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005364 case CXCursor_OMPCancelDirective:
5365 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005366 case CXCursor_OMPTaskLoopDirective:
5367 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005368 case CXCursor_OMPTaskLoopSimdDirective:
5369 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005370 case CXCursor_OMPDistributeDirective:
5371 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005372 case CXCursor_OMPDistributeParallelForDirective:
5373 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005374 case CXCursor_OMPDistributeParallelForSimdDirective:
5375 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005376 case CXCursor_OMPDistributeSimdDirective:
5377 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005378 case CXCursor_OMPTargetParallelForSimdDirective:
5379 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005380 case CXCursor_OMPTargetSimdDirective:
5381 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005382 case CXCursor_OMPTeamsDistributeDirective:
5383 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005384 case CXCursor_OMPTeamsDistributeSimdDirective:
5385 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005386 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5387 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005388 case CXCursor_OMPTeamsDistributeParallelForDirective:
5389 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005390 case CXCursor_OMPTargetTeamsDirective:
5391 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005392 case CXCursor_OMPTargetTeamsDistributeDirective:
5393 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005394 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5395 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005396 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5397 return cxstring::createRef(
5398 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005399 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5400 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005401 case CXCursor_OverloadCandidate:
5402 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005403 case CXCursor_TypeAliasTemplateDecl:
5404 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005405 case CXCursor_StaticAssert:
5406 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005407 case CXCursor_FriendDecl:
5408 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005409 }
5410
5411 llvm_unreachable("Unhandled CXCursorKind");
5412}
5413
5414struct GetCursorData {
5415 SourceLocation TokenBeginLoc;
5416 bool PointsAtMacroArgExpansion;
5417 bool VisitedObjCPropertyImplDecl;
5418 SourceLocation VisitedDeclaratorDeclStartLoc;
5419 CXCursor &BestCursor;
5420
5421 GetCursorData(SourceManager &SM,
5422 SourceLocation tokenBegin, CXCursor &outputCursor)
5423 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5424 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5425 VisitedObjCPropertyImplDecl = false;
5426 }
5427};
5428
5429static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5430 CXCursor parent,
5431 CXClientData client_data) {
5432 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5433 CXCursor *BestCursor = &Data->BestCursor;
5434
5435 // If we point inside a macro argument we should provide info of what the
5436 // token is so use the actual cursor, don't replace it with a macro expansion
5437 // cursor.
5438 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5439 return CXChildVisit_Recurse;
5440
5441 if (clang_isDeclaration(cursor.kind)) {
5442 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005443 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005444 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5445 if (MD->isImplicit())
5446 return CXChildVisit_Break;
5447
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005448 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005449 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5450 // Check that when we have multiple @class references in the same line,
5451 // that later ones do not override the previous ones.
5452 // If we have:
5453 // @class Foo, Bar;
5454 // source ranges for both start at '@', so 'Bar' will end up overriding
5455 // 'Foo' even though the cursor location was at 'Foo'.
5456 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5457 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005458 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005459 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5460 if (PrevID != ID &&
5461 !PrevID->isThisDeclarationADefinition() &&
5462 !ID->isThisDeclarationADefinition())
5463 return CXChildVisit_Break;
5464 }
5465
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005466 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005467 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5468 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5469 // Check that when we have multiple declarators in the same line,
5470 // that later ones do not override the previous ones.
5471 // If we have:
5472 // int Foo, Bar;
5473 // source ranges for both start at 'int', so 'Bar' will end up overriding
5474 // 'Foo' even though the cursor location was at 'Foo'.
5475 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5476 return CXChildVisit_Break;
5477 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5478
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005479 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005480 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5481 (void)PropImp;
5482 // Check that when we have multiple @synthesize in the same line,
5483 // that later ones do not override the previous ones.
5484 // If we have:
5485 // @synthesize Foo, Bar;
5486 // source ranges for both start at '@', so 'Bar' will end up overriding
5487 // 'Foo' even though the cursor location was at 'Foo'.
5488 if (Data->VisitedObjCPropertyImplDecl)
5489 return CXChildVisit_Break;
5490 Data->VisitedObjCPropertyImplDecl = true;
5491 }
5492 }
5493
5494 if (clang_isExpression(cursor.kind) &&
5495 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005496 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005497 // Avoid having the cursor of an expression replace the declaration cursor
5498 // when the expression source range overlaps the declaration range.
5499 // This can happen for C++ constructor expressions whose range generally
5500 // include the variable declaration, e.g.:
5501 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5502 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5503 D->getLocation() == Data->TokenBeginLoc)
5504 return CXChildVisit_Break;
5505 }
5506 }
5507
5508 // If our current best cursor is the construction of a temporary object,
5509 // don't replace that cursor with a type reference, because we want
5510 // clang_getCursor() to point at the constructor.
5511 if (clang_isExpression(BestCursor->kind) &&
5512 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5513 cursor.kind == CXCursor_TypeRef) {
5514 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5515 // as having the actual point on the type reference.
5516 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5517 return CXChildVisit_Recurse;
5518 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005519
5520 // If we already have an Objective-C superclass reference, don't
5521 // update it further.
5522 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5523 return CXChildVisit_Break;
5524
Guy Benyei11169dd2012-12-18 14:30:41 +00005525 *BestCursor = cursor;
5526 return CXChildVisit_Recurse;
5527}
5528
5529CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005530 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005531 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005532 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005533 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005534
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005535 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005536 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5537
5538 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5539 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5540
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005541 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005542 CXFile SearchFile;
5543 unsigned SearchLine, SearchColumn;
5544 CXFile ResultFile;
5545 unsigned ResultLine, ResultColumn;
5546 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5547 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5548 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005549
5550 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5551 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005552 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005553 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 SearchFileName = clang_getFileName(SearchFile);
5555 ResultFileName = clang_getFileName(ResultFile);
5556 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5557 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005558 *Log << llvm::format("(%s:%d:%d) = %s",
5559 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5560 clang_getCString(KindSpelling))
5561 << llvm::format("(%s:%d:%d):%s%s",
5562 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5563 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005564 clang_disposeString(SearchFileName);
5565 clang_disposeString(ResultFileName);
5566 clang_disposeString(KindSpelling);
5567 clang_disposeString(USR);
5568
5569 CXCursor Definition = clang_getCursorDefinition(Result);
5570 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5571 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5572 CXString DefinitionKindSpelling
5573 = clang_getCursorKindSpelling(Definition.kind);
5574 CXFile DefinitionFile;
5575 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005576 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005577 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005578 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005579 *Log << llvm::format(" -> %s(%s:%d:%d)",
5580 clang_getCString(DefinitionKindSpelling),
5581 clang_getCString(DefinitionFileName),
5582 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005583 clang_disposeString(DefinitionFileName);
5584 clang_disposeString(DefinitionKindSpelling);
5585 }
5586 }
5587
5588 return Result;
5589}
5590
5591CXCursor clang_getNullCursor(void) {
5592 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5593}
5594
5595unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005596 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5597 // can't set consistently. For example, when visiting a DeclStmt we will set
5598 // it but we don't set it on the result of clang_getCursorDefinition for
5599 // a reference of the same declaration.
5600 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5601 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5602 // to provide that kind of info.
5603 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005604 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005605 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005606 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005607
Guy Benyei11169dd2012-12-18 14:30:41 +00005608 return X == Y;
5609}
5610
5611unsigned clang_hashCursor(CXCursor C) {
5612 unsigned Index = 0;
5613 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5614 Index = 1;
5615
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005616 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005617 std::make_pair(C.kind, C.data[Index]));
5618}
5619
5620unsigned clang_isInvalid(enum CXCursorKind K) {
5621 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5622}
5623
5624unsigned clang_isDeclaration(enum CXCursorKind K) {
5625 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005626 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5627}
5628
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005629unsigned clang_isInvalidDeclaration(CXCursor C) {
5630 if (clang_isDeclaration(C.kind)) {
5631 if (const Decl *D = getCursorDecl(C))
5632 return D->isInvalidDecl();
5633 }
5634
5635 return 0;
5636}
5637
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005638unsigned clang_isReference(enum CXCursorKind K) {
5639 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5640}
Guy Benyei11169dd2012-12-18 14:30:41 +00005641
5642unsigned clang_isExpression(enum CXCursorKind K) {
5643 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5644}
5645
5646unsigned clang_isStatement(enum CXCursorKind K) {
5647 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5648}
5649
5650unsigned clang_isAttribute(enum CXCursorKind K) {
5651 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5652}
5653
5654unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5655 return K == CXCursor_TranslationUnit;
5656}
5657
5658unsigned clang_isPreprocessing(enum CXCursorKind K) {
5659 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5660}
5661
5662unsigned clang_isUnexposed(enum CXCursorKind K) {
5663 switch (K) {
5664 case CXCursor_UnexposedDecl:
5665 case CXCursor_UnexposedExpr:
5666 case CXCursor_UnexposedStmt:
5667 case CXCursor_UnexposedAttr:
5668 return true;
5669 default:
5670 return false;
5671 }
5672}
5673
5674CXCursorKind clang_getCursorKind(CXCursor C) {
5675 return C.kind;
5676}
5677
5678CXSourceLocation clang_getCursorLocation(CXCursor C) {
5679 if (clang_isReference(C.kind)) {
5680 switch (C.kind) {
5681 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005682 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005683 = getCursorObjCSuperClassRef(C);
5684 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5685 }
5686
5687 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005688 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005689 = getCursorObjCProtocolRef(C);
5690 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5691 }
5692
5693 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005694 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005695 = getCursorObjCClassRef(C);
5696 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5697 }
5698
5699 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005700 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005701 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5702 }
5703
5704 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005705 std::pair<const TemplateDecl *, SourceLocation> P =
5706 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005707 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5708 }
5709
5710 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005711 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5713 }
5714
5715 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005716 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005717 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5718 }
5719
5720 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005721 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005722 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5723 }
5724
5725 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005726 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005727 if (!BaseSpec)
5728 return clang_getNullLocation();
5729
5730 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5731 return cxloc::translateSourceLocation(getCursorContext(C),
5732 TSInfo->getTypeLoc().getBeginLoc());
5733
5734 return cxloc::translateSourceLocation(getCursorContext(C),
5735 BaseSpec->getLocStart());
5736 }
5737
5738 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005739 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005740 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5741 }
5742
5743 case CXCursor_OverloadedDeclRef:
5744 return cxloc::translateSourceLocation(getCursorContext(C),
5745 getCursorOverloadedDeclRef(C).second);
5746
5747 default:
5748 // FIXME: Need a way to enumerate all non-reference cases.
5749 llvm_unreachable("Missed a reference kind");
5750 }
5751 }
5752
5753 if (clang_isExpression(C.kind))
5754 return cxloc::translateSourceLocation(getCursorContext(C),
5755 getLocationFromExpr(getCursorExpr(C)));
5756
5757 if (clang_isStatement(C.kind))
5758 return cxloc::translateSourceLocation(getCursorContext(C),
5759 getCursorStmt(C)->getLocStart());
5760
5761 if (C.kind == CXCursor_PreprocessingDirective) {
5762 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5763 return cxloc::translateSourceLocation(getCursorContext(C), L);
5764 }
5765
5766 if (C.kind == CXCursor_MacroExpansion) {
5767 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005768 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005769 return cxloc::translateSourceLocation(getCursorContext(C), L);
5770 }
5771
5772 if (C.kind == CXCursor_MacroDefinition) {
5773 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5774 return cxloc::translateSourceLocation(getCursorContext(C), L);
5775 }
5776
5777 if (C.kind == CXCursor_InclusionDirective) {
5778 SourceLocation L
5779 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5780 return cxloc::translateSourceLocation(getCursorContext(C), L);
5781 }
5782
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005783 if (clang_isAttribute(C.kind)) {
5784 SourceLocation L
5785 = cxcursor::getCursorAttr(C)->getLocation();
5786 return cxloc::translateSourceLocation(getCursorContext(C), L);
5787 }
5788
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 if (!clang_isDeclaration(C.kind))
5790 return clang_getNullLocation();
5791
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005792 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005793 if (!D)
5794 return clang_getNullLocation();
5795
5796 SourceLocation Loc = D->getLocation();
5797 // FIXME: Multiple variables declared in a single declaration
5798 // currently lack the information needed to correctly determine their
5799 // ranges when accounting for the type-specifier. We use context
5800 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5801 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005802 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005803 if (!cxcursor::isFirstInDeclGroup(C))
5804 Loc = VD->getLocation();
5805 }
5806
5807 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005808 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005809 Loc = MD->getSelectorStartLoc();
5810
5811 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5812}
5813
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005814} // end extern "C"
5815
Guy Benyei11169dd2012-12-18 14:30:41 +00005816CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5817 assert(TU);
5818
5819 // Guard against an invalid SourceLocation, or we may assert in one
5820 // of the following calls.
5821 if (SLoc.isInvalid())
5822 return clang_getNullCursor();
5823
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005824 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005825
5826 // Translate the given source location to make it point at the beginning of
5827 // the token under the cursor.
5828 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5829 CXXUnit->getASTContext().getLangOpts());
5830
5831 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5832 if (SLoc.isValid()) {
5833 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5834 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5835 /*VisitPreprocessorLast=*/true,
5836 /*VisitIncludedEntities=*/false,
5837 SourceLocation(SLoc));
5838 CursorVis.visitFileRegion();
5839 }
5840
5841 return Result;
5842}
5843
5844static SourceRange getRawCursorExtent(CXCursor C) {
5845 if (clang_isReference(C.kind)) {
5846 switch (C.kind) {
5847 case CXCursor_ObjCSuperClassRef:
5848 return getCursorObjCSuperClassRef(C).second;
5849
5850 case CXCursor_ObjCProtocolRef:
5851 return getCursorObjCProtocolRef(C).second;
5852
5853 case CXCursor_ObjCClassRef:
5854 return getCursorObjCClassRef(C).second;
5855
5856 case CXCursor_TypeRef:
5857 return getCursorTypeRef(C).second;
5858
5859 case CXCursor_TemplateRef:
5860 return getCursorTemplateRef(C).second;
5861
5862 case CXCursor_NamespaceRef:
5863 return getCursorNamespaceRef(C).second;
5864
5865 case CXCursor_MemberRef:
5866 return getCursorMemberRef(C).second;
5867
5868 case CXCursor_CXXBaseSpecifier:
5869 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5870
5871 case CXCursor_LabelRef:
5872 return getCursorLabelRef(C).second;
5873
5874 case CXCursor_OverloadedDeclRef:
5875 return getCursorOverloadedDeclRef(C).second;
5876
5877 case CXCursor_VariableRef:
5878 return getCursorVariableRef(C).second;
5879
5880 default:
5881 // FIXME: Need a way to enumerate all non-reference cases.
5882 llvm_unreachable("Missed a reference kind");
5883 }
5884 }
5885
5886 if (clang_isExpression(C.kind))
5887 return getCursorExpr(C)->getSourceRange();
5888
5889 if (clang_isStatement(C.kind))
5890 return getCursorStmt(C)->getSourceRange();
5891
5892 if (clang_isAttribute(C.kind))
5893 return getCursorAttr(C)->getRange();
5894
5895 if (C.kind == CXCursor_PreprocessingDirective)
5896 return cxcursor::getCursorPreprocessingDirective(C);
5897
5898 if (C.kind == CXCursor_MacroExpansion) {
5899 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005900 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005901 return TU->mapRangeFromPreamble(Range);
5902 }
5903
5904 if (C.kind == CXCursor_MacroDefinition) {
5905 ASTUnit *TU = getCursorASTUnit(C);
5906 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5907 return TU->mapRangeFromPreamble(Range);
5908 }
5909
5910 if (C.kind == CXCursor_InclusionDirective) {
5911 ASTUnit *TU = getCursorASTUnit(C);
5912 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5913 return TU->mapRangeFromPreamble(Range);
5914 }
5915
5916 if (C.kind == CXCursor_TranslationUnit) {
5917 ASTUnit *TU = getCursorASTUnit(C);
5918 FileID MainID = TU->getSourceManager().getMainFileID();
5919 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5920 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5921 return SourceRange(Start, End);
5922 }
5923
5924 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005925 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005926 if (!D)
5927 return SourceRange();
5928
5929 SourceRange R = D->getSourceRange();
5930 // FIXME: Multiple variables declared in a single declaration
5931 // currently lack the information needed to correctly determine their
5932 // ranges when accounting for the type-specifier. We use context
5933 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5934 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005935 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005936 if (!cxcursor::isFirstInDeclGroup(C))
5937 R.setBegin(VD->getLocation());
5938 }
5939 return R;
5940 }
5941 return SourceRange();
5942}
5943
5944/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5945/// the decl-specifier-seq for declarations.
5946static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5947 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005948 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005949 if (!D)
5950 return SourceRange();
5951
5952 SourceRange R = D->getSourceRange();
5953
5954 // Adjust the start of the location for declarations preceded by
5955 // declaration specifiers.
5956 SourceLocation StartLoc;
5957 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5958 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5959 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005960 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005961 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5962 StartLoc = TI->getTypeLoc().getLocStart();
5963 }
5964
5965 if (StartLoc.isValid() && R.getBegin().isValid() &&
5966 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5967 R.setBegin(StartLoc);
5968
5969 // FIXME: Multiple variables declared in a single declaration
5970 // currently lack the information needed to correctly determine their
5971 // ranges when accounting for the type-specifier. We use context
5972 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5973 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005974 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005975 if (!cxcursor::isFirstInDeclGroup(C))
5976 R.setBegin(VD->getLocation());
5977 }
5978
5979 return R;
5980 }
5981
5982 return getRawCursorExtent(C);
5983}
5984
Guy Benyei11169dd2012-12-18 14:30:41 +00005985CXSourceRange clang_getCursorExtent(CXCursor C) {
5986 SourceRange R = getRawCursorExtent(C);
5987 if (R.isInvalid())
5988 return clang_getNullRange();
5989
5990 return cxloc::translateSourceRange(getCursorContext(C), R);
5991}
5992
5993CXCursor clang_getCursorReferenced(CXCursor C) {
5994 if (clang_isInvalid(C.kind))
5995 return clang_getNullCursor();
5996
5997 CXTranslationUnit tu = getCursorTU(C);
5998 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005999 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006000 if (!D)
6001 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006002 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006003 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006004 if (const ObjCPropertyImplDecl *PropImpl =
6005 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006006 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6007 return MakeCXCursor(Property, tu);
6008
6009 return C;
6010 }
6011
6012 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006013 const Expr *E = getCursorExpr(C);
6014 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006015 if (D) {
6016 CXCursor declCursor = MakeCXCursor(D, tu);
6017 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6018 declCursor);
6019 return declCursor;
6020 }
6021
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006022 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006023 return MakeCursorOverloadedDeclRef(Ovl, tu);
6024
6025 return clang_getNullCursor();
6026 }
6027
6028 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006029 const Stmt *S = getCursorStmt(C);
6030 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006031 if (LabelDecl *label = Goto->getLabel())
6032 if (LabelStmt *labelS = label->getStmt())
6033 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6034
6035 return clang_getNullCursor();
6036 }
Richard Smith66a81862015-05-04 02:25:31 +00006037
Guy Benyei11169dd2012-12-18 14:30:41 +00006038 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006039 if (const MacroDefinitionRecord *Def =
6040 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006041 return MakeMacroDefinitionCursor(Def, tu);
6042 }
6043
6044 if (!clang_isReference(C.kind))
6045 return clang_getNullCursor();
6046
6047 switch (C.kind) {
6048 case CXCursor_ObjCSuperClassRef:
6049 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6050
6051 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006052 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6053 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006054 return MakeCXCursor(Def, tu);
6055
6056 return MakeCXCursor(Prot, tu);
6057 }
6058
6059 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006060 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6061 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006062 return MakeCXCursor(Def, tu);
6063
6064 return MakeCXCursor(Class, tu);
6065 }
6066
6067 case CXCursor_TypeRef:
6068 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6069
6070 case CXCursor_TemplateRef:
6071 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6072
6073 case CXCursor_NamespaceRef:
6074 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6075
6076 case CXCursor_MemberRef:
6077 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6078
6079 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006080 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6082 tu ));
6083 }
6084
6085 case CXCursor_LabelRef:
6086 // FIXME: We end up faking the "parent" declaration here because we
6087 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006088 return MakeCXCursor(getCursorLabelRef(C).first,
6089 cxtu::getASTUnit(tu)->getASTContext()
6090 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 tu);
6092
6093 case CXCursor_OverloadedDeclRef:
6094 return C;
6095
6096 case CXCursor_VariableRef:
6097 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6098
6099 default:
6100 // We would prefer to enumerate all non-reference cursor kinds here.
6101 llvm_unreachable("Unhandled reference cursor kind");
6102 }
6103}
6104
6105CXCursor clang_getCursorDefinition(CXCursor C) {
6106 if (clang_isInvalid(C.kind))
6107 return clang_getNullCursor();
6108
6109 CXTranslationUnit TU = getCursorTU(C);
6110
6111 bool WasReference = false;
6112 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6113 C = clang_getCursorReferenced(C);
6114 WasReference = true;
6115 }
6116
6117 if (C.kind == CXCursor_MacroExpansion)
6118 return clang_getCursorReferenced(C);
6119
6120 if (!clang_isDeclaration(C.kind))
6121 return clang_getNullCursor();
6122
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006123 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006124 if (!D)
6125 return clang_getNullCursor();
6126
6127 switch (D->getKind()) {
6128 // Declaration kinds that don't really separate the notions of
6129 // declaration and definition.
6130 case Decl::Namespace:
6131 case Decl::Typedef:
6132 case Decl::TypeAlias:
6133 case Decl::TypeAliasTemplate:
6134 case Decl::TemplateTypeParm:
6135 case Decl::EnumConstant:
6136 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006137 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006138 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006139 case Decl::IndirectField:
6140 case Decl::ObjCIvar:
6141 case Decl::ObjCAtDefsField:
6142 case Decl::ImplicitParam:
6143 case Decl::ParmVar:
6144 case Decl::NonTypeTemplateParm:
6145 case Decl::TemplateTemplateParm:
6146 case Decl::ObjCCategoryImpl:
6147 case Decl::ObjCImplementation:
6148 case Decl::AccessSpec:
6149 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006150 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 case Decl::ObjCPropertyImpl:
6152 case Decl::FileScopeAsm:
6153 case Decl::StaticAssert:
6154 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006155 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006156 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 case Decl::Label: // FIXME: Is this right??
6158 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006159 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006160 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006161 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006162 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006163 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006164 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006165 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006166 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006167 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006168 return C;
6169
6170 // Declaration kinds that don't make any sense here, but are
6171 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006172 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006173 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006174 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 break;
6176
6177 // Declaration kinds for which the definition is not resolvable.
6178 case Decl::UnresolvedUsingTypename:
6179 case Decl::UnresolvedUsingValue:
6180 break;
6181
6182 case Decl::UsingDirective:
6183 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6184 TU);
6185
6186 case Decl::NamespaceAlias:
6187 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6188
6189 case Decl::Enum:
6190 case Decl::Record:
6191 case Decl::CXXRecord:
6192 case Decl::ClassTemplateSpecialization:
6193 case Decl::ClassTemplatePartialSpecialization:
6194 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6195 return MakeCXCursor(Def, TU);
6196 return clang_getNullCursor();
6197
6198 case Decl::Function:
6199 case Decl::CXXMethod:
6200 case Decl::CXXConstructor:
6201 case Decl::CXXDestructor:
6202 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006203 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006204 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006205 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006206 return clang_getNullCursor();
6207 }
6208
Larisse Voufo39a1e502013-08-06 01:03:05 +00006209 case Decl::Var:
6210 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006211 case Decl::VarTemplatePartialSpecialization:
6212 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006214 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006215 return MakeCXCursor(Def, TU);
6216 return clang_getNullCursor();
6217 }
6218
6219 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006220 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006221 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6222 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6223 return clang_getNullCursor();
6224 }
6225
6226 case Decl::ClassTemplate: {
6227 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6228 ->getDefinition())
6229 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6230 TU);
6231 return clang_getNullCursor();
6232 }
6233
Larisse Voufo39a1e502013-08-06 01:03:05 +00006234 case Decl::VarTemplate: {
6235 if (VarDecl *Def =
6236 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6237 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6238 return clang_getNullCursor();
6239 }
6240
Guy Benyei11169dd2012-12-18 14:30:41 +00006241 case Decl::Using:
6242 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6243 D->getLocation(), TU);
6244
6245 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006246 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006247 return clang_getCursorDefinition(
6248 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6249 TU));
6250
6251 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006252 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006253 if (Method->isThisDeclarationADefinition())
6254 return C;
6255
6256 // Dig out the method definition in the associated
6257 // @implementation, if we have it.
6258 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006259 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006260 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6261 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6262 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6263 Method->isInstanceMethod()))
6264 if (Def->isThisDeclarationADefinition())
6265 return MakeCXCursor(Def, TU);
6266
6267 return clang_getNullCursor();
6268 }
6269
6270 case Decl::ObjCCategory:
6271 if (ObjCCategoryImplDecl *Impl
6272 = cast<ObjCCategoryDecl>(D)->getImplementation())
6273 return MakeCXCursor(Impl, TU);
6274 return clang_getNullCursor();
6275
6276 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006277 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006278 return MakeCXCursor(Def, TU);
6279 return clang_getNullCursor();
6280
6281 case Decl::ObjCInterface: {
6282 // There are two notions of a "definition" for an Objective-C
6283 // class: the interface and its implementation. When we resolved a
6284 // reference to an Objective-C class, produce the @interface as
6285 // the definition; when we were provided with the interface,
6286 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006287 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006288 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006289 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 return MakeCXCursor(Def, TU);
6291 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6292 return MakeCXCursor(Impl, TU);
6293 return clang_getNullCursor();
6294 }
6295
6296 case Decl::ObjCProperty:
6297 // FIXME: We don't really know where to find the
6298 // ObjCPropertyImplDecls that implement this property.
6299 return clang_getNullCursor();
6300
6301 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006302 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006303 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006304 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006305 return MakeCXCursor(Def, TU);
6306
6307 return clang_getNullCursor();
6308
6309 case Decl::Friend:
6310 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6311 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6312 return clang_getNullCursor();
6313
6314 case Decl::FriendTemplate:
6315 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6316 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6317 return clang_getNullCursor();
6318 }
6319
6320 return clang_getNullCursor();
6321}
6322
6323unsigned clang_isCursorDefinition(CXCursor C) {
6324 if (!clang_isDeclaration(C.kind))
6325 return 0;
6326
6327 return clang_getCursorDefinition(C) == C;
6328}
6329
6330CXCursor clang_getCanonicalCursor(CXCursor C) {
6331 if (!clang_isDeclaration(C.kind))
6332 return C;
6333
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006334 if (const Decl *D = getCursorDecl(C)) {
6335 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006336 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6337 return MakeCXCursor(CatD, getCursorTU(C));
6338
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006339 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6340 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006341 return MakeCXCursor(IFD, getCursorTU(C));
6342
6343 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6344 }
6345
6346 return C;
6347}
6348
6349int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6350 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6351}
6352
6353unsigned clang_getNumOverloadedDecls(CXCursor C) {
6354 if (C.kind != CXCursor_OverloadedDeclRef)
6355 return 0;
6356
6357 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006358 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006359 return E->getNumDecls();
6360
6361 if (OverloadedTemplateStorage *S
6362 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6363 return S->size();
6364
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006365 const Decl *D = Storage.get<const Decl *>();
6366 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006367 return Using->shadow_size();
6368
6369 return 0;
6370}
6371
6372CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6373 if (cursor.kind != CXCursor_OverloadedDeclRef)
6374 return clang_getNullCursor();
6375
6376 if (index >= clang_getNumOverloadedDecls(cursor))
6377 return clang_getNullCursor();
6378
6379 CXTranslationUnit TU = getCursorTU(cursor);
6380 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006381 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006382 return MakeCXCursor(E->decls_begin()[index], TU);
6383
6384 if (OverloadedTemplateStorage *S
6385 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6386 return MakeCXCursor(S->begin()[index], TU);
6387
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006388 const Decl *D = Storage.get<const Decl *>();
6389 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 // FIXME: This is, unfortunately, linear time.
6391 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6392 std::advance(Pos, index);
6393 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6394 }
6395
6396 return clang_getNullCursor();
6397}
6398
6399void clang_getDefinitionSpellingAndExtent(CXCursor C,
6400 const char **startBuf,
6401 const char **endBuf,
6402 unsigned *startLine,
6403 unsigned *startColumn,
6404 unsigned *endLine,
6405 unsigned *endColumn) {
6406 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006407 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6409
6410 SourceManager &SM = FD->getASTContext().getSourceManager();
6411 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6412 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6413 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6414 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6415 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6416 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6417}
6418
6419
6420CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6421 unsigned PieceIndex) {
6422 RefNamePieces Pieces;
6423
6424 switch (C.kind) {
6425 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006426 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006427 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6428 E->getQualifierLoc().getSourceRange());
6429 break;
6430
6431 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006432 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6433 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6434 Pieces =
6435 buildPieces(NameFlags, false, E->getNameInfo(),
6436 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6437 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006438 break;
6439
6440 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006441 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006442 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006443 const Expr *Callee = OCE->getCallee();
6444 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006445 Callee = ICE->getSubExpr();
6446
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006447 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006448 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6449 DRE->getQualifierLoc().getSourceRange());
6450 }
6451 break;
6452
6453 default:
6454 break;
6455 }
6456
6457 if (Pieces.empty()) {
6458 if (PieceIndex == 0)
6459 return clang_getCursorExtent(C);
6460 } else if (PieceIndex < Pieces.size()) {
6461 SourceRange R = Pieces[PieceIndex];
6462 if (R.isValid())
6463 return cxloc::translateSourceRange(getCursorContext(C), R);
6464 }
6465
6466 return clang_getNullRange();
6467}
6468
6469void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006470 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6471 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006472}
6473
6474void clang_executeOnThread(void (*fn)(void*), void *user_data,
6475 unsigned stack_size) {
6476 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6477}
6478
Guy Benyei11169dd2012-12-18 14:30:41 +00006479//===----------------------------------------------------------------------===//
6480// Token-based Operations.
6481//===----------------------------------------------------------------------===//
6482
6483/* CXToken layout:
6484 * int_data[0]: a CXTokenKind
6485 * int_data[1]: starting token location
6486 * int_data[2]: token length
6487 * int_data[3]: reserved
6488 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6489 * otherwise unused.
6490 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006491CXTokenKind clang_getTokenKind(CXToken CXTok) {
6492 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6493}
6494
6495CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6496 switch (clang_getTokenKind(CXTok)) {
6497 case CXToken_Identifier:
6498 case CXToken_Keyword:
6499 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006500 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006501 ->getNameStart());
6502
6503 case CXToken_Literal: {
6504 // We have stashed the starting pointer in the ptr_data field. Use it.
6505 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006506 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006507 }
6508
6509 case CXToken_Punctuation:
6510 case CXToken_Comment:
6511 break;
6512 }
6513
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006514 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006515 LOG_BAD_TU(TU);
6516 return cxstring::createEmpty();
6517 }
6518
Guy Benyei11169dd2012-12-18 14:30:41 +00006519 // We have to find the starting buffer pointer the hard way, by
6520 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006521 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006523 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006524
6525 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6526 std::pair<FileID, unsigned> LocInfo
6527 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6528 bool Invalid = false;
6529 StringRef Buffer
6530 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6531 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006532 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006533
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006534 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006535}
6536
6537CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006538 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006539 LOG_BAD_TU(TU);
6540 return clang_getNullLocation();
6541 }
6542
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006543 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006544 if (!CXXUnit)
6545 return clang_getNullLocation();
6546
6547 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6548 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6549}
6550
6551CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006552 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006553 LOG_BAD_TU(TU);
6554 return clang_getNullRange();
6555 }
6556
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006557 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006558 if (!CXXUnit)
6559 return clang_getNullRange();
6560
6561 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6562 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6563}
6564
6565static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6566 SmallVectorImpl<CXToken> &CXTokens) {
6567 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6568 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006569 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006570 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006571 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006572
6573 // Cannot tokenize across files.
6574 if (BeginLocInfo.first != EndLocInfo.first)
6575 return;
6576
6577 // Create a lexer
6578 bool Invalid = false;
6579 StringRef Buffer
6580 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6581 if (Invalid)
6582 return;
6583
6584 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6585 CXXUnit->getASTContext().getLangOpts(),
6586 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6587 Lex.SetCommentRetentionState(true);
6588
6589 // Lex tokens until we hit the end of the range.
6590 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6591 Token Tok;
6592 bool previousWasAt = false;
6593 do {
6594 // Lex the next token
6595 Lex.LexFromRawLexer(Tok);
6596 if (Tok.is(tok::eof))
6597 break;
6598
6599 // Initialize the CXToken.
6600 CXToken CXTok;
6601
6602 // - Common fields
6603 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6604 CXTok.int_data[2] = Tok.getLength();
6605 CXTok.int_data[3] = 0;
6606
6607 // - Kind-specific fields
6608 if (Tok.isLiteral()) {
6609 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006610 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006611 } else if (Tok.is(tok::raw_identifier)) {
6612 // Lookup the identifier to determine whether we have a keyword.
6613 IdentifierInfo *II
6614 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6615
6616 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6617 CXTok.int_data[0] = CXToken_Keyword;
6618 }
6619 else {
6620 CXTok.int_data[0] = Tok.is(tok::identifier)
6621 ? CXToken_Identifier
6622 : CXToken_Keyword;
6623 }
6624 CXTok.ptr_data = II;
6625 } else if (Tok.is(tok::comment)) {
6626 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006627 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 } else {
6629 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006630 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006631 }
6632 CXTokens.push_back(CXTok);
6633 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006634 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006635}
6636
6637void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6638 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006639 LOG_FUNC_SECTION {
6640 *Log << TU << ' ' << Range;
6641 }
6642
Guy Benyei11169dd2012-12-18 14:30:41 +00006643 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006644 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006645 if (NumTokens)
6646 *NumTokens = 0;
6647
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006648 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006649 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006650 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006651 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006652
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006653 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006654 if (!CXXUnit || !Tokens || !NumTokens)
6655 return;
6656
6657 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6658
6659 SourceRange R = cxloc::translateCXSourceRange(Range);
6660 if (R.isInvalid())
6661 return;
6662
6663 SmallVector<CXToken, 32> CXTokens;
6664 getTokens(CXXUnit, R, CXTokens);
6665
6666 if (CXTokens.empty())
6667 return;
6668
Serge Pavlov52525732018-02-21 02:02:39 +00006669 *Tokens = static_cast<CXToken *>(
6670 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006671 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6672 *NumTokens = CXTokens.size();
6673}
6674
6675void clang_disposeTokens(CXTranslationUnit TU,
6676 CXToken *Tokens, unsigned NumTokens) {
6677 free(Tokens);
6678}
6679
Guy Benyei11169dd2012-12-18 14:30:41 +00006680//===----------------------------------------------------------------------===//
6681// Token annotation APIs.
6682//===----------------------------------------------------------------------===//
6683
Guy Benyei11169dd2012-12-18 14:30:41 +00006684static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6685 CXCursor parent,
6686 CXClientData client_data);
6687static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6688 CXClientData client_data);
6689
6690namespace {
6691class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006692 CXToken *Tokens;
6693 CXCursor *Cursors;
6694 unsigned NumTokens;
6695 unsigned TokIdx;
6696 unsigned PreprocessingTokIdx;
6697 CursorVisitor AnnotateVis;
6698 SourceManager &SrcMgr;
6699 bool HasContextSensitiveKeywords;
6700
6701 struct PostChildrenInfo {
6702 CXCursor Cursor;
6703 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006704 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 unsigned BeforeChildrenTokenIdx;
6706 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006707 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006708
6709 CXToken &getTok(unsigned Idx) {
6710 assert(Idx < NumTokens);
6711 return Tokens[Idx];
6712 }
6713 const CXToken &getTok(unsigned Idx) const {
6714 assert(Idx < NumTokens);
6715 return Tokens[Idx];
6716 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006717 bool MoreTokens() const { return TokIdx < NumTokens; }
6718 unsigned NextToken() const { return TokIdx; }
6719 void AdvanceToken() { ++TokIdx; }
6720 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006721 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006722 }
6723 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006724 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 }
6726 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006727 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006728 }
6729
6730 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006731 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006732 SourceRange);
6733
6734public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006735 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006736 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006737 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006738 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006739 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006740 AnnotateTokensVisitor, this,
6741 /*VisitPreprocessorLast=*/true,
6742 /*VisitIncludedEntities=*/false,
6743 RegionOfInterest,
6744 /*VisitDeclsOnly=*/false,
6745 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006746 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006747 HasContextSensitiveKeywords(false) { }
6748
6749 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6750 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6751 bool postVisitChildren(CXCursor cursor);
6752 void AnnotateTokens();
6753
6754 /// \brief Determine whether the annotator saw any cursors that have
6755 /// context-sensitive keywords.
6756 bool hasContextSensitiveKeywords() const {
6757 return HasContextSensitiveKeywords;
6758 }
6759
6760 ~AnnotateTokensWorker() {
6761 assert(PostChildrenInfos.empty());
6762 }
6763};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006764}
Guy Benyei11169dd2012-12-18 14:30:41 +00006765
6766void AnnotateTokensWorker::AnnotateTokens() {
6767 // Walk the AST within the region of interest, annotating tokens
6768 // along the way.
6769 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006770}
Guy Benyei11169dd2012-12-18 14:30:41 +00006771
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006772static inline void updateCursorAnnotation(CXCursor &Cursor,
6773 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006774 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006775 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006776 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006777}
6778
6779/// \brief It annotates and advances tokens with a cursor until the comparison
6780//// between the cursor location and the source range is the same as
6781/// \arg compResult.
6782///
6783/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6784/// Pass RangeOverlap to annotate tokens inside a range.
6785void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6786 RangeComparisonResult compResult,
6787 SourceRange range) {
6788 while (MoreTokens()) {
6789 const unsigned I = NextToken();
6790 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006791 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6792 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006793
6794 SourceLocation TokLoc = GetTokenLoc(I);
6795 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006796 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006797 AdvanceToken();
6798 continue;
6799 }
6800 break;
6801 }
6802}
6803
6804/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006805/// \returns true if it advanced beyond all macro tokens, false otherwise.
6806bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006807 CXCursor updateC,
6808 RangeComparisonResult compResult,
6809 SourceRange range) {
6810 assert(MoreTokens());
6811 assert(isFunctionMacroToken(NextToken()) &&
6812 "Should be called only for macro arg tokens");
6813
6814 // This works differently than annotateAndAdvanceTokens; because expanded
6815 // macro arguments can have arbitrary translation-unit source order, we do not
6816 // advance the token index one by one until a token fails the range test.
6817 // We only advance once past all of the macro arg tokens if all of them
6818 // pass the range test. If one of them fails we keep the token index pointing
6819 // at the start of the macro arg tokens so that the failing token will be
6820 // annotated by a subsequent annotation try.
6821
6822 bool atLeastOneCompFail = false;
6823
6824 unsigned I = NextToken();
6825 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6826 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6827 if (TokLoc.isFileID())
6828 continue; // not macro arg token, it's parens or comma.
6829 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6830 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6831 Cursors[I] = updateC;
6832 } else
6833 atLeastOneCompFail = true;
6834 }
6835
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006836 if (atLeastOneCompFail)
6837 return false;
6838
6839 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6840 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006841}
6842
6843enum CXChildVisitResult
6844AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006845 SourceRange cursorRange = getRawCursorExtent(cursor);
6846 if (cursorRange.isInvalid())
6847 return CXChildVisit_Recurse;
6848
6849 if (!HasContextSensitiveKeywords) {
6850 // Objective-C properties can have context-sensitive keywords.
6851 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006852 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6854 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6855 }
6856 // Objective-C methods can have context-sensitive keywords.
6857 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6858 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006859 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6861 if (Method->getObjCDeclQualifier())
6862 HasContextSensitiveKeywords = true;
6863 else {
David Majnemer59f77922016-06-24 04:05:48 +00006864 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006865 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006866 HasContextSensitiveKeywords = true;
6867 break;
6868 }
6869 }
6870 }
6871 }
6872 }
6873 // C++ methods can have context-sensitive keywords.
6874 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006875 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006876 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6877 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6878 HasContextSensitiveKeywords = true;
6879 }
6880 }
6881 // C++ classes can have context-sensitive keywords.
6882 else if (cursor.kind == CXCursor_StructDecl ||
6883 cursor.kind == CXCursor_ClassDecl ||
6884 cursor.kind == CXCursor_ClassTemplate ||
6885 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006886 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006887 if (D->hasAttr<FinalAttr>())
6888 HasContextSensitiveKeywords = true;
6889 }
6890 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006891
6892 // Don't override a property annotation with its getter/setter method.
6893 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6894 parent.kind == CXCursor_ObjCPropertyDecl)
6895 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006896
6897 if (clang_isPreprocessing(cursor.kind)) {
6898 // Items in the preprocessing record are kept separate from items in
6899 // declarations, so we keep a separate token index.
6900 unsigned SavedTokIdx = TokIdx;
6901 TokIdx = PreprocessingTokIdx;
6902
6903 // Skip tokens up until we catch up to the beginning of the preprocessing
6904 // entry.
6905 while (MoreTokens()) {
6906 const unsigned I = NextToken();
6907 SourceLocation TokLoc = GetTokenLoc(I);
6908 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6909 case RangeBefore:
6910 AdvanceToken();
6911 continue;
6912 case RangeAfter:
6913 case RangeOverlap:
6914 break;
6915 }
6916 break;
6917 }
6918
6919 // Look at all of the tokens within this range.
6920 while (MoreTokens()) {
6921 const unsigned I = NextToken();
6922 SourceLocation TokLoc = GetTokenLoc(I);
6923 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6924 case RangeBefore:
6925 llvm_unreachable("Infeasible");
6926 case RangeAfter:
6927 break;
6928 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006929 // For macro expansions, just note where the beginning of the macro
6930 // expansion occurs.
6931 if (cursor.kind == CXCursor_MacroExpansion) {
6932 if (TokLoc == cursorRange.getBegin())
6933 Cursors[I] = cursor;
6934 AdvanceToken();
6935 break;
6936 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006937 // We may have already annotated macro names inside macro definitions.
6938 if (Cursors[I].kind != CXCursor_MacroExpansion)
6939 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 continue;
6942 }
6943 break;
6944 }
6945
6946 // Save the preprocessing token index; restore the non-preprocessing
6947 // token index.
6948 PreprocessingTokIdx = TokIdx;
6949 TokIdx = SavedTokIdx;
6950 return CXChildVisit_Recurse;
6951 }
6952
6953 if (cursorRange.isInvalid())
6954 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006955
6956 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006957 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 const enum CXCursorKind K = clang_getCursorKind(parent);
6959 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006960 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6961 // Attributes are annotated out-of-order, skip tokens until we reach it.
6962 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 ? clang_getNullCursor() : parent;
6964
6965 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6966
6967 // Avoid having the cursor of an expression "overwrite" the annotation of the
6968 // variable declaration that it belongs to.
6969 // This can happen for C++ constructor expressions whose range generally
6970 // include the variable declaration, e.g.:
6971 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006972 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006973 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006974 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006975 const unsigned I = NextToken();
6976 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6977 E->getLocStart() == D->getLocation() &&
6978 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006979 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006980 AdvanceToken();
6981 }
6982 }
6983 }
6984
6985 // Before recursing into the children keep some state that we are going
6986 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6987 // extra work after the child nodes are visited.
6988 // Note that we don't call VisitChildren here to avoid traversing statements
6989 // code-recursively which can blow the stack.
6990
6991 PostChildrenInfo Info;
6992 Info.Cursor = cursor;
6993 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006994 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006995 Info.BeforeChildrenTokenIdx = NextToken();
6996 PostChildrenInfos.push_back(Info);
6997
6998 return CXChildVisit_Recurse;
6999}
7000
7001bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7002 if (PostChildrenInfos.empty())
7003 return false;
7004 const PostChildrenInfo &Info = PostChildrenInfos.back();
7005 if (!clang_equalCursors(Info.Cursor, cursor))
7006 return false;
7007
7008 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7009 const unsigned AfterChildren = NextToken();
7010 SourceRange cursorRange = Info.CursorRange;
7011
7012 // Scan the tokens that are at the end of the cursor, but are not captured
7013 // but the child cursors.
7014 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7015
7016 // Scan the tokens that are at the beginning of the cursor, but are not
7017 // capture by the child cursors.
7018 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7019 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7020 break;
7021
7022 Cursors[I] = cursor;
7023 }
7024
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007025 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7026 // encountered the attribute cursor.
7027 if (clang_isAttribute(cursor.kind))
7028 TokIdx = Info.BeforeReachingCursorIdx;
7029
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 PostChildrenInfos.pop_back();
7031 return false;
7032}
7033
7034static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7035 CXCursor parent,
7036 CXClientData client_data) {
7037 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7038}
7039
7040static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7041 CXClientData client_data) {
7042 return static_cast<AnnotateTokensWorker*>(client_data)->
7043 postVisitChildren(cursor);
7044}
7045
7046namespace {
7047
7048/// \brief Uses the macro expansions in the preprocessing record to find
7049/// and mark tokens that are macro arguments. This info is used by the
7050/// AnnotateTokensWorker.
7051class MarkMacroArgTokensVisitor {
7052 SourceManager &SM;
7053 CXToken *Tokens;
7054 unsigned NumTokens;
7055 unsigned CurIdx;
7056
7057public:
7058 MarkMacroArgTokensVisitor(SourceManager &SM,
7059 CXToken *tokens, unsigned numTokens)
7060 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7061
7062 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7063 if (cursor.kind != CXCursor_MacroExpansion)
7064 return CXChildVisit_Continue;
7065
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007066 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007067 if (macroRange.getBegin() == macroRange.getEnd())
7068 return CXChildVisit_Continue; // it's not a function macro.
7069
7070 for (; CurIdx < NumTokens; ++CurIdx) {
7071 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7072 macroRange.getBegin()))
7073 break;
7074 }
7075
7076 if (CurIdx == NumTokens)
7077 return CXChildVisit_Break;
7078
7079 for (; CurIdx < NumTokens; ++CurIdx) {
7080 SourceLocation tokLoc = getTokenLoc(CurIdx);
7081 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7082 break;
7083
7084 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7085 }
7086
7087 if (CurIdx == NumTokens)
7088 return CXChildVisit_Break;
7089
7090 return CXChildVisit_Continue;
7091 }
7092
7093private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007094 CXToken &getTok(unsigned Idx) {
7095 assert(Idx < NumTokens);
7096 return Tokens[Idx];
7097 }
7098 const CXToken &getTok(unsigned Idx) const {
7099 assert(Idx < NumTokens);
7100 return Tokens[Idx];
7101 }
7102
Guy Benyei11169dd2012-12-18 14:30:41 +00007103 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007104 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007105 }
7106
7107 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7108 // The third field is reserved and currently not used. Use it here
7109 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007110 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007111 }
7112};
7113
7114} // end anonymous namespace
7115
7116static CXChildVisitResult
7117MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7118 CXClientData client_data) {
7119 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7120 parent);
7121}
7122
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007123/// \brief Used by \c annotatePreprocessorTokens.
7124/// \returns true if lexing was finished, false otherwise.
7125static bool lexNext(Lexer &Lex, Token &Tok,
7126 unsigned &NextIdx, unsigned NumTokens) {
7127 if (NextIdx >= NumTokens)
7128 return true;
7129
7130 ++NextIdx;
7131 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007132 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007133}
7134
Guy Benyei11169dd2012-12-18 14:30:41 +00007135static void annotatePreprocessorTokens(CXTranslationUnit TU,
7136 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007137 CXCursor *Cursors,
7138 CXToken *Tokens,
7139 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007140 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007141
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007142 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007143 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7144 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007145 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007146 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007147 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007148
7149 if (BeginLocInfo.first != EndLocInfo.first)
7150 return;
7151
7152 StringRef Buffer;
7153 bool Invalid = false;
7154 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7155 if (Buffer.empty() || Invalid)
7156 return;
7157
7158 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7159 CXXUnit->getASTContext().getLangOpts(),
7160 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7161 Buffer.end());
7162 Lex.SetCommentRetentionState(true);
7163
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007164 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 // Lex tokens in raw mode until we hit the end of the range, to avoid
7166 // entering #includes or expanding macros.
7167 while (true) {
7168 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007169 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7170 break;
7171 unsigned TokIdx = NextIdx-1;
7172 assert(Tok.getLocation() ==
7173 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007174
7175 reprocess:
7176 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007177 // We have found a preprocessing directive. Annotate the tokens
7178 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007179 //
7180 // FIXME: Some simple tests here could identify macro definitions and
7181 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007182
7183 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007184 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7185 break;
7186
Craig Topper69186e72014-06-08 08:38:04 +00007187 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007188 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007189 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7190 break;
7191
7192 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007193 IdentifierInfo &II =
7194 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007195 SourceLocation MappedTokLoc =
7196 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7197 MI = getMacroInfo(II, MappedTokLoc, TU);
7198 }
7199 }
7200
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007201 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007202 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007203 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7204 finished = true;
7205 break;
7206 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007207 // If we are in a macro definition, check if the token was ever a
7208 // macro name and annotate it if that's the case.
7209 if (MI) {
7210 SourceLocation SaveLoc = Tok.getLocation();
7211 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007212 MacroDefinitionRecord *MacroDef =
7213 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007214 Tok.setLocation(SaveLoc);
7215 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007216 Cursors[NextIdx - 1] =
7217 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007218 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007219 } while (!Tok.isAtStartOfLine());
7220
7221 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7222 assert(TokIdx <= LastIdx);
7223 SourceLocation EndLoc =
7224 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7225 CXCursor Cursor =
7226 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7227
7228 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007229 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007230
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007231 if (finished)
7232 break;
7233 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007234 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007235 }
7236}
7237
7238// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007239static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7240 CXToken *Tokens, unsigned NumTokens,
7241 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007242 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007243 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7244 setThreadBackgroundPriority();
7245
7246 // Determine the region of interest, which contains all of the tokens.
7247 SourceRange RegionOfInterest;
7248 RegionOfInterest.setBegin(
7249 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7250 RegionOfInterest.setEnd(
7251 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7252 Tokens[NumTokens-1])));
7253
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 // Relex the tokens within the source range to look for preprocessing
7255 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007256 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007257
7258 // If begin location points inside a macro argument, set it to the expansion
7259 // location so we can have the full context when annotating semantically.
7260 {
7261 SourceManager &SM = CXXUnit->getSourceManager();
7262 SourceLocation Loc =
7263 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7264 if (Loc.isMacroID())
7265 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7266 }
7267
Guy Benyei11169dd2012-12-18 14:30:41 +00007268 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7269 // Search and mark tokens that are macro argument expansions.
7270 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7271 Tokens, NumTokens);
7272 CursorVisitor MacroArgMarker(TU,
7273 MarkMacroArgTokensVisitorDelegate, &Visitor,
7274 /*VisitPreprocessorLast=*/true,
7275 /*VisitIncludedEntities=*/false,
7276 RegionOfInterest);
7277 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7278 }
7279
7280 // Annotate all of the source locations in the region of interest that map to
7281 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007282 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007283
7284 // FIXME: We use a ridiculous stack size here because the data-recursion
7285 // algorithm uses a large stack frame than the non-data recursive version,
7286 // and AnnotationTokensWorker currently transforms the data-recursion
7287 // algorithm back into a traditional recursion by explicitly calling
7288 // VisitChildren(). We will need to remove this explicit recursive call.
7289 W.AnnotateTokens();
7290
7291 // If we ran into any entities that involve context-sensitive keywords,
7292 // take another pass through the tokens to mark them as such.
7293 if (W.hasContextSensitiveKeywords()) {
7294 for (unsigned I = 0; I != NumTokens; ++I) {
7295 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7296 continue;
7297
7298 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7299 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007300 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007301 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7302 if (Property->getPropertyAttributesAsWritten() != 0 &&
7303 llvm::StringSwitch<bool>(II->getName())
7304 .Case("readonly", true)
7305 .Case("assign", true)
7306 .Case("unsafe_unretained", true)
7307 .Case("readwrite", true)
7308 .Case("retain", true)
7309 .Case("copy", true)
7310 .Case("nonatomic", true)
7311 .Case("atomic", true)
7312 .Case("getter", true)
7313 .Case("setter", true)
7314 .Case("strong", true)
7315 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007316 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007317 .Default(false))
7318 Tokens[I].int_data[0] = CXToken_Keyword;
7319 }
7320 continue;
7321 }
7322
7323 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7324 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7325 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7326 if (llvm::StringSwitch<bool>(II->getName())
7327 .Case("in", true)
7328 .Case("out", true)
7329 .Case("inout", true)
7330 .Case("oneway", true)
7331 .Case("bycopy", true)
7332 .Case("byref", true)
7333 .Default(false))
7334 Tokens[I].int_data[0] = CXToken_Keyword;
7335 continue;
7336 }
7337
7338 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7339 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7340 Tokens[I].int_data[0] = CXToken_Keyword;
7341 continue;
7342 }
7343 }
7344 }
7345}
7346
Guy Benyei11169dd2012-12-18 14:30:41 +00007347void clang_annotateTokens(CXTranslationUnit TU,
7348 CXToken *Tokens, unsigned NumTokens,
7349 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007350 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007351 LOG_BAD_TU(TU);
7352 return;
7353 }
7354 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007355 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007356 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007357 }
7358
7359 LOG_FUNC_SECTION {
7360 *Log << TU << ' ';
7361 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7362 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7363 *Log << clang_getRange(bloc, eloc);
7364 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007365
7366 // Any token we don't specifically annotate will have a NULL cursor.
7367 CXCursor C = clang_getNullCursor();
7368 for (unsigned I = 0; I != NumTokens; ++I)
7369 Cursors[I] = C;
7370
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007371 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007372 if (!CXXUnit)
7373 return;
7374
7375 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007376
7377 auto AnnotateTokensImpl = [=]() {
7378 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7379 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007380 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007381 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007382 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7383 }
7384}
7385
Guy Benyei11169dd2012-12-18 14:30:41 +00007386//===----------------------------------------------------------------------===//
7387// Operations for querying linkage of a cursor.
7388//===----------------------------------------------------------------------===//
7389
Guy Benyei11169dd2012-12-18 14:30:41 +00007390CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7391 if (!clang_isDeclaration(cursor.kind))
7392 return CXLinkage_Invalid;
7393
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007394 const Decl *D = cxcursor::getCursorDecl(cursor);
7395 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007396 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007397 case NoLinkage:
7398 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007399 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007400 case InternalLinkage: return CXLinkage_Internal;
7401 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007402 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007403 case ExternalLinkage: return CXLinkage_External;
7404 };
7405
7406 return CXLinkage_Invalid;
7407}
Guy Benyei11169dd2012-12-18 14:30:41 +00007408
7409//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007410// Operations for querying visibility of a cursor.
7411//===----------------------------------------------------------------------===//
7412
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007413CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7414 if (!clang_isDeclaration(cursor.kind))
7415 return CXVisibility_Invalid;
7416
7417 const Decl *D = cxcursor::getCursorDecl(cursor);
7418 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7419 switch (ND->getVisibility()) {
7420 case HiddenVisibility: return CXVisibility_Hidden;
7421 case ProtectedVisibility: return CXVisibility_Protected;
7422 case DefaultVisibility: return CXVisibility_Default;
7423 };
7424
7425 return CXVisibility_Invalid;
7426}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007427
7428//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007429// Operations for querying language of a cursor.
7430//===----------------------------------------------------------------------===//
7431
7432static CXLanguageKind getDeclLanguage(const Decl *D) {
7433 if (!D)
7434 return CXLanguage_C;
7435
7436 switch (D->getKind()) {
7437 default:
7438 break;
7439 case Decl::ImplicitParam:
7440 case Decl::ObjCAtDefsField:
7441 case Decl::ObjCCategory:
7442 case Decl::ObjCCategoryImpl:
7443 case Decl::ObjCCompatibleAlias:
7444 case Decl::ObjCImplementation:
7445 case Decl::ObjCInterface:
7446 case Decl::ObjCIvar:
7447 case Decl::ObjCMethod:
7448 case Decl::ObjCProperty:
7449 case Decl::ObjCPropertyImpl:
7450 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007451 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007452 return CXLanguage_ObjC;
7453 case Decl::CXXConstructor:
7454 case Decl::CXXConversion:
7455 case Decl::CXXDestructor:
7456 case Decl::CXXMethod:
7457 case Decl::CXXRecord:
7458 case Decl::ClassTemplate:
7459 case Decl::ClassTemplatePartialSpecialization:
7460 case Decl::ClassTemplateSpecialization:
7461 case Decl::Friend:
7462 case Decl::FriendTemplate:
7463 case Decl::FunctionTemplate:
7464 case Decl::LinkageSpec:
7465 case Decl::Namespace:
7466 case Decl::NamespaceAlias:
7467 case Decl::NonTypeTemplateParm:
7468 case Decl::StaticAssert:
7469 case Decl::TemplateTemplateParm:
7470 case Decl::TemplateTypeParm:
7471 case Decl::UnresolvedUsingTypename:
7472 case Decl::UnresolvedUsingValue:
7473 case Decl::Using:
7474 case Decl::UsingDirective:
7475 case Decl::UsingShadow:
7476 return CXLanguage_CPlusPlus;
7477 }
7478
7479 return CXLanguage_C;
7480}
7481
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007482static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7483 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007484 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007485
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007486 switch (D->getAvailability()) {
7487 case AR_Available:
7488 case AR_NotYetIntroduced:
7489 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007490 return getCursorAvailabilityForDecl(
7491 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007492 return CXAvailability_Available;
7493
7494 case AR_Deprecated:
7495 return CXAvailability_Deprecated;
7496
7497 case AR_Unavailable:
7498 return CXAvailability_NotAvailable;
7499 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007500
7501 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007502}
7503
Guy Benyei11169dd2012-12-18 14:30:41 +00007504enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7505 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007506 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7507 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007508
7509 return CXAvailability_Available;
7510}
7511
7512static CXVersion convertVersion(VersionTuple In) {
7513 CXVersion Out = { -1, -1, -1 };
7514 if (In.empty())
7515 return Out;
7516
7517 Out.Major = In.getMajor();
7518
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007519 Optional<unsigned> Minor = In.getMinor();
7520 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007521 Out.Minor = *Minor;
7522 else
7523 return Out;
7524
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007525 Optional<unsigned> Subminor = In.getSubminor();
7526 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007527 Out.Subminor = *Subminor;
7528
7529 return Out;
7530}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007531
Alex Lorenz1345ea22017-06-12 19:06:30 +00007532static void getCursorPlatformAvailabilityForDecl(
7533 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7534 int *always_unavailable, CXString *unavailable_message,
7535 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007536 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007537 for (auto A : D->attrs()) {
7538 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007539 HadAvailAttr = true;
7540 if (always_deprecated)
7541 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007542 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007543 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007544 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007545 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007546 continue;
7547 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007548
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007549 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007550 HadAvailAttr = true;
7551 if (always_unavailable)
7552 *always_unavailable = 1;
7553 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007554 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007555 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7556 }
7557 continue;
7558 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007559
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007560 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007561 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007562 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007563 }
7564 }
7565
7566 if (!HadAvailAttr)
7567 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7568 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007569 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7570 deprecated_message, always_unavailable, unavailable_message,
7571 AvailabilityAttrs);
7572
7573 if (AvailabilityAttrs.empty())
7574 return;
7575
7576 std::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7577 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
Reid Klecknere6cde142017-08-04 21:52:25 +00007578 return LHS->getPlatform()->getName() <
7579 RHS->getPlatform()->getName();
Alex Lorenz1345ea22017-06-12 19:06:30 +00007580 });
7581 ASTContext &Ctx = D->getASTContext();
7582 auto It = std::unique(
7583 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7584 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7585 if (LHS->getPlatform() != RHS->getPlatform())
7586 return false;
7587
7588 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7589 LHS->getDeprecated() == RHS->getDeprecated() &&
7590 LHS->getObsoleted() == RHS->getObsoleted() &&
7591 LHS->getMessage() == RHS->getMessage() &&
7592 LHS->getReplacement() == RHS->getReplacement())
7593 return true;
7594
7595 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7596 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7597 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7598 return false;
7599
7600 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7601 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7602
7603 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7604 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7605 if (LHS->getMessage().empty())
7606 LHS->setMessage(Ctx, RHS->getMessage());
7607 if (LHS->getReplacement().empty())
7608 LHS->setReplacement(Ctx, RHS->getReplacement());
7609 }
7610
7611 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7612 LHS->setObsoleted(Ctx, RHS->getObsoleted());
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 return true;
7620 });
7621 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007622}
7623
Alex Lorenz1345ea22017-06-12 19:06:30 +00007624int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007625 CXString *deprecated_message,
7626 int *always_unavailable,
7627 CXString *unavailable_message,
7628 CXPlatformAvailability *availability,
7629 int availability_size) {
7630 if (always_deprecated)
7631 *always_deprecated = 0;
7632 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007633 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007634 if (always_unavailable)
7635 *always_unavailable = 0;
7636 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007637 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007638
Guy Benyei11169dd2012-12-18 14:30:41 +00007639 if (!clang_isDeclaration(cursor.kind))
7640 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007641
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007642 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 if (!D)
7644 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007645
Alex Lorenz1345ea22017-06-12 19:06:30 +00007646 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7647 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7648 always_unavailable, unavailable_message,
7649 AvailabilityAttrs);
7650 for (const auto &Avail :
7651 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7652 .take_front(availability_size))) {
7653 availability[Avail.index()].Platform =
7654 cxstring::createDup(Avail.value()->getPlatform()->getName());
7655 availability[Avail.index()].Introduced =
7656 convertVersion(Avail.value()->getIntroduced());
7657 availability[Avail.index()].Deprecated =
7658 convertVersion(Avail.value()->getDeprecated());
7659 availability[Avail.index()].Obsoleted =
7660 convertVersion(Avail.value()->getObsoleted());
7661 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7662 availability[Avail.index()].Message =
7663 cxstring::createDup(Avail.value()->getMessage());
7664 }
7665
7666 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007667}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007668
Guy Benyei11169dd2012-12-18 14:30:41 +00007669void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7670 clang_disposeString(availability->Platform);
7671 clang_disposeString(availability->Message);
7672}
7673
7674CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7675 if (clang_isDeclaration(cursor.kind))
7676 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7677
7678 return CXLanguage_Invalid;
7679}
7680
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007681CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7682 const Decl *D = cxcursor::getCursorDecl(cursor);
7683 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7684 switch (VD->getTLSKind()) {
7685 case VarDecl::TLS_None:
7686 return CXTLS_None;
7687 case VarDecl::TLS_Dynamic:
7688 return CXTLS_Dynamic;
7689 case VarDecl::TLS_Static:
7690 return CXTLS_Static;
7691 }
7692 }
7693
7694 return CXTLS_None;
7695}
7696
Guy Benyei11169dd2012-12-18 14:30:41 +00007697 /// \brief If the given cursor is the "templated" declaration
7698 /// descibing a class or function template, return the class or
7699 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007700static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007701 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007702 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007703
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007704 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007705 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7706 return FunTmpl;
7707
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007708 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007709 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7710 return ClassTmpl;
7711
7712 return D;
7713}
7714
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007715
7716enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7717 StorageClass sc = SC_None;
7718 const Decl *D = getCursorDecl(C);
7719 if (D) {
7720 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7721 sc = FD->getStorageClass();
7722 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7723 sc = VD->getStorageClass();
7724 } else {
7725 return CX_SC_Invalid;
7726 }
7727 } else {
7728 return CX_SC_Invalid;
7729 }
7730 switch (sc) {
7731 case SC_None:
7732 return CX_SC_None;
7733 case SC_Extern:
7734 return CX_SC_Extern;
7735 case SC_Static:
7736 return CX_SC_Static;
7737 case SC_PrivateExtern:
7738 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007739 case SC_Auto:
7740 return CX_SC_Auto;
7741 case SC_Register:
7742 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007743 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007744 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007745}
7746
Guy Benyei11169dd2012-12-18 14:30:41 +00007747CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7748 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007749 if (const Decl *D = getCursorDecl(cursor)) {
7750 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007751 if (!DC)
7752 return clang_getNullCursor();
7753
7754 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7755 getCursorTU(cursor));
7756 }
7757 }
7758
7759 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007760 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007761 return MakeCXCursor(D, getCursorTU(cursor));
7762 }
7763
7764 return clang_getNullCursor();
7765}
7766
7767CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7768 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007769 if (const Decl *D = getCursorDecl(cursor)) {
7770 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007771 if (!DC)
7772 return clang_getNullCursor();
7773
7774 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7775 getCursorTU(cursor));
7776 }
7777 }
7778
7779 // FIXME: Note that we can't easily compute the lexical context of a
7780 // statement or expression, so we return nothing.
7781 return clang_getNullCursor();
7782}
7783
7784CXFile clang_getIncludedFile(CXCursor cursor) {
7785 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007786 return nullptr;
7787
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007788 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007789 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007790}
7791
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007792unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7793 if (C.kind != CXCursor_ObjCPropertyDecl)
7794 return CXObjCPropertyAttr_noattr;
7795
7796 unsigned Result = CXObjCPropertyAttr_noattr;
7797 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7798 ObjCPropertyDecl::PropertyAttributeKind Attr =
7799 PD->getPropertyAttributesAsWritten();
7800
7801#define SET_CXOBJCPROP_ATTR(A) \
7802 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7803 Result |= CXObjCPropertyAttr_##A
7804 SET_CXOBJCPROP_ATTR(readonly);
7805 SET_CXOBJCPROP_ATTR(getter);
7806 SET_CXOBJCPROP_ATTR(assign);
7807 SET_CXOBJCPROP_ATTR(readwrite);
7808 SET_CXOBJCPROP_ATTR(retain);
7809 SET_CXOBJCPROP_ATTR(copy);
7810 SET_CXOBJCPROP_ATTR(nonatomic);
7811 SET_CXOBJCPROP_ATTR(setter);
7812 SET_CXOBJCPROP_ATTR(atomic);
7813 SET_CXOBJCPROP_ATTR(weak);
7814 SET_CXOBJCPROP_ATTR(strong);
7815 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007816 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007817#undef SET_CXOBJCPROP_ATTR
7818
7819 return Result;
7820}
7821
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007822unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7823 if (!clang_isDeclaration(C.kind))
7824 return CXObjCDeclQualifier_None;
7825
7826 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7827 const Decl *D = getCursorDecl(C);
7828 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7829 QT = MD->getObjCDeclQualifier();
7830 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7831 QT = PD->getObjCDeclQualifier();
7832 if (QT == Decl::OBJC_TQ_None)
7833 return CXObjCDeclQualifier_None;
7834
7835 unsigned Result = CXObjCDeclQualifier_None;
7836 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7837 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7838 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7839 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7840 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7841 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7842
7843 return Result;
7844}
7845
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007846unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7847 if (!clang_isDeclaration(C.kind))
7848 return 0;
7849
7850 const Decl *D = getCursorDecl(C);
7851 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7852 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7853 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7854 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7855
7856 return 0;
7857}
7858
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007859unsigned clang_Cursor_isVariadic(CXCursor C) {
7860 if (!clang_isDeclaration(C.kind))
7861 return 0;
7862
7863 const Decl *D = getCursorDecl(C);
7864 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7865 return FD->isVariadic();
7866 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7867 return MD->isVariadic();
7868
7869 return 0;
7870}
7871
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007872unsigned clang_Cursor_isExternalSymbol(CXCursor C,
7873 CXString *language, CXString *definedIn,
7874 unsigned *isGenerated) {
7875 if (!clang_isDeclaration(C.kind))
7876 return 0;
7877
7878 const Decl *D = getCursorDecl(C);
7879
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00007880 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007881 if (language)
7882 *language = cxstring::createDup(attr->getLanguage());
7883 if (definedIn)
7884 *definedIn = cxstring::createDup(attr->getDefinedIn());
7885 if (isGenerated)
7886 *isGenerated = attr->getGeneratedDeclaration();
7887 return 1;
7888 }
7889 return 0;
7890}
7891
Guy Benyei11169dd2012-12-18 14:30:41 +00007892CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7893 if (!clang_isDeclaration(C.kind))
7894 return clang_getNullRange();
7895
7896 const Decl *D = getCursorDecl(C);
7897 ASTContext &Context = getCursorContext(C);
7898 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7899 if (!RC)
7900 return clang_getNullRange();
7901
7902 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7903}
7904
7905CXString clang_Cursor_getRawCommentText(CXCursor C) {
7906 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007907 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007908
7909 const Decl *D = getCursorDecl(C);
7910 ASTContext &Context = getCursorContext(C);
7911 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7912 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7913 StringRef();
7914
7915 // Don't duplicate the string because RawText points directly into source
7916 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007917 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007918}
7919
7920CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7921 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007922 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007923
7924 const Decl *D = getCursorDecl(C);
7925 const ASTContext &Context = getCursorContext(C);
7926 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7927
7928 if (RC) {
7929 StringRef BriefText = RC->getBriefText(Context);
7930
7931 // Don't duplicate the string because RawComment ensures that this memory
7932 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007933 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007934 }
7935
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007936 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007937}
7938
Guy Benyei11169dd2012-12-18 14:30:41 +00007939CXModule clang_Cursor_getModule(CXCursor C) {
7940 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007941 if (const ImportDecl *ImportD =
7942 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007943 return ImportD->getImportedModule();
7944 }
7945
Craig Topper69186e72014-06-08 08:38:04 +00007946 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007947}
7948
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007949CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7950 if (isNotUsableTU(TU)) {
7951 LOG_BAD_TU(TU);
7952 return nullptr;
7953 }
7954 if (!File)
7955 return nullptr;
7956 FileEntry *FE = static_cast<FileEntry *>(File);
7957
7958 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7959 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7960 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7961
Richard Smithfeb54b62014-10-23 02:01:19 +00007962 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007963}
7964
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007965CXFile clang_Module_getASTFile(CXModule CXMod) {
7966 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007967 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007968 Module *Mod = static_cast<Module*>(CXMod);
7969 return const_cast<FileEntry *>(Mod->getASTFile());
7970}
7971
Guy Benyei11169dd2012-12-18 14:30:41 +00007972CXModule clang_Module_getParent(CXModule CXMod) {
7973 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007974 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007975 Module *Mod = static_cast<Module*>(CXMod);
7976 return Mod->Parent;
7977}
7978
7979CXString clang_Module_getName(CXModule CXMod) {
7980 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007981 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007982 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007983 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007984}
7985
7986CXString clang_Module_getFullName(CXModule CXMod) {
7987 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007988 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007989 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007990 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007991}
7992
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007993int clang_Module_isSystem(CXModule CXMod) {
7994 if (!CXMod)
7995 return 0;
7996 Module *Mod = static_cast<Module*>(CXMod);
7997 return Mod->IsSystem;
7998}
7999
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008000unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8001 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008002 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008003 LOG_BAD_TU(TU);
8004 return 0;
8005 }
8006 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 return 0;
8008 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008009 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8010 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8011 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008012}
8013
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008014CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8015 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008016 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008017 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008018 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008019 }
8020 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008021 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008022 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008023 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008024
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008025 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8026 if (Index < TopHeaders.size())
8027 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008028
Craig Topper69186e72014-06-08 08:38:04 +00008029 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008030}
8031
Guy Benyei11169dd2012-12-18 14:30:41 +00008032//===----------------------------------------------------------------------===//
8033// C++ AST instrospection.
8034//===----------------------------------------------------------------------===//
8035
Jonathan Coe29565352016-04-27 12:48:25 +00008036unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8037 if (!clang_isDeclaration(C.kind))
8038 return 0;
8039
8040 const Decl *D = cxcursor::getCursorDecl(C);
8041 const CXXConstructorDecl *Constructor =
8042 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8043 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8044}
8045
8046unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8047 if (!clang_isDeclaration(C.kind))
8048 return 0;
8049
8050 const Decl *D = cxcursor::getCursorDecl(C);
8051 const CXXConstructorDecl *Constructor =
8052 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8053 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8054}
8055
8056unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8057 if (!clang_isDeclaration(C.kind))
8058 return 0;
8059
8060 const Decl *D = cxcursor::getCursorDecl(C);
8061 const CXXConstructorDecl *Constructor =
8062 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8063 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8064}
8065
8066unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8067 if (!clang_isDeclaration(C.kind))
8068 return 0;
8069
8070 const Decl *D = cxcursor::getCursorDecl(C);
8071 const CXXConstructorDecl *Constructor =
8072 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8073 // Passing 'false' excludes constructors marked 'explicit'.
8074 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8075}
8076
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008077unsigned clang_CXXField_isMutable(CXCursor C) {
8078 if (!clang_isDeclaration(C.kind))
8079 return 0;
8080
8081 if (const auto D = cxcursor::getCursorDecl(C))
8082 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8083 return FD->isMutable() ? 1 : 0;
8084 return 0;
8085}
8086
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008087unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8088 if (!clang_isDeclaration(C.kind))
8089 return 0;
8090
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008091 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008092 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008093 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008094 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8095}
8096
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008097unsigned clang_CXXMethod_isConst(CXCursor C) {
8098 if (!clang_isDeclaration(C.kind))
8099 return 0;
8100
8101 const Decl *D = cxcursor::getCursorDecl(C);
8102 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008103 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008104 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
8105}
8106
Jonathan Coe29565352016-04-27 12:48:25 +00008107unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8108 if (!clang_isDeclaration(C.kind))
8109 return 0;
8110
8111 const Decl *D = cxcursor::getCursorDecl(C);
8112 const CXXMethodDecl *Method =
8113 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8114 return (Method && Method->isDefaulted()) ? 1 : 0;
8115}
8116
Guy Benyei11169dd2012-12-18 14:30:41 +00008117unsigned clang_CXXMethod_isStatic(CXCursor C) {
8118 if (!clang_isDeclaration(C.kind))
8119 return 0;
8120
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008121 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008122 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008123 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008124 return (Method && Method->isStatic()) ? 1 : 0;
8125}
8126
8127unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8128 if (!clang_isDeclaration(C.kind))
8129 return 0;
8130
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008131 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008132 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008133 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 return (Method && Method->isVirtual()) ? 1 : 0;
8135}
Guy Benyei11169dd2012-12-18 14:30:41 +00008136
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008137unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8138 if (!clang_isDeclaration(C.kind))
8139 return 0;
8140
8141 const auto *D = cxcursor::getCursorDecl(C);
8142 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8143 if (RD)
8144 RD = RD->getDefinition();
8145 return (RD && RD->isAbstract()) ? 1 : 0;
8146}
8147
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008148unsigned clang_EnumDecl_isScoped(CXCursor C) {
8149 if (!clang_isDeclaration(C.kind))
8150 return 0;
8151
8152 const Decl *D = cxcursor::getCursorDecl(C);
8153 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8154 return (Enum && Enum->isScoped()) ? 1 : 0;
8155}
8156
Guy Benyei11169dd2012-12-18 14:30:41 +00008157//===----------------------------------------------------------------------===//
8158// Attribute introspection.
8159//===----------------------------------------------------------------------===//
8160
Guy Benyei11169dd2012-12-18 14:30:41 +00008161CXType clang_getIBOutletCollectionType(CXCursor C) {
8162 if (C.kind != CXCursor_IBOutletCollectionAttr)
8163 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8164
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008165 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8167
8168 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8169}
Guy Benyei11169dd2012-12-18 14:30:41 +00008170
8171//===----------------------------------------------------------------------===//
8172// Inspecting memory usage.
8173//===----------------------------------------------------------------------===//
8174
8175typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8176
8177static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8178 enum CXTUResourceUsageKind k,
8179 unsigned long amount) {
8180 CXTUResourceUsageEntry entry = { k, amount };
8181 entries.push_back(entry);
8182}
8183
Guy Benyei11169dd2012-12-18 14:30:41 +00008184const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8185 const char *str = "";
8186 switch (kind) {
8187 case CXTUResourceUsage_AST:
8188 str = "ASTContext: expressions, declarations, and types";
8189 break;
8190 case CXTUResourceUsage_Identifiers:
8191 str = "ASTContext: identifiers";
8192 break;
8193 case CXTUResourceUsage_Selectors:
8194 str = "ASTContext: selectors";
8195 break;
8196 case CXTUResourceUsage_GlobalCompletionResults:
8197 str = "Code completion: cached global results";
8198 break;
8199 case CXTUResourceUsage_SourceManagerContentCache:
8200 str = "SourceManager: content cache allocator";
8201 break;
8202 case CXTUResourceUsage_AST_SideTables:
8203 str = "ASTContext: side tables";
8204 break;
8205 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8206 str = "SourceManager: malloc'ed memory buffers";
8207 break;
8208 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8209 str = "SourceManager: mmap'ed memory buffers";
8210 break;
8211 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8212 str = "ExternalASTSource: malloc'ed memory buffers";
8213 break;
8214 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8215 str = "ExternalASTSource: mmap'ed memory buffers";
8216 break;
8217 case CXTUResourceUsage_Preprocessor:
8218 str = "Preprocessor: malloc'ed memory";
8219 break;
8220 case CXTUResourceUsage_PreprocessingRecord:
8221 str = "Preprocessor: PreprocessingRecord";
8222 break;
8223 case CXTUResourceUsage_SourceManager_DataStructures:
8224 str = "SourceManager: data structures and tables";
8225 break;
8226 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8227 str = "Preprocessor: header search tables";
8228 break;
8229 }
8230 return str;
8231}
8232
8233CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008234 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008235 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008236 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008237 return usage;
8238 }
8239
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008240 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008241 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 ASTContext &astContext = astUnit->getASTContext();
8243
8244 // How much memory is used by AST nodes and types?
8245 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8246 (unsigned long) astContext.getASTAllocatedMemory());
8247
8248 // How much memory is used by identifiers?
8249 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8250 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8251
8252 // How much memory is used for selectors?
8253 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8254 (unsigned long) astContext.Selectors.getTotalMemory());
8255
8256 // How much memory is used by ASTContext's side tables?
8257 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8258 (unsigned long) astContext.getSideTableAllocatedMemory());
8259
8260 // How much memory is used for caching global code completion results?
8261 unsigned long completionBytes = 0;
8262 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008263 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008264 completionBytes = completionAllocator->getTotalMemory();
8265 }
8266 createCXTUResourceUsageEntry(*entries,
8267 CXTUResourceUsage_GlobalCompletionResults,
8268 completionBytes);
8269
8270 // How much memory is being used by SourceManager's content cache?
8271 createCXTUResourceUsageEntry(*entries,
8272 CXTUResourceUsage_SourceManagerContentCache,
8273 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8274
8275 // How much memory is being used by the MemoryBuffer's in SourceManager?
8276 const SourceManager::MemoryBufferSizes &srcBufs =
8277 astUnit->getSourceManager().getMemoryBufferSizes();
8278
8279 createCXTUResourceUsageEntry(*entries,
8280 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8281 (unsigned long) srcBufs.malloc_bytes);
8282 createCXTUResourceUsageEntry(*entries,
8283 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8284 (unsigned long) srcBufs.mmap_bytes);
8285 createCXTUResourceUsageEntry(*entries,
8286 CXTUResourceUsage_SourceManager_DataStructures,
8287 (unsigned long) astContext.getSourceManager()
8288 .getDataStructureSizes());
8289
8290 // How much memory is being used by the ExternalASTSource?
8291 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8292 const ExternalASTSource::MemoryBufferSizes &sizes =
8293 esrc->getMemoryBufferSizes();
8294
8295 createCXTUResourceUsageEntry(*entries,
8296 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8297 (unsigned long) sizes.malloc_bytes);
8298 createCXTUResourceUsageEntry(*entries,
8299 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8300 (unsigned long) sizes.mmap_bytes);
8301 }
8302
8303 // How much memory is being used by the Preprocessor?
8304 Preprocessor &pp = astUnit->getPreprocessor();
8305 createCXTUResourceUsageEntry(*entries,
8306 CXTUResourceUsage_Preprocessor,
8307 pp.getTotalMemory());
8308
8309 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8310 createCXTUResourceUsageEntry(*entries,
8311 CXTUResourceUsage_PreprocessingRecord,
8312 pRec->getTotalMemory());
8313 }
8314
8315 createCXTUResourceUsageEntry(*entries,
8316 CXTUResourceUsage_Preprocessor_HeaderSearch,
8317 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008318
Guy Benyei11169dd2012-12-18 14:30:41 +00008319 CXTUResourceUsage usage = { (void*) entries.get(),
8320 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008321 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008322 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008323 return usage;
8324}
8325
8326void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8327 if (usage.data)
8328 delete (MemUsageEntries*) usage.data;
8329}
8330
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008331CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8332 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008333 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008334 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008335
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008336 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008337 LOG_BAD_TU(TU);
8338 return skipped;
8339 }
8340
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008341 if (!file)
8342 return skipped;
8343
8344 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8345 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8346 if (!ppRec)
8347 return skipped;
8348
8349 ASTContext &Ctx = astUnit->getASTContext();
8350 SourceManager &sm = Ctx.getSourceManager();
8351 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8352 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008353 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008354
8355 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8356 std::vector<SourceRange> wantedRanges;
8357 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8358 i != ei; ++i) {
8359 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8360 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008361 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8362 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008363 }
8364
8365 skipped->count = wantedRanges.size();
8366 skipped->ranges = new CXSourceRange[skipped->count];
8367 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8368 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8369
8370 return skipped;
8371}
8372
Cameron Desrochersd8091282016-08-18 15:43:55 +00008373CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8374 CXSourceRangeList *skipped = new CXSourceRangeList;
8375 skipped->count = 0;
8376 skipped->ranges = nullptr;
8377
8378 if (isNotUsableTU(TU)) {
8379 LOG_BAD_TU(TU);
8380 return skipped;
8381 }
8382
8383 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8384 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8385 if (!ppRec)
8386 return skipped;
8387
8388 ASTContext &Ctx = astUnit->getASTContext();
8389
8390 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8391
8392 skipped->count = SkippedRanges.size();
8393 skipped->ranges = new CXSourceRange[skipped->count];
8394 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8395 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8396
8397 return skipped;
8398}
8399
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008400void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8401 if (ranges) {
8402 delete[] ranges->ranges;
8403 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008404 }
8405}
8406
Guy Benyei11169dd2012-12-18 14:30:41 +00008407void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8408 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8409 for (unsigned I = 0; I != Usage.numEntries; ++I)
8410 fprintf(stderr, " %s: %lu\n",
8411 clang_getTUResourceUsageName(Usage.entries[I].kind),
8412 Usage.entries[I].amount);
8413
8414 clang_disposeCXTUResourceUsage(Usage);
8415}
8416
8417//===----------------------------------------------------------------------===//
8418// Misc. utility functions.
8419//===----------------------------------------------------------------------===//
8420
8421/// Default to using an 8 MB stack size on "safety" threads.
8422static unsigned SafetyStackThreadSize = 8 << 20;
8423
8424namespace clang {
8425
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008426bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008427 unsigned Size) {
8428 if (!Size)
8429 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008430 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008431 return CRC.RunSafelyOnThread(Fn, Size);
8432 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008433}
8434
8435unsigned GetSafetyThreadStackSize() {
8436 return SafetyStackThreadSize;
8437}
8438
8439void SetSafetyThreadStackSize(unsigned Value) {
8440 SafetyStackThreadSize = Value;
8441}
8442
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008443}
Guy Benyei11169dd2012-12-18 14:30:41 +00008444
8445void clang::setThreadBackgroundPriority() {
8446 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8447 return;
8448
Alp Toker1a86ad22014-07-06 06:24:00 +00008449#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008450 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8451#endif
8452}
8453
8454void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8455 if (!Unit)
8456 return;
8457
8458 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8459 DEnd = Unit->stored_diag_end();
8460 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008461 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008462 CXString Msg = clang_formatDiagnostic(&Diag,
8463 clang_defaultDiagnosticDisplayOptions());
8464 fprintf(stderr, "%s\n", clang_getCString(Msg));
8465 clang_disposeString(Msg);
8466 }
8467#ifdef LLVM_ON_WIN32
8468 // On Windows, force a flush, since there may be multiple copies of
8469 // stderr and stdout in the file system, all with different buffers
8470 // but writing to the same device.
8471 fflush(stderr);
8472#endif
8473}
8474
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008475MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8476 SourceLocation MacroDefLoc,
8477 CXTranslationUnit TU){
8478 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008479 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008480 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008481 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008482
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008483 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008484 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008485 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008486 if (MD) {
8487 for (MacroDirective::DefInfo
8488 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8489 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8490 return Def.getMacroInfo();
8491 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008492 }
8493
Craig Topper69186e72014-06-08 08:38:04 +00008494 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008495}
8496
Richard Smith66a81862015-05-04 02:25:31 +00008497const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008498 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008499 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008500 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008501 const IdentifierInfo *II = MacroDef->getName();
8502 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008503 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008504
8505 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8506}
8507
Richard Smith66a81862015-05-04 02:25:31 +00008508MacroDefinitionRecord *
8509cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8510 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008511 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008512 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008513 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008514 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008515
8516 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008517 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008518 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8519 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008520 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008521
8522 // Check that the token is inside the definition and not its argument list.
8523 SourceManager &SM = Unit->getSourceManager();
8524 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008525 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008526 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008527 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008528
8529 Preprocessor &PP = Unit->getPreprocessor();
8530 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8531 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008532 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008533
Alp Toker2d57cea2014-05-17 04:53:25 +00008534 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008535 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008536 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008537
8538 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008539 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008540 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008541
Richard Smith20e883e2015-04-29 23:20:19 +00008542 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008543 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008544 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008545
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008546 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008547}
8548
Richard Smith66a81862015-05-04 02:25:31 +00008549MacroDefinitionRecord *
8550cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8551 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008552 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008553 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008554
8555 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008556 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008557 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008558 Preprocessor &PP = Unit->getPreprocessor();
8559 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008560 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008561 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8562 Token Tok;
8563 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008564 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008565
8566 return checkForMacroInMacroDefinition(MI, Tok, TU);
8567}
8568
Guy Benyei11169dd2012-12-18 14:30:41 +00008569CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008570 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008571}
8572
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008573Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8574 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008575 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008576 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008577 if (Unit->isMainFileAST())
8578 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008579 return *this;
8580 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008581 } else {
8582 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008583 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008584 return *this;
8585}
8586
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008587Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8588 *this << FE->getName();
8589 return *this;
8590}
8591
8592Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8593 CXString cursorName = clang_getCursorDisplayName(cursor);
8594 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8595 clang_disposeString(cursorName);
8596 return *this;
8597}
8598
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008599Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8600 CXFile File;
8601 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008602 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008603 CXString FileName = clang_getFileName(File);
8604 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8605 clang_disposeString(FileName);
8606 return *this;
8607}
8608
8609Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8610 CXSourceLocation BLoc = clang_getRangeStart(range);
8611 CXSourceLocation ELoc = clang_getRangeEnd(range);
8612
8613 CXFile BFile;
8614 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008615 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008616
8617 CXFile EFile;
8618 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008619 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008620
8621 CXString BFileName = clang_getFileName(BFile);
8622 if (BFile == EFile) {
8623 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8624 BLine, BColumn, ELine, EColumn);
8625 } else {
8626 CXString EFileName = clang_getFileName(EFile);
8627 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8628 BLine, BColumn)
8629 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8630 ELine, EColumn);
8631 clang_disposeString(EFileName);
8632 }
8633 clang_disposeString(BFileName);
8634 return *this;
8635}
8636
8637Logger &cxindex::Logger::operator<<(CXString Str) {
8638 *this << clang_getCString(Str);
8639 return *this;
8640}
8641
8642Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8643 LogOS << Fmt;
8644 return *this;
8645}
8646
Chandler Carruth37ad2582014-06-27 15:14:39 +00008647static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8648
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008649cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008650 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008651
8652 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8653
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008654 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008655 OS << "[libclang:" << Name << ':';
8656
Alp Toker1a86ad22014-07-06 06:24:00 +00008657#ifdef USE_DARWIN_THREADS
8658 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008659 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8660 OS << tid << ':';
8661#endif
8662
8663 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8664 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008665 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008666
8667 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008668 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008669 OS << "--------------------------------------------------\n";
8670 }
8671}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008672
8673#ifdef CLANG_TOOL_EXTRA_BUILD
8674// This anchor is used to force the linker to link the clang-tidy plugin.
8675extern volatile int ClangTidyPluginAnchorSource;
8676static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8677 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008678
8679// This anchor is used to force the linker to link the clang-include-fixer
8680// plugin.
8681extern volatile int ClangIncludeFixerPluginAnchorSource;
8682static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8683 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008684#endif