blob: ae7fd4271799fa814e954face138f01b9fc3e2fd [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the main API hooks in the Clang-C Source Indexing
10// library.
11//
12//===----------------------------------------------------------------------===//
13
Guy Benyei11169dd2012-12-18 14:30:41 +000014#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000015#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000016#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CXCursor.h"
18#include "CXSourceLocation.h"
19#include "CXString.h"
20#include "CXTranslationUnit.h"
21#include "CXType.h"
22#include "CursorVisitor.h"
Jan Korousf7d23762019-09-12 22:55:55 +000023#include "clang-c/FatalErrorHandler.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Jan Korous7e36ecd2019-09-05 20:33:52 +000025#include "clang/AST/Mangle.h"
Alexey Bataev95598342020-02-10 15:49:05 -050026#include "clang/AST/OpenMPClause.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/AST/StmtVisitor.h"
28#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000029#include "clang/Basic/DiagnosticCategories.h"
30#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000031#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000032#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000033#include "clang/Basic/Version.h"
34#include "clang/Frontend/ASTUnit.h"
35#include "clang/Frontend/CompilerInstance.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000036#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "clang/Lex/HeaderSearch.h"
38#include "clang/Lex/Lexer.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
41#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"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/Program.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000053#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/Threading.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
Benjamin Kramer762bc332019-08-07 14:44:40 +000057#include <mutex>
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000058
Alp Toker1a86ad22014-07-06 06:24:00 +000059#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
60#define USE_DARWIN_THREADS
61#endif
62
63#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000064#include <pthread.h>
65#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000066
67using namespace clang;
68using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000069using namespace clang::cxtu;
70using namespace clang::cxindex;
71
David Blaikieea4395e2017-01-06 19:49:01 +000072CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
73 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000074 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000075 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000076 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000077 CXTranslationUnit D = new CXTranslationUnitImpl();
78 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000079 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000080 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000082 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000083 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000084 D->ParsingOptions = 0;
85 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000086 return D;
87}
88
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000089bool cxtu::isASTReadError(ASTUnit *AU) {
90 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
91 DEnd = AU->stored_diag_end();
92 D != DEnd; ++D) {
93 if (D->getLevel() >= DiagnosticsEngine::Error &&
94 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
95 diag::DiagCat_AST_Deserialization_Issue)
96 return true;
97 }
98 return false;
99}
100
Guy Benyei11169dd2012-12-18 14:30:41 +0000101cxtu::CXTUOwner::~CXTUOwner() {
102 if (TU)
103 clang_disposeTranslationUnit(TU);
104}
105
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000106/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000107/// the translation unit.
108static RangeComparisonResult RangeCompare(SourceManager &SM,
109 SourceRange R1,
110 SourceRange R2) {
111 assert(R1.isValid() && "First range is invalid?");
112 assert(R2.isValid() && "Second range is invalid?");
113 if (R1.getEnd() != R2.getBegin() &&
114 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
115 return RangeBefore;
116 if (R2.getEnd() != R1.getBegin() &&
117 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
118 return RangeAfter;
119 return RangeOverlap;
120}
121
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000122/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000123/// a given source range.
124static RangeComparisonResult LocationCompare(SourceManager &SM,
125 SourceLocation L, SourceRange R) {
126 assert(R.isValid() && "First range is invalid?");
127 assert(L.isValid() && "Second range is invalid?");
128 if (L == R.getBegin() || L == R.getEnd())
129 return RangeOverlap;
130 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
131 return RangeBefore;
132 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
133 return RangeAfter;
134 return RangeOverlap;
135}
136
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000137/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000138///
139/// Clang internally represents ranges where the end location points to the
140/// start of the token at the end. However, for external clients it is more
141/// useful to have a CXSourceRange be a proper half-open interval. This routine
142/// does the appropriate translation.
143CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
144 const LangOptions &LangOpts,
145 const CharSourceRange &R) {
146 // We want the last character in this location, so we will adjust the
147 // location accordingly.
148 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000149 bool IsTokenRange = R.isTokenRange();
150 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
151 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
152 EndLoc = Expansion.getEnd();
153 IsTokenRange = Expansion.isTokenRange();
154 }
155 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000156 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
157 SM, LangOpts);
158 EndLoc = EndLoc.getLocWithOffset(Length);
159 }
160
Bill Wendlingeade3622013-01-23 08:25:41 +0000161 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000162 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000163 R.getBegin().getRawEncoding(),
164 EndLoc.getRawEncoding()
165 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000166 return Result;
167}
168
169//===----------------------------------------------------------------------===//
170// Cursor visitor.
171//===----------------------------------------------------------------------===//
172
173static SourceRange getRawCursorExtent(CXCursor C);
174static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
175
Guy Benyei11169dd2012-12-18 14:30:41 +0000176RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
177 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
178}
179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000180/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000181/// its children.
182///
183/// \param Cursor the cursor to visit.
184///
185/// \param CheckedRegionOfInterest if true, then the caller already checked
186/// that this cursor is within the region of interest.
187///
188/// \returns true if the visitation should be aborted, false if it
189/// should continue.
190bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
191 if (clang_isInvalid(Cursor.kind))
192 return false;
193
194 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000195 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000196 if (!D) {
197 assert(0 && "Invalid declaration cursor");
198 return true; // abort.
199 }
200
201 // Ignore implicit declarations, unless it's an objc method because
202 // currently we should report implicit methods for properties when indexing.
203 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
204 return false;
205 }
206
207 // If we have a range of interest, and this cursor doesn't intersect with it,
208 // we're done.
209 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
210 SourceRange Range = getRawCursorExtent(Cursor);
211 if (Range.isInvalid() || CompareRegionOfInterest(Range))
212 return false;
213 }
214
215 switch (Visitor(Cursor, Parent, ClientData)) {
216 case CXChildVisit_Break:
217 return true;
218
219 case CXChildVisit_Continue:
220 return false;
221
222 case CXChildVisit_Recurse: {
223 bool ret = VisitChildren(Cursor);
224 if (PostChildrenVisitor)
225 if (PostChildrenVisitor(Cursor, ClientData))
226 return true;
227 return ret;
228 }
229 }
230
231 llvm_unreachable("Invalid CXChildVisitResult!");
232}
233
234static bool visitPreprocessedEntitiesInRange(SourceRange R,
235 PreprocessingRecord &PPRec,
236 CursorVisitor &Visitor) {
237 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
238 FileID FID;
239
240 if (!Visitor.shouldVisitIncludedEntities()) {
241 // If the begin/end of the range lie in the same FileID, do the optimization
242 // where we skip preprocessed entities that do not come from the same FileID.
243 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
244 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
245 FID = FileID();
246 }
247
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000248 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
249 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000250 PPRec, FID);
251}
252
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000253bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000254 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000255 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000256
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000257 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000258 SourceManager &SM = Unit->getSourceManager();
259
260 std::pair<FileID, unsigned>
261 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
262 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
263
264 if (End.first != Begin.first) {
265 // If the end does not reside in the same file, try to recover by
266 // picking the end of the file of begin location.
267 End.first = Begin.first;
268 End.second = SM.getFileIDSize(Begin.first);
269 }
270
271 assert(Begin.first == End.first);
272 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000273 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000274
275 FileID File = Begin.first;
276 unsigned Offset = Begin.second;
277 unsigned Length = End.second - Begin.second;
278
279 if (!VisitDeclsOnly && !VisitPreprocessorLast)
280 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000281 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000282
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000283 if (visitDeclsFromFileRegion(File, Offset, Length))
284 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000285
286 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000287 return visitPreprocessedEntitiesInRegion();
288
289 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000290}
291
292static bool isInLexicalContext(Decl *D, DeclContext *DC) {
293 if (!DC)
294 return false;
295
296 for (DeclContext *DeclDC = D->getLexicalDeclContext();
297 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
298 if (DeclDC == DC)
299 return true;
300 }
301 return false;
302}
303
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000304bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000305 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000306 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000307 SourceManager &SM = Unit->getSourceManager();
308 SourceRange Range = RegionOfInterest;
309
310 SmallVector<Decl *, 16> Decls;
311 Unit->findFileRegionDecls(File, Offset, Length, Decls);
312
313 // If we didn't find any file level decls for the file, try looking at the
314 // file that it was included from.
315 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
316 bool Invalid = false;
317 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
318 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000319 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000320
321 SourceLocation Outer;
322 if (SLEntry.isFile())
323 Outer = SLEntry.getFile().getIncludeLoc();
324 else
325 Outer = SLEntry.getExpansion().getExpansionLocStart();
326 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000327 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000328
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000329 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000330 Length = 0;
331 Unit->findFileRegionDecls(File, Offset, Length, Decls);
332 }
333
334 assert(!Decls.empty());
335
336 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000337 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000338 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
339 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000340 Decl *D = *DIt;
341 if (D->getSourceRange().isInvalid())
342 continue;
343
344 if (isInLexicalContext(D, CurDC))
345 continue;
346
347 CurDC = dyn_cast<DeclContext>(D);
348
349 if (TagDecl *TD = dyn_cast<TagDecl>(D))
350 if (!TD->isFreeStanding())
351 continue;
352
353 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
354 if (CompRes == RangeBefore)
355 continue;
356 if (CompRes == RangeAfter)
357 break;
358
359 assert(CompRes == RangeOverlap);
360 VisitedAtLeastOnce = true;
361
362 if (isa<ObjCContainerDecl>(D)) {
363 FileDI_current = &DIt;
364 FileDE_current = DE;
365 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000366 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000367 }
368
369 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000370 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000371 }
372
373 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000374 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000375
376 // No Decls overlapped with the range. Move up the lexical context until there
377 // is a context that contains the range or we reach the translation unit
378 // level.
379 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
380 : (*(DIt-1))->getLexicalDeclContext();
381
382 while (DC && !DC->isTranslationUnit()) {
383 Decl *D = cast<Decl>(DC);
384 SourceRange CurDeclRange = D->getSourceRange();
385 if (CurDeclRange.isInvalid())
386 break;
387
388 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000389 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
390 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000391 }
392
393 DC = D->getLexicalDeclContext();
394 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000395
396 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000397}
398
399bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
400 if (!AU->getPreprocessor().getPreprocessingRecord())
401 return false;
402
403 PreprocessingRecord &PPRec
404 = *AU->getPreprocessor().getPreprocessingRecord();
405 SourceManager &SM = AU->getSourceManager();
406
407 if (RegionOfInterest.isValid()) {
408 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
409 SourceLocation B = MappedRange.getBegin();
410 SourceLocation E = MappedRange.getEnd();
411
412 if (AU->isInPreambleFileID(B)) {
413 if (SM.isLoadedSourceLocation(E))
414 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
415 PPRec, *this);
416
417 // Beginning of range lies in the preamble but it also extends beyond
418 // it into the main file. Split the range into 2 parts, one covering
419 // the preamble and another covering the main file. This allows subsequent
420 // calls to visitPreprocessedEntitiesInRange to accept a source range that
421 // lies in the same FileID, allowing it to skip preprocessed entities that
422 // do not come from the same FileID.
423 bool breaked =
424 visitPreprocessedEntitiesInRange(
425 SourceRange(B, AU->getEndOfPreambleFileID()),
426 PPRec, *this);
427 if (breaked) return true;
428 return visitPreprocessedEntitiesInRange(
429 SourceRange(AU->getStartOfMainFileID(), E),
430 PPRec, *this);
431 }
432
433 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
434 }
435
436 bool OnlyLocalDecls
437 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
438
439 if (OnlyLocalDecls)
440 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
441 PPRec);
442
443 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
444}
445
446template<typename InputIterator>
447bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
448 InputIterator Last,
449 PreprocessingRecord &PPRec,
450 FileID FID) {
451 for (; First != Last; ++First) {
452 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
453 continue;
454
455 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000456 if (!PPE)
457 continue;
458
Guy Benyei11169dd2012-12-18 14:30:41 +0000459 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
460 if (Visit(MakeMacroExpansionCursor(ME, TU)))
461 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000462
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 continue;
464 }
Richard Smith66a81862015-05-04 02:25:31 +0000465
466 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000467 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
468 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000469
Guy Benyei11169dd2012-12-18 14:30:41 +0000470 continue;
471 }
472
473 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
474 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
475 return true;
476
477 continue;
478 }
479 }
480
481 return false;
482}
483
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000484/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000485///
486/// \returns true if the visitation should be aborted, false if it
487/// should continue.
488bool CursorVisitor::VisitChildren(CXCursor Cursor) {
489 if (clang_isReference(Cursor.kind) &&
490 Cursor.kind != CXCursor_CXXBaseSpecifier) {
491 // By definition, references have no children.
492 return false;
493 }
494
495 // Set the Parent field to Cursor, then back to its old value once we're
496 // done.
497 SetParentRAII SetParent(Parent, StmtParent, Cursor);
498
499 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000500 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000501 if (!D)
502 return false;
503
504 return VisitAttributes(D) || Visit(D);
505 }
506
507 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000508 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 return Visit(S);
510
511 return false;
512 }
513
514 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000515 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000516 return Visit(E);
517
518 return false;
519 }
520
521 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000522 CXTranslationUnit TU = getCursorTU(Cursor);
523 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000524
525 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
526 for (unsigned I = 0; I != 2; ++I) {
527 if (VisitOrder[I]) {
528 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
529 RegionOfInterest.isInvalid()) {
530 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
531 TLEnd = CXXUnit->top_level_end();
532 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000533 const Optional<bool> V = handleDeclForVisitation(*TL);
534 if (!V.hasValue())
535 continue;
536 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000537 }
538 } else if (VisitDeclContext(
539 CXXUnit->getASTContext().getTranslationUnitDecl()))
540 return true;
541 continue;
542 }
543
544 // Walk the preprocessing record.
545 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
546 visitPreprocessedEntitiesInRegion();
547 }
548
549 return false;
550 }
551
552 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000553 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000554 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
555 return Visit(BaseTSInfo->getTypeLoc());
556 }
557 }
558 }
559
560 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000561 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000562 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000563 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000564 return Visit(cxcursor::MakeCursorObjCClassRef(
565 ObjT->getInterface(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000566 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 }
568
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000569 // If pointing inside a macro definition, check if the token is an identifier
570 // that was ever defined as a macro. In such a case, create a "pseudo" macro
571 // expansion cursor for that token.
572 SourceLocation BeginLoc = RegionOfInterest.getBegin();
573 if (Cursor.kind == CXCursor_MacroDefinition &&
574 BeginLoc == RegionOfInterest.getEnd()) {
575 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000576 const MacroInfo *MI =
577 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000578 if (MacroDefinitionRecord *MacroDef =
579 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000580 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
581 }
582
Guy Benyei11169dd2012-12-18 14:30:41 +0000583 // Nothing to visit at the moment.
584 return false;
585}
586
587bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
588 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
589 if (Visit(TSInfo->getTypeLoc()))
590 return true;
591
592 if (Stmt *Body = B->getBody())
593 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
594
595 return false;
596}
597
Ted Kremenek03325582013-02-21 01:29:01 +0000598Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 if (RegionOfInterest.isValid()) {
600 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
601 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000602 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000603
604 switch (CompareRegionOfInterest(Range)) {
605 case RangeBefore:
606 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000607 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000608
609 case RangeAfter:
610 // This declaration comes after the region of interest; we're done.
611 return false;
612
613 case RangeOverlap:
614 // This declaration overlaps the region of interest; visit it.
615 break;
616 }
617 }
618 return true;
619}
620
621bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
622 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
623
624 // FIXME: Eventually remove. This part of a hack to support proper
625 // iteration over all Decls contained lexically within an ObjC container.
626 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
627 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
628
629 for ( ; I != E; ++I) {
630 Decl *D = *I;
631 if (D->getLexicalDeclContext() != DC)
632 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -0800633 // Filter out synthesized property accessor redeclarations.
634 if (isa<ObjCImplDecl>(DC))
635 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
636 if (OMD->isSynthesizedAccessorStub())
637 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000638 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 if (!V.hasValue())
640 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000641 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000642 }
643 return false;
644}
645
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000646Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
647 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
648
649 // Ignore synthesized ivars here, otherwise if we have something like:
650 // @synthesize prop = _prop;
651 // and '_prop' is not declared, we will encounter a '_prop' ivar before
652 // encountering the 'prop' synthesize declaration and we will think that
653 // we passed the region-of-interest.
654 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
655 if (ivarD->getSynthesize())
656 return None;
657 }
658
659 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
660 // declarations is a mismatch with the compiler semantics.
661 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
662 auto *ID = cast<ObjCInterfaceDecl>(D);
663 if (!ID->isThisDeclarationADefinition())
664 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
665
666 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
667 auto *PD = cast<ObjCProtocolDecl>(D);
668 if (!PD->isThisDeclarationADefinition())
669 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
670 }
671
672 const Optional<bool> V = shouldVisitCursor(Cursor);
673 if (!V.hasValue())
674 return None;
675 if (!V.getValue())
676 return false;
677 if (Visit(Cursor, true))
678 return true;
679 return None;
680}
681
Guy Benyei11169dd2012-12-18 14:30:41 +0000682bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
683 llvm_unreachable("Translation units are visited directly by Visit()");
684}
685
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000686bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
687 if (VisitTemplateParameters(D->getTemplateParameters()))
688 return true;
689
690 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
691}
692
Guy Benyei11169dd2012-12-18 14:30:41 +0000693bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
694 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
695 return Visit(TSInfo->getTypeLoc());
696
697 return false;
698}
699
700bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
701 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
702 return Visit(TSInfo->getTypeLoc());
703
704 return false;
705}
706
707bool CursorVisitor::VisitTagDecl(TagDecl *D) {
708 return VisitDeclContext(D);
709}
710
711bool CursorVisitor::VisitClassTemplateSpecializationDecl(
712 ClassTemplateSpecializationDecl *D) {
713 bool ShouldVisitBody = false;
714 switch (D->getSpecializationKind()) {
715 case TSK_Undeclared:
716 case TSK_ImplicitInstantiation:
717 // Nothing to visit
718 return false;
719
720 case TSK_ExplicitInstantiationDeclaration:
721 case TSK_ExplicitInstantiationDefinition:
722 break;
723
724 case TSK_ExplicitSpecialization:
725 ShouldVisitBody = true;
726 break;
727 }
728
729 // Visit the template arguments used in the specialization.
730 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
731 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000732 if (TemplateSpecializationTypeLoc TSTLoc =
733 TL.getAs<TemplateSpecializationTypeLoc>()) {
734 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
735 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000736 return true;
737 }
738 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000739
740 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000741}
742
743bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
744 ClassTemplatePartialSpecializationDecl *D) {
745 // FIXME: Visit the "outer" template parameter lists on the TagDecl
746 // before visiting these template parameters.
747 if (VisitTemplateParameters(D->getTemplateParameters()))
748 return true;
749
750 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000751 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
752 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
753 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000754 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
755 return true;
756
757 return VisitCXXRecordDecl(D);
758}
759
760bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Saar Razff1e0fc2020-01-15 02:48:42 +0200761 if (const auto *TC = D->getTypeConstraint())
762 if (Visit(MakeCXCursor(TC->getImmediatelyDeclaredConstraint(), StmtParent,
763 TU, RegionOfInterest)))
764 return true;
765
Guy Benyei11169dd2012-12-18 14:30:41 +0000766 // Visit the default argument.
767 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
768 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
769 if (Visit(DefArg->getTypeLoc()))
770 return true;
771
772 return false;
773}
774
775bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
776 if (Expr *Init = D->getInitExpr())
777 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
778 return false;
779}
780
781bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000782 unsigned NumParamList = DD->getNumTemplateParameterLists();
783 for (unsigned i = 0; i < NumParamList; i++) {
784 TemplateParameterList* Params = DD->getTemplateParameterList(i);
785 if (VisitTemplateParameters(Params))
786 return true;
787 }
788
Guy Benyei11169dd2012-12-18 14:30:41 +0000789 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
790 if (Visit(TSInfo->getTypeLoc()))
791 return true;
792
793 // Visit the nested-name-specifier, if present.
794 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
795 if (VisitNestedNameSpecifierLoc(QualifierLoc))
796 return true;
797
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000798 return false;
799}
800
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000801static bool HasTrailingReturnType(FunctionDecl *ND) {
802 const QualType Ty = ND->getType();
803 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
804 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
805 return FT->hasTrailingReturn();
806 }
807
808 return false;
809}
810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000812static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
813 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000814 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
815}
816
Guy Benyei11169dd2012-12-18 14:30:41 +0000817bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000818 unsigned NumParamList = ND->getNumTemplateParameterLists();
819 for (unsigned i = 0; i < NumParamList; i++) {
820 TemplateParameterList* Params = ND->getTemplateParameterList(i);
821 if (VisitTemplateParameters(Params))
822 return true;
823 }
824
Guy Benyei11169dd2012-12-18 14:30:41 +0000825 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
826 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000827 // written. This requires a bit of work.
828 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
829 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000830 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000831
832 // If we have a function declared directly (without the use of a typedef),
833 // visit just the return type. Otherwise, just visit the function's type
834 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000835 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
836 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000837 (!FTL && Visit(TL)))
838 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000839
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000840 // Visit the nested-name-specifier, if present.
841 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
842 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000843 return true;
844
845 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000846 if (!isa<CXXDestructorDecl>(ND))
847 if (VisitDeclarationNameInfo(ND->getNameInfo()))
848 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000849
850 // FIXME: Visit explicitly-specified template arguments!
851
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000852 // Visit the function parameters, if we have a function type.
853 if (FTL && VisitFunctionTypeLoc(FTL, true))
854 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000855
856 // Visit the function's trailing return type.
857 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
858 return true;
859
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000860 // FIXME: Attributes?
861 }
862
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
864 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
865 // Find the initializers that were written in the source.
866 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000867 for (auto *I : Constructor->inits()) {
868 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 continue;
870
Aaron Ballman0ad78302014-03-13 17:34:31 +0000871 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000872 }
873
874 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000875 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
876 &CompareCXXCtorInitializers);
877
Guy Benyei11169dd2012-12-18 14:30:41 +0000878 // Visit the initializers in source order
879 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
880 CXXCtorInitializer *Init = WrittenInits[I];
881 if (Init->isAnyMemberInitializer()) {
882 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
883 Init->getMemberLocation(), TU)))
884 return true;
885 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
886 if (Visit(TInfo->getTypeLoc()))
887 return true;
888 }
889
890 // Visit the initializer value.
891 if (Expr *Initializer = Init->getInit())
892 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
893 return true;
894 }
895 }
896
897 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
898 return true;
899 }
900
901 return false;
902}
903
904bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
905 if (VisitDeclaratorDecl(D))
906 return true;
907
908 if (Expr *BitWidth = D->getBitWidth())
909 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
910
Benjamin Kramer99f97592017-11-15 12:20:41 +0000911 if (Expr *Init = D->getInClassInitializer())
912 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
913
Guy Benyei11169dd2012-12-18 14:30:41 +0000914 return false;
915}
916
917bool CursorVisitor::VisitVarDecl(VarDecl *D) {
918 if (VisitDeclaratorDecl(D))
919 return true;
920
921 if (Expr *Init = D->getInit())
922 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
923
924 return false;
925}
926
927bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
928 if (VisitDeclaratorDecl(D))
929 return true;
930
931 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
932 if (Expr *DefArg = D->getDefaultArgument())
933 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
934
935 return false;
936}
937
938bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
939 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
940 // before visiting these template parameters.
941 if (VisitTemplateParameters(D->getTemplateParameters()))
942 return true;
943
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000944 auto* FD = D->getTemplatedDecl();
945 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000946}
947
948bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
949 // FIXME: Visit the "outer" template parameter lists on the TagDecl
950 // before visiting these template parameters.
951 if (VisitTemplateParameters(D->getTemplateParameters()))
952 return true;
953
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000954 auto* CD = D->getTemplatedDecl();
955 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000956}
957
958bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
959 if (VisitTemplateParameters(D->getTemplateParameters()))
960 return true;
961
962 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
963 VisitTemplateArgumentLoc(D->getDefaultArgument()))
964 return true;
965
966 return false;
967}
968
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000969bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
970 // Visit the bound, if it's explicit.
971 if (D->hasExplicitBound()) {
972 if (auto TInfo = D->getTypeSourceInfo()) {
973 if (Visit(TInfo->getTypeLoc()))
974 return true;
975 }
976 }
977
978 return false;
979}
980
Guy Benyei11169dd2012-12-18 14:30:41 +0000981bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000982 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 if (Visit(TSInfo->getTypeLoc()))
984 return true;
985
David Majnemer59f77922016-06-24 04:05:48 +0000986 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000987 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 return true;
989 }
990
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000991 return ND->isThisDeclarationADefinition() &&
992 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000993}
994
995template <typename DeclIt>
996static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
997 SourceManager &SM, SourceLocation EndLoc,
998 SmallVectorImpl<Decl *> &Decls) {
999 DeclIt next = *DI_current;
1000 while (++next != DE_current) {
1001 Decl *D_next = *next;
1002 if (!D_next)
1003 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001004 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 if (!L.isValid())
1006 break;
1007 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1008 *DI_current = next;
1009 Decls.push_back(D_next);
1010 continue;
1011 }
1012 break;
1013 }
1014}
1015
Guy Benyei11169dd2012-12-18 14:30:41 +00001016bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1017 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1018 // an @implementation can lexically contain Decls that are not properly
1019 // nested in the AST. When we identify such cases, we need to retrofit
1020 // this nesting here.
1021 if (!DI_current && !FileDI_current)
1022 return VisitDeclContext(D);
1023
1024 // Scan the Decls that immediately come after the container
1025 // in the current DeclContext. If any fall within the
1026 // container's lexical region, stash them into a vector
1027 // for later processing.
1028 SmallVector<Decl *, 24> DeclsInContainer;
1029 SourceLocation EndLoc = D->getSourceRange().getEnd();
1030 SourceManager &SM = AU->getSourceManager();
1031 if (EndLoc.isValid()) {
1032 if (DI_current) {
1033 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1034 DeclsInContainer);
1035 } else {
1036 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1037 DeclsInContainer);
1038 }
1039 }
1040
1041 // The common case.
1042 if (DeclsInContainer.empty())
1043 return VisitDeclContext(D);
1044
1045 // Get all the Decls in the DeclContext, and sort them with the
1046 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001047 for (auto *SubDecl : D->decls()) {
1048 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001049 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001050 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001051 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 }
1053
1054 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001055 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001056 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001057 SourceLocation L_A = A->getBeginLoc();
1058 SourceLocation L_B = B->getBeginLoc();
1059 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001060 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1061 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001062 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001063
1064 // Now visit the decls.
1065 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1066 E = DeclsInContainer.end(); I != E; ++I) {
1067 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001068 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001069 if (!V.hasValue())
1070 continue;
1071 if (!V.getValue())
1072 return false;
1073 if (Visit(Cursor, true))
1074 return true;
1075 }
1076 return false;
1077}
1078
1079bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1080 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1081 TU)))
1082 return true;
1083
Douglas Gregore9d95f12015-07-07 03:57:35 +00001084 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1085 return true;
1086
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1088 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1089 E = ND->protocol_end(); I != E; ++I, ++PL)
1090 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1091 return true;
1092
1093 return VisitObjCContainerDecl(ND);
1094}
1095
1096bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1097 if (!PID->isThisDeclarationADefinition())
1098 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1099
1100 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1101 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1102 E = PID->protocol_end(); I != E; ++I, ++PL)
1103 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1104 return true;
1105
1106 return VisitObjCContainerDecl(PID);
1107}
1108
1109bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1110 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1111 return true;
1112
1113 // FIXME: This implements a workaround with @property declarations also being
1114 // installed in the DeclContext for the @interface. Eventually this code
1115 // should be removed.
1116 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1117 if (!CDecl || !CDecl->IsClassExtension())
1118 return false;
1119
1120 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1121 if (!ID)
1122 return false;
1123
1124 IdentifierInfo *PropertyId = PD->getIdentifier();
1125 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001126 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1127 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001128
1129 if (!prevDecl)
1130 return false;
1131
1132 // Visit synthesized methods since they will be skipped when visiting
1133 // the @interface.
1134 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1135 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1136 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1137 return true;
1138
1139 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1140 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1141 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1142 return true;
1143
1144 return false;
1145}
1146
Douglas Gregore9d95f12015-07-07 03:57:35 +00001147bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1148 if (!typeParamList)
1149 return false;
1150
1151 for (auto *typeParam : *typeParamList) {
1152 // Visit the type parameter.
1153 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1154 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001155 }
1156
1157 return false;
1158}
1159
Guy Benyei11169dd2012-12-18 14:30:41 +00001160bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1161 if (!D->isThisDeclarationADefinition()) {
1162 // Forward declaration is treated like a reference.
1163 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1164 }
1165
Douglas Gregore9d95f12015-07-07 03:57:35 +00001166 // Objective-C type parameters.
1167 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1168 return true;
1169
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 // Issue callbacks for super class.
1171 if (D->getSuperClass() &&
1172 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1173 D->getSuperClassLoc(),
1174 TU)))
1175 return true;
1176
Douglas Gregore9d95f12015-07-07 03:57:35 +00001177 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1178 if (Visit(SuperClassTInfo->getTypeLoc()))
1179 return true;
1180
Guy Benyei11169dd2012-12-18 14:30:41 +00001181 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1182 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1183 E = D->protocol_end(); I != E; ++I, ++PL)
1184 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1185 return true;
1186
1187 return VisitObjCContainerDecl(D);
1188}
1189
1190bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1191 return VisitObjCContainerDecl(D);
1192}
1193
1194bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1195 // 'ID' could be null when dealing with invalid code.
1196 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1197 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1198 return true;
1199
1200 return VisitObjCImplDecl(D);
1201}
1202
1203bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1204#if 0
1205 // Issue callbacks for super class.
1206 // FIXME: No source location information!
1207 if (D->getSuperClass() &&
1208 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1209 D->getSuperClassLoc(),
1210 TU)))
1211 return true;
1212#endif
1213
1214 return VisitObjCImplDecl(D);
1215}
1216
1217bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1218 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1219 if (PD->isIvarNameSpecified())
1220 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1221
1222 return false;
1223}
1224
1225bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1226 return VisitDeclContext(D);
1227}
1228
1229bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1230 // Visit nested-name-specifier.
1231 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1232 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1233 return true;
1234
1235 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1236 D->getTargetNameLoc(), TU));
1237}
1238
1239bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1240 // Visit nested-name-specifier.
1241 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1242 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1243 return true;
1244 }
1245
1246 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1247 return true;
1248
1249 return VisitDeclarationNameInfo(D->getNameInfo());
1250}
1251
1252bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1253 // Visit nested-name-specifier.
1254 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1255 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1256 return true;
1257
1258 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1259 D->getIdentLocation(), TU));
1260}
1261
1262bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1263 // Visit nested-name-specifier.
1264 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1265 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1266 return true;
1267 }
1268
1269 return VisitDeclarationNameInfo(D->getNameInfo());
1270}
1271
1272bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1273 UnresolvedUsingTypenameDecl *D) {
1274 // Visit nested-name-specifier.
1275 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1276 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1277 return true;
1278
1279 return false;
1280}
1281
Olivier Goffart81978012016-06-09 16:15:55 +00001282bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1283 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1284 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001285 if (StringLiteral *Message = D->getMessage())
1286 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1287 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001288 return false;
1289}
1290
Olivier Goffartd211c642016-11-04 06:29:27 +00001291bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1292 if (NamedDecl *FriendD = D->getFriendDecl()) {
1293 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1294 return true;
1295 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1296 if (Visit(TI->getTypeLoc()))
1297 return true;
1298 }
1299 return false;
1300}
1301
Guy Benyei11169dd2012-12-18 14:30:41 +00001302bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1303 switch (Name.getName().getNameKind()) {
1304 case clang::DeclarationName::Identifier:
1305 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001306 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 case clang::DeclarationName::CXXOperatorName:
1308 case clang::DeclarationName::CXXUsingDirective:
1309 return false;
Richard Smith35845152017-02-07 01:37:30 +00001310
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 case clang::DeclarationName::CXXConstructorName:
1312 case clang::DeclarationName::CXXDestructorName:
1313 case clang::DeclarationName::CXXConversionFunctionName:
1314 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1315 return Visit(TSInfo->getTypeLoc());
1316 return false;
1317
1318 case clang::DeclarationName::ObjCZeroArgSelector:
1319 case clang::DeclarationName::ObjCOneArgSelector:
1320 case clang::DeclarationName::ObjCMultiArgSelector:
1321 // FIXME: Per-identifier location info?
1322 return false;
1323 }
1324
1325 llvm_unreachable("Invalid DeclarationName::Kind!");
1326}
1327
1328bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1329 SourceRange Range) {
1330 // FIXME: This whole routine is a hack to work around the lack of proper
1331 // source information in nested-name-specifiers (PR5791). Since we do have
1332 // a beginning source location, we can visit the first component of the
1333 // nested-name-specifier, if it's a single-token component.
1334 if (!NNS)
1335 return false;
1336
1337 // Get the first component in the nested-name-specifier.
1338 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1339 NNS = Prefix;
1340
1341 switch (NNS->getKind()) {
1342 case NestedNameSpecifier::Namespace:
1343 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1344 TU));
1345
1346 case NestedNameSpecifier::NamespaceAlias:
1347 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1348 Range.getBegin(), TU));
1349
1350 case NestedNameSpecifier::TypeSpec: {
1351 // If the type has a form where we know that the beginning of the source
1352 // range matches up with a reference cursor. Visit the appropriate reference
1353 // cursor.
1354 const Type *T = NNS->getAsType();
1355 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1356 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1357 if (const TagType *Tag = dyn_cast<TagType>(T))
1358 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1359 if (const TemplateSpecializationType *TST
1360 = dyn_cast<TemplateSpecializationType>(T))
1361 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1362 break;
1363 }
1364
1365 case NestedNameSpecifier::TypeSpecWithTemplate:
1366 case NestedNameSpecifier::Global:
1367 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001368 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 break;
1370 }
1371
1372 return false;
1373}
1374
1375bool
1376CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1377 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1378 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1379 Qualifiers.push_back(Qualifier);
1380
1381 while (!Qualifiers.empty()) {
1382 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1383 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1384 switch (NNS->getKind()) {
1385 case NestedNameSpecifier::Namespace:
1386 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1387 Q.getLocalBeginLoc(),
1388 TU)))
1389 return true;
1390
1391 break;
1392
1393 case NestedNameSpecifier::NamespaceAlias:
1394 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1395 Q.getLocalBeginLoc(),
1396 TU)))
1397 return true;
1398
1399 break;
1400
1401 case NestedNameSpecifier::TypeSpec:
1402 case NestedNameSpecifier::TypeSpecWithTemplate:
1403 if (Visit(Q.getTypeLoc()))
1404 return true;
1405
1406 break;
1407
1408 case NestedNameSpecifier::Global:
1409 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001410 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 break;
1412 }
1413 }
1414
1415 return false;
1416}
1417
1418bool CursorVisitor::VisitTemplateParameters(
1419 const TemplateParameterList *Params) {
1420 if (!Params)
1421 return false;
1422
1423 for (TemplateParameterList::const_iterator P = Params->begin(),
1424 PEnd = Params->end();
1425 P != PEnd; ++P) {
1426 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1427 return true;
1428 }
1429
1430 return false;
1431}
1432
1433bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1434 switch (Name.getKind()) {
1435 case TemplateName::Template:
1436 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1437
1438 case TemplateName::OverloadedTemplate:
1439 // Visit the overloaded template set.
1440 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1441 return true;
1442
1443 return false;
1444
Richard Smithb23c5e82019-05-09 03:31:27 +00001445 case TemplateName::AssumedTemplate:
1446 // FIXME: Visit DeclarationName?
1447 return false;
1448
Guy Benyei11169dd2012-12-18 14:30:41 +00001449 case TemplateName::DependentTemplate:
1450 // FIXME: Visit nested-name-specifier.
1451 return false;
1452
1453 case TemplateName::QualifiedTemplate:
1454 // FIXME: Visit nested-name-specifier.
1455 return Visit(MakeCursorTemplateRef(
1456 Name.getAsQualifiedTemplateName()->getDecl(),
1457 Loc, TU));
1458
1459 case TemplateName::SubstTemplateTemplateParm:
1460 return Visit(MakeCursorTemplateRef(
1461 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1462 Loc, TU));
1463
1464 case TemplateName::SubstTemplateTemplateParmPack:
1465 return Visit(MakeCursorTemplateRef(
1466 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1467 Loc, TU));
1468 }
1469
1470 llvm_unreachable("Invalid TemplateName::Kind!");
1471}
1472
1473bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1474 switch (TAL.getArgument().getKind()) {
1475 case TemplateArgument::Null:
1476 case TemplateArgument::Integral:
1477 case TemplateArgument::Pack:
1478 return false;
1479
1480 case TemplateArgument::Type:
1481 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1482 return Visit(TSInfo->getTypeLoc());
1483 return false;
1484
1485 case TemplateArgument::Declaration:
1486 if (Expr *E = TAL.getSourceDeclExpression())
1487 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1488 return false;
1489
1490 case TemplateArgument::NullPtr:
1491 if (Expr *E = TAL.getSourceNullPtrExpression())
1492 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1493 return false;
1494
1495 case TemplateArgument::Expression:
1496 if (Expr *E = TAL.getSourceExpression())
1497 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1498 return false;
1499
1500 case TemplateArgument::Template:
1501 case TemplateArgument::TemplateExpansion:
1502 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1503 return true;
1504
1505 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1506 TAL.getTemplateNameLoc());
1507 }
1508
1509 llvm_unreachable("Invalid TemplateArgument::Kind!");
1510}
1511
1512bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1513 return VisitDeclContext(D);
1514}
1515
1516bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1517 return Visit(TL.getUnqualifiedLoc());
1518}
1519
1520bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1521 ASTContext &Context = AU->getASTContext();
1522
1523 // Some builtin types (such as Objective-C's "id", "sel", and
1524 // "Class") have associated declarations. Create cursors for those.
1525 QualType VisitType;
1526 switch (TL.getTypePtr()->getKind()) {
1527
1528 case BuiltinType::Void:
1529 case BuiltinType::NullPtr:
1530 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001531#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1532 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001533#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001534#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1535 case BuiltinType::Id:
1536#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001537 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001538 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001539 case BuiltinType::OCLClkEvent:
1540 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001541 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001542#define SVE_TYPE(Name, Id, SingletonId) \
1543 case BuiltinType::Id:
1544#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00001545#define BUILTIN_TYPE(Id, SingletonId)
1546#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1547#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1548#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1549#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1550#include "clang/AST/BuiltinTypes.def"
1551 break;
1552
1553 case BuiltinType::ObjCId:
1554 VisitType = Context.getObjCIdType();
1555 break;
1556
1557 case BuiltinType::ObjCClass:
1558 VisitType = Context.getObjCClassType();
1559 break;
1560
1561 case BuiltinType::ObjCSel:
1562 VisitType = Context.getObjCSelType();
1563 break;
1564 }
1565
1566 if (!VisitType.isNull()) {
1567 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1568 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1569 TU));
1570 }
1571
1572 return false;
1573}
1574
1575bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1576 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1577}
1578
1579bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1580 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1581}
1582
1583bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1584 if (TL.isDefinition())
1585 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1586
1587 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1588}
1589
1590bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1591 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1592}
1593
1594bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001595 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001596}
1597
Manman Rene6be26c2016-09-13 17:25:08 +00001598bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001599 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001600 return true;
1601 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1602 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1603 TU)))
1604 return true;
1605 }
1606
1607 return false;
1608}
1609
Guy Benyei11169dd2012-12-18 14:30:41 +00001610bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1611 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1612 return true;
1613
Douglas Gregore9d95f12015-07-07 03:57:35 +00001614 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1615 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1616 return true;
1617 }
1618
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1620 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1621 TU)))
1622 return true;
1623 }
1624
1625 return false;
1626}
1627
1628bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1629 return Visit(TL.getPointeeLoc());
1630}
1631
1632bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1633 return Visit(TL.getInnerLoc());
1634}
1635
Leonard Chanc72aaf62019-05-07 03:20:17 +00001636bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1637 return Visit(TL.getInnerLoc());
1638}
1639
Guy Benyei11169dd2012-12-18 14:30:41 +00001640bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1641 return Visit(TL.getPointeeLoc());
1642}
1643
1644bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1645 return Visit(TL.getPointeeLoc());
1646}
1647
1648bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1649 return Visit(TL.getPointeeLoc());
1650}
1651
1652bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1653 return Visit(TL.getPointeeLoc());
1654}
1655
1656bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1657 return Visit(TL.getPointeeLoc());
1658}
1659
1660bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1661 return Visit(TL.getModifiedLoc());
1662}
1663
1664bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1665 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001666 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 return true;
1668
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001669 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1670 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1672 return true;
1673
1674 return false;
1675}
1676
1677bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1678 if (Visit(TL.getElementLoc()))
1679 return true;
1680
1681 if (Expr *Size = TL.getSizeExpr())
1682 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1683
1684 return false;
1685}
1686
Reid Kleckner8a365022013-06-24 17:51:48 +00001687bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1688 return Visit(TL.getOriginalLoc());
1689}
1690
Reid Kleckner0503a872013-12-05 01:23:43 +00001691bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1692 return Visit(TL.getOriginalLoc());
1693}
1694
Richard Smith600b5262017-01-26 20:40:47 +00001695bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1696 DeducedTemplateSpecializationTypeLoc TL) {
1697 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1698 TL.getTemplateNameLoc()))
1699 return true;
1700
1701 return false;
1702}
1703
Guy Benyei11169dd2012-12-18 14:30:41 +00001704bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1705 TemplateSpecializationTypeLoc TL) {
1706 // Visit the template name.
1707 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1708 TL.getTemplateNameLoc()))
1709 return true;
1710
1711 // Visit the template arguments.
1712 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1713 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1714 return true;
1715
1716 return false;
1717}
1718
1719bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1720 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1721}
1722
1723bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1724 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1725 return Visit(TSInfo->getTypeLoc());
1726
1727 return false;
1728}
1729
1730bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1731 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1732 return Visit(TSInfo->getTypeLoc());
1733
1734 return false;
1735}
1736
1737bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001738 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001739}
1740
1741bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1742 DependentTemplateSpecializationTypeLoc TL) {
1743 // Visit the nested-name-specifier, if there is one.
1744 if (TL.getQualifierLoc() &&
1745 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1746 return true;
1747
1748 // Visit the template arguments.
1749 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1750 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1751 return true;
1752
1753 return false;
1754}
1755
1756bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1757 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1758 return true;
1759
1760 return Visit(TL.getNamedTypeLoc());
1761}
1762
1763bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1764 return Visit(TL.getPatternLoc());
1765}
1766
1767bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1768 if (Expr *E = TL.getUnderlyingExpr())
1769 return Visit(MakeCXCursor(E, StmtParent, TU));
1770
1771 return false;
1772}
1773
1774bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1775 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1776}
1777
1778bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1779 return Visit(TL.getValueLoc());
1780}
1781
Xiuli Pan9c14e282016-01-09 12:53:17 +00001782bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1783 return Visit(TL.getValueLoc());
1784}
1785
Guy Benyei11169dd2012-12-18 14:30:41 +00001786#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1787bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1788 return Visit##PARENT##Loc(TL); \
1789}
1790
1791DEFAULT_TYPELOC_IMPL(Complex, Type)
1792DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1793DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1794DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1795DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001796DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001797DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001798DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1799DEFAULT_TYPELOC_IMPL(Vector, Type)
1800DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1801DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1802DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1803DEFAULT_TYPELOC_IMPL(Record, TagType)
1804DEFAULT_TYPELOC_IMPL(Enum, TagType)
1805DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1806DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1807DEFAULT_TYPELOC_IMPL(Auto, Type)
1808
1809bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1810 // Visit the nested-name-specifier, if present.
1811 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1812 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1813 return true;
1814
1815 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001816 for (const auto &I : D->bases()) {
1817 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001818 return true;
1819 }
1820 }
1821
1822 return VisitTagDecl(D);
1823}
1824
1825bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001826 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001827 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1828 !I->isImplicit()) &&
1829 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 return true;
1831
1832 return false;
1833}
1834
1835//===----------------------------------------------------------------------===//
1836// Data-recursive visitor methods.
1837//===----------------------------------------------------------------------===//
1838
1839namespace {
1840#define DEF_JOB(NAME, DATA, KIND)\
1841class NAME : public VisitorJob {\
1842public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001843 NAME(const DATA *d, CXCursor parent) : \
1844 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001845 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001846 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001847};
1848
1849DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1850DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1851DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1852DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001853DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1854DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1855DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1856#undef DEF_JOB
1857
James Y Knight04ec5bf2015-12-24 02:59:37 +00001858class ExplicitTemplateArgsVisit : public VisitorJob {
1859public:
1860 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1861 const TemplateArgumentLoc *End, CXCursor parent)
1862 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1863 End) {}
1864 static bool classof(const VisitorJob *VJ) {
1865 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1866 }
1867 const TemplateArgumentLoc *begin() const {
1868 return static_cast<const TemplateArgumentLoc *>(data[0]);
1869 }
1870 const TemplateArgumentLoc *end() {
1871 return static_cast<const TemplateArgumentLoc *>(data[1]);
1872 }
1873};
Guy Benyei11169dd2012-12-18 14:30:41 +00001874class DeclVisit : public VisitorJob {
1875public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001876 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001877 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001878 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 static bool classof(const VisitorJob *VJ) {
1880 return VJ->getKind() == DeclVisitKind;
1881 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001882 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001883 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001884};
1885class TypeLocVisit : public VisitorJob {
1886public:
1887 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1888 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1889 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1890
1891 static bool classof(const VisitorJob *VJ) {
1892 return VJ->getKind() == TypeLocVisitKind;
1893 }
1894
1895 TypeLoc get() const {
1896 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001897 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001898 }
1899};
1900
1901class LabelRefVisit : public VisitorJob {
1902public:
1903 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1904 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1905 labelLoc.getPtrEncoding()) {}
1906
1907 static bool classof(const VisitorJob *VJ) {
1908 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1909 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001910 const LabelDecl *get() const {
1911 return static_cast<const LabelDecl *>(data[0]);
1912 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001913 SourceLocation getLoc() const {
1914 return SourceLocation::getFromPtrEncoding(data[1]); }
1915};
1916
1917class NestedNameSpecifierLocVisit : public VisitorJob {
1918public:
1919 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1920 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1921 Qualifier.getNestedNameSpecifier(),
1922 Qualifier.getOpaqueData()) { }
1923
1924 static bool classof(const VisitorJob *VJ) {
1925 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1926 }
1927
1928 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001929 return NestedNameSpecifierLoc(
1930 const_cast<NestedNameSpecifier *>(
1931 static_cast<const NestedNameSpecifier *>(data[0])),
1932 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001933 }
1934};
1935
1936class DeclarationNameInfoVisit : public VisitorJob {
1937public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001938 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001939 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 static bool classof(const VisitorJob *VJ) {
1941 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1942 }
1943 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001944 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001945 switch (S->getStmtClass()) {
1946 default:
1947 llvm_unreachable("Unhandled Stmt");
1948 case clang::Stmt::MSDependentExistsStmtClass:
1949 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1950 case Stmt::CXXDependentScopeMemberExprClass:
1951 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1952 case Stmt::DependentScopeDeclRefExprClass:
1953 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001954 case Stmt::OMPCriticalDirectiveClass:
1955 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001956 }
1957 }
1958};
1959class MemberRefVisit : public VisitorJob {
1960public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001961 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001962 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1963 L.getPtrEncoding()) {}
1964 static bool classof(const VisitorJob *VJ) {
1965 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1966 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001967 const FieldDecl *get() const {
1968 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001969 }
1970 SourceLocation getLoc() const {
1971 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1972 }
1973};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001974class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001975 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001976 VisitorWorkList &WL;
1977 CXCursor Parent;
1978public:
1979 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1980 : WL(wl), Parent(parent) {}
1981
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001982 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1983 void VisitBlockExpr(const BlockExpr *B);
1984 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1985 void VisitCompoundStmt(const CompoundStmt *S);
1986 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1987 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1988 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1989 void VisitCXXNewExpr(const CXXNewExpr *E);
1990 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1991 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1992 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1993 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1994 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1995 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1996 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1997 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001998 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001999 void VisitDeclRefExpr(const DeclRefExpr *D);
2000 void VisitDeclStmt(const DeclStmt *S);
2001 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
2002 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
2003 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
2004 void VisitForStmt(const ForStmt *FS);
2005 void VisitGotoStmt(const GotoStmt *GS);
2006 void VisitIfStmt(const IfStmt *If);
2007 void VisitInitListExpr(const InitListExpr *IE);
2008 void VisitMemberExpr(const MemberExpr *M);
2009 void VisitOffsetOfExpr(const OffsetOfExpr *E);
2010 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2011 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
2012 void VisitOverloadExpr(const OverloadExpr *E);
2013 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2014 void VisitStmt(const Stmt *S);
2015 void VisitSwitchStmt(const SwitchStmt *S);
2016 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002017 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2018 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2019 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2020 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2021 void VisitVAArgExpr(const VAArgExpr *E);
2022 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2023 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2024 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2025 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002026 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002027 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002028 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002029 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002030 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002031 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002032 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002033 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002034 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002035 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002036 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002037 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002038 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
cchen47d60942019-12-05 13:43:48 -05002039 void VisitOMPParallelMasterDirective(const OMPParallelMasterDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002040 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002041 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002042 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002043 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002044 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002045 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002046 void
2047 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002048 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002049 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataevc112e942020-02-28 09:52:15 -05002050 void VisitOMPDepobjDirective(const OMPDepobjDirective *D);
Alexey Bataevfcba7c32020-03-20 07:03:01 -04002051 void VisitOMPScanDirective(const OMPScanDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002052 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002053 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002054 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002055 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002056 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002057 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002058 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002059 void
2060 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002061 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002062 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002063 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Alexey Bataev60e51c42019-10-10 20:13:02 +00002064 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002065 void
2066 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002067 void VisitOMPParallelMasterTaskLoopDirective(
2068 const OMPParallelMasterTaskLoopDirective *D);
Alexey Bataev14a388f2019-10-25 10:27:13 -04002069 void VisitOMPParallelMasterTaskLoopSimdDirective(
2070 const OMPParallelMasterTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002071 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002072 void VisitOMPDistributeParallelForDirective(
2073 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002074 void VisitOMPDistributeParallelForSimdDirective(
2075 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002076 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002077 void VisitOMPTargetParallelForSimdDirective(
2078 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002079 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002080 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002081 void VisitOMPTeamsDistributeSimdDirective(
2082 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002083 void VisitOMPTeamsDistributeParallelForSimdDirective(
2084 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002085 void VisitOMPTeamsDistributeParallelForDirective(
2086 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002087 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002088 void VisitOMPTargetTeamsDistributeDirective(
2089 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002090 void VisitOMPTargetTeamsDistributeParallelForDirective(
2091 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002092 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2093 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002094 void VisitOMPTargetTeamsDistributeSimdDirective(
2095 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002096
Guy Benyei11169dd2012-12-18 14:30:41 +00002097private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002098 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002099 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002100 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2101 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002102 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2103 void AddStmt(const Stmt *S);
2104 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002105 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002106 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002107 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002108};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002109} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002110
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002111void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002112 // 'S' should always be non-null, since it comes from the
2113 // statement we are visiting.
2114 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2115}
2116
2117void
2118EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2119 if (Qualifier)
2120 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2121}
2122
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002123void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002124 if (S)
2125 WL.push_back(StmtVisit(S, Parent));
2126}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002127void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002128 if (D)
2129 WL.push_back(DeclVisit(D, Parent, isFirst));
2130}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002131void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2132 unsigned NumTemplateArgs) {
2133 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002134}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002135void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002136 if (D)
2137 WL.push_back(MemberRefVisit(D, L, Parent));
2138}
2139void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2140 if (TI)
2141 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2142 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002143void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002144 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002145 for (const Stmt *SubStmt : S->children()) {
2146 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002147 }
2148 if (size == WL.size())
2149 return;
2150 // Now reverse the entries we just added. This will match the DFS
2151 // ordering performed by the worklist.
2152 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2153 std::reverse(I, E);
2154}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002155namespace {
2156class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2157 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002158 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002159 template <typename T>
2160 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002161public:
2162 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2163#define OPENMP_CLAUSE(Name, Class) \
2164 void Visit##Class(const Class *C);
2165#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002166 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002167 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002168};
2169
Alexey Bataev3392d762016-02-16 11:18:12 +00002170void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2171 const OMPClauseWithPreInit *C) {
2172 Visitor->AddStmt(C->getPreInitStmt());
2173}
2174
Alexey Bataev005248a2016-02-25 05:25:57 +00002175void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2176 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002177 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002178 Visitor->AddStmt(C->getPostUpdateExpr());
2179}
2180
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002181void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002182 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002183 Visitor->AddStmt(C->getCondition());
2184}
2185
Alexey Bataev3778b602014-07-17 07:32:53 +00002186void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2187 Visitor->AddStmt(C->getCondition());
2188}
2189
Alexey Bataev568a8332014-03-06 06:15:19 +00002190void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002191 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002192 Visitor->AddStmt(C->getNumThreads());
2193}
2194
Alexey Bataev62c87d22014-03-21 04:51:18 +00002195void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2196 Visitor->AddStmt(C->getSafelen());
2197}
2198
Alexey Bataev66b15b52015-08-21 11:14:16 +00002199void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2200 Visitor->AddStmt(C->getSimdlen());
2201}
2202
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002203void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2204 Visitor->AddStmt(C->getAllocator());
2205}
2206
Alexander Musman8bd31e62014-05-27 15:12:19 +00002207void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2208 Visitor->AddStmt(C->getNumForLoops());
2209}
2210
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002211void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002212
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002213void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2214
Alexey Bataev56dafe82014-06-20 07:16:17 +00002215void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002216 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002217 Visitor->AddStmt(C->getChunkSize());
2218}
2219
Alexey Bataev10e775f2015-07-30 11:36:16 +00002220void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2221 Visitor->AddStmt(C->getNumForLoops());
2222}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002223
Alexey Bataev0f0564b2020-03-17 09:17:42 -04002224void OMPClauseEnqueue::VisitOMPDetachClause(const OMPDetachClause *C) {
2225 Visitor->AddStmt(C->getEventHandler());
2226}
2227
Alexey Bataev236070f2014-06-20 11:19:47 +00002228void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2229
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002230void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2231
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002232void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2233
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002234void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2235
Alexey Bataevdea47612014-07-23 07:46:59 +00002236void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2237
Alexey Bataev67a4f222014-07-23 10:25:33 +00002238void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2239
Alexey Bataev459dec02014-07-24 06:46:57 +00002240void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2241
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002242void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2243
Alexey Bataevea9166b2020-02-06 16:30:23 -05002244void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
2245
Alexey Bataev04a830f2020-02-10 14:30:39 -05002246void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
2247
Alexey Bataev95598342020-02-10 15:49:05 -05002248void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {}
2249
Alexey Bataev9a8defc2020-02-11 11:10:43 -05002250void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {}
2251
Alexey Bataev346265e2015-09-25 10:37:12 +00002252void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2253
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002254void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2255
Alexey Bataevb825de12015-12-07 10:51:44 +00002256void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2257
Alexey Bataev375437a2020-03-02 14:21:20 -05002258void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *) {}
2259
Kelvin Li1408f912018-09-26 04:28:39 +00002260void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2261 const OMPUnifiedAddressClause *) {}
2262
Patrick Lyster4a370b92018-10-01 13:47:43 +00002263void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2264 const OMPUnifiedSharedMemoryClause *) {}
2265
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002266void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2267 const OMPReverseOffloadClause *) {}
2268
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002269void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2270 const OMPDynamicAllocatorsClause *) {}
2271
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002272void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2273 const OMPAtomicDefaultMemOrderClause *) {}
2274
Michael Wonge710d542015-08-07 16:16:36 +00002275void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2276 Visitor->AddStmt(C->getDevice());
2277}
2278
Kelvin Li099bb8c2015-11-24 20:50:12 +00002279void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002280 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002281 Visitor->AddStmt(C->getNumTeams());
2282}
2283
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002284void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002285 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002286 Visitor->AddStmt(C->getThreadLimit());
2287}
2288
Alexey Bataeva0569352015-12-01 10:17:31 +00002289void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2290 Visitor->AddStmt(C->getPriority());
2291}
2292
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002293void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2294 Visitor->AddStmt(C->getGrainsize());
2295}
2296
Alexey Bataev382967a2015-12-08 12:06:20 +00002297void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2298 Visitor->AddStmt(C->getNumTasks());
2299}
2300
Alexey Bataev28c75412015-12-15 08:19:24 +00002301void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2302 Visitor->AddStmt(C->getHint());
2303}
2304
Alexey Bataev756c1962013-09-24 03:17:45 +00002305template<typename T>
2306void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002307 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002308 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002309 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002310}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002311
Alexey Bataev06dea732020-03-20 09:41:22 -04002312void OMPClauseEnqueue::VisitOMPInclusiveClause(const OMPInclusiveClause *C) {
2313 VisitOMPClauseList(C);
2314}
Alexey Bataev63828a32020-03-23 10:41:08 -04002315void OMPClauseEnqueue::VisitOMPExclusiveClause(const OMPExclusiveClause *C) {
2316 VisitOMPClauseList(C);
2317}
Alexey Bataeve04483e2019-03-27 14:14:31 +00002318void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2319 VisitOMPClauseList(C);
2320 Visitor->AddStmt(C->getAllocator());
2321}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002322void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002323 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002324 for (const auto *E : C->private_copies()) {
2325 Visitor->AddStmt(E);
2326 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002327}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002328void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2329 const OMPFirstprivateClause *C) {
2330 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002331 VisitOMPClauseWithPreInit(C);
2332 for (const auto *E : C->private_copies()) {
2333 Visitor->AddStmt(E);
2334 }
2335 for (const auto *E : C->inits()) {
2336 Visitor->AddStmt(E);
2337 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002338}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002339void OMPClauseEnqueue::VisitOMPLastprivateClause(
2340 const OMPLastprivateClause *C) {
2341 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002342 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002343 for (auto *E : C->private_copies()) {
2344 Visitor->AddStmt(E);
2345 }
2346 for (auto *E : C->source_exprs()) {
2347 Visitor->AddStmt(E);
2348 }
2349 for (auto *E : C->destination_exprs()) {
2350 Visitor->AddStmt(E);
2351 }
2352 for (auto *E : C->assignment_ops()) {
2353 Visitor->AddStmt(E);
2354 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002355}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002356void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002357 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002358}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002359void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2360 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002361 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002362 for (auto *E : C->privates()) {
2363 Visitor->AddStmt(E);
2364 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002365 for (auto *E : C->lhs_exprs()) {
2366 Visitor->AddStmt(E);
2367 }
2368 for (auto *E : C->rhs_exprs()) {
2369 Visitor->AddStmt(E);
2370 }
2371 for (auto *E : C->reduction_ops()) {
2372 Visitor->AddStmt(E);
2373 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002374}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002375void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2376 const OMPTaskReductionClause *C) {
2377 VisitOMPClauseList(C);
2378 VisitOMPClauseWithPostUpdate(C);
2379 for (auto *E : C->privates()) {
2380 Visitor->AddStmt(E);
2381 }
2382 for (auto *E : C->lhs_exprs()) {
2383 Visitor->AddStmt(E);
2384 }
2385 for (auto *E : C->rhs_exprs()) {
2386 Visitor->AddStmt(E);
2387 }
2388 for (auto *E : C->reduction_ops()) {
2389 Visitor->AddStmt(E);
2390 }
2391}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002392void OMPClauseEnqueue::VisitOMPInReductionClause(
2393 const OMPInReductionClause *C) {
2394 VisitOMPClauseList(C);
2395 VisitOMPClauseWithPostUpdate(C);
2396 for (auto *E : C->privates()) {
2397 Visitor->AddStmt(E);
2398 }
2399 for (auto *E : C->lhs_exprs()) {
2400 Visitor->AddStmt(E);
2401 }
2402 for (auto *E : C->rhs_exprs()) {
2403 Visitor->AddStmt(E);
2404 }
2405 for (auto *E : C->reduction_ops()) {
2406 Visitor->AddStmt(E);
2407 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002408 for (auto *E : C->taskgroup_descriptors())
2409 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002410}
Alexander Musman8dba6642014-04-22 13:09:42 +00002411void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2412 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002413 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002414 for (const auto *E : C->privates()) {
2415 Visitor->AddStmt(E);
2416 }
Alexander Musman3276a272015-03-21 10:12:56 +00002417 for (const auto *E : C->inits()) {
2418 Visitor->AddStmt(E);
2419 }
2420 for (const auto *E : C->updates()) {
2421 Visitor->AddStmt(E);
2422 }
2423 for (const auto *E : C->finals()) {
2424 Visitor->AddStmt(E);
2425 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002426 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002427 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002428}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002429void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2430 VisitOMPClauseList(C);
2431 Visitor->AddStmt(C->getAlignment());
2432}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002433void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2434 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002435 for (auto *E : C->source_exprs()) {
2436 Visitor->AddStmt(E);
2437 }
2438 for (auto *E : C->destination_exprs()) {
2439 Visitor->AddStmt(E);
2440 }
2441 for (auto *E : C->assignment_ops()) {
2442 Visitor->AddStmt(E);
2443 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002444}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002445void
2446OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2447 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002448 for (auto *E : C->source_exprs()) {
2449 Visitor->AddStmt(E);
2450 }
2451 for (auto *E : C->destination_exprs()) {
2452 Visitor->AddStmt(E);
2453 }
2454 for (auto *E : C->assignment_ops()) {
2455 Visitor->AddStmt(E);
2456 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002457}
Alexey Bataev6125da92014-07-21 11:26:11 +00002458void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2459 VisitOMPClauseList(C);
2460}
Alexey Bataevc112e942020-02-28 09:52:15 -05002461void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) {
2462 Visitor->AddStmt(C->getDepobj());
2463}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002464void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2465 VisitOMPClauseList(C);
2466}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002467void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2468 VisitOMPClauseList(C);
2469}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002470void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2471 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002472 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002473 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002474}
Alexey Bataev3392d762016-02-16 11:18:12 +00002475void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2476 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002477void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2478 VisitOMPClauseList(C);
2479}
Samuel Antaoec172c62016-05-26 17:49:04 +00002480void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2481 VisitOMPClauseList(C);
2482}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002483void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2484 VisitOMPClauseList(C);
2485}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002486void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2487 VisitOMPClauseList(C);
2488}
Alexey Bataevb6e70842019-12-16 15:54:17 -05002489void OMPClauseEnqueue::VisitOMPNontemporalClause(
2490 const OMPNontemporalClause *C) {
2491 VisitOMPClauseList(C);
Alexey Bataev0860db92019-12-19 10:01:10 -05002492 for (const auto *E : C->private_refs())
2493 Visitor->AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05002494}
Alexey Bataevcb8e6912020-01-31 16:09:26 -05002495void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002496}
Alexey Bataev756c1962013-09-24 03:17:45 +00002497
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002498void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2499 unsigned size = WL.size();
2500 OMPClauseEnqueue Visitor(this);
2501 Visitor.Visit(S);
2502 if (size == WL.size())
2503 return;
2504 // Now reverse the entries we just added. This will match the DFS
2505 // ordering performed by the worklist.
2506 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2507 std::reverse(I, E);
2508}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002509void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2511}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002512void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 AddDecl(B->getBlockDecl());
2514}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002515void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 EnqueueChildren(E);
2517 AddTypeLoc(E->getTypeSourceInfo());
2518}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002519void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002520 for (auto &I : llvm::reverse(S->body()))
2521 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002522}
2523void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002524VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 AddStmt(S->getSubStmt());
2526 AddDeclarationNameInfo(S);
2527 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2528 AddNestedNameSpecifierLoc(QualifierLoc);
2529}
2530
2531void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002532VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002533 if (E->hasExplicitTemplateArgs())
2534 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 AddDeclarationNameInfo(E);
2536 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2537 AddNestedNameSpecifierLoc(QualifierLoc);
2538 if (!E->isImplicitAccess())
2539 AddStmt(E->getBase());
2540}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002541void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 // Enqueue the initializer , if any.
2543 AddStmt(E->getInitializer());
2544 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002545 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 // Enqueue the allocated type.
2547 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2548 // Enqueue the placement arguments.
2549 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2550 AddStmt(E->getPlacementArg(I-1));
2551}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002552void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2554 AddStmt(CE->getArg(I-1));
2555 AddStmt(CE->getCallee());
2556 AddStmt(CE->getArg(0));
2557}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002558void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2559 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 // Visit the name of the type being destroyed.
2561 AddTypeLoc(E->getDestroyedTypeInfo());
2562 // Visit the scope type that looks disturbingly like the nested-name-specifier
2563 // but isn't.
2564 AddTypeLoc(E->getScopeTypeInfo());
2565 // Visit the nested-name-specifier.
2566 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2567 AddNestedNameSpecifierLoc(QualifierLoc);
2568 // Visit base expression.
2569 AddStmt(E->getBase());
2570}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002571void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2572 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 AddTypeLoc(E->getTypeSourceInfo());
2574}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002575void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2576 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 EnqueueChildren(E);
2578 AddTypeLoc(E->getTypeSourceInfo());
2579}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002580void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 EnqueueChildren(E);
2582 if (E->isTypeOperand())
2583 AddTypeLoc(E->getTypeOperandSourceInfo());
2584}
2585
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002586void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2587 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 EnqueueChildren(E);
2589 AddTypeLoc(E->getTypeSourceInfo());
2590}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002591void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 EnqueueChildren(E);
2593 if (E->isTypeOperand())
2594 AddTypeLoc(E->getTypeOperandSourceInfo());
2595}
2596
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002597void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 EnqueueChildren(S);
2599 AddDecl(S->getExceptionDecl());
2600}
2601
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002602void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002603 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002604 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002605 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002606}
2607
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002608void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002609 if (DR->hasExplicitTemplateArgs())
2610 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 WL.push_back(DeclRefExprParts(DR, Parent));
2612}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002613void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2614 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002615 if (E->hasExplicitTemplateArgs())
2616 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 AddDeclarationNameInfo(E);
2618 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2619}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002620void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 unsigned size = WL.size();
2622 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002623 for (const auto *D : S->decls()) {
2624 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 isFirst = false;
2626 }
2627 if (size == WL.size())
2628 return;
2629 // Now reverse the entries we just added. This will match the DFS
2630 // ordering performed by the worklist.
2631 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2632 std::reverse(I, E);
2633}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002634void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002636 for (const DesignatedInitExpr::Designator &D :
2637 llvm::reverse(E->designators())) {
2638 if (D.isFieldDesignator()) {
2639 if (FieldDecl *Field = D.getField())
2640 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 continue;
2642 }
David Majnemerf7e36092016-06-23 00:15:04 +00002643 if (D.isArrayDesignator()) {
2644 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 continue;
2646 }
David Majnemerf7e36092016-06-23 00:15:04 +00002647 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2648 AddStmt(E->getArrayRangeEnd(D));
2649 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 }
2651}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002652void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 EnqueueChildren(E);
2654 AddTypeLoc(E->getTypeInfoAsWritten());
2655}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002656void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 AddStmt(FS->getBody());
2658 AddStmt(FS->getInc());
2659 AddStmt(FS->getCond());
2660 AddDecl(FS->getConditionVariable());
2661 AddStmt(FS->getInit());
2662}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002663void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2665}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002666void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 AddStmt(If->getElse());
2668 AddStmt(If->getThen());
2669 AddStmt(If->getCond());
2670 AddDecl(If->getConditionVariable());
2671}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002672void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 // We care about the syntactic form of the initializer list, only.
2674 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2675 IE = Syntactic;
2676 EnqueueChildren(IE);
2677}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002678void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 WL.push_back(MemberExprParts(M, Parent));
2680
2681 // If the base of the member access expression is an implicit 'this', don't
2682 // visit it.
2683 // FIXME: If we ever want to show these implicit accesses, this will be
2684 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002685 if (M->isImplicitAccess())
2686 return;
2687
2688 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002689 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002690 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2691 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2692 if (FD->isAnonymousStructOrUnion()) {
2693 AddStmt(SubME->getBase());
2694 return;
2695 }
2696 }
2697 }
2698
2699 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002700}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002701void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 AddTypeLoc(E->getEncodedTypeSourceInfo());
2703}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002704void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 EnqueueChildren(M);
2706 AddTypeLoc(M->getClassReceiverTypeInfo());
2707}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002708void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 // Visit the components of the offsetof expression.
2710 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 const OffsetOfNode &Node = E->getComponent(I-1);
2712 switch (Node.getKind()) {
2713 case OffsetOfNode::Array:
2714 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2715 break;
2716 case OffsetOfNode::Field:
2717 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2718 break;
2719 case OffsetOfNode::Identifier:
2720 case OffsetOfNode::Base:
2721 continue;
2722 }
2723 }
2724 // Visit the type into which we're computing the offset.
2725 AddTypeLoc(E->getTypeSourceInfo());
2726}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002727void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002728 if (E->hasExplicitTemplateArgs())
2729 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 WL.push_back(OverloadExprParts(E, Parent));
2731}
2732void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002733 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 EnqueueChildren(E);
2735 if (E->isArgumentType())
2736 AddTypeLoc(E->getArgumentTypeInfo());
2737}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002738void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 EnqueueChildren(S);
2740}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002741void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 AddStmt(S->getBody());
2743 AddStmt(S->getCond());
2744 AddDecl(S->getConditionVariable());
2745}
2746
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002747void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 AddStmt(W->getBody());
2749 AddStmt(W->getCond());
2750 AddDecl(W->getConditionVariable());
2751}
2752
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002753void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 for (unsigned I = E->getNumArgs(); I > 0; --I)
2755 AddTypeLoc(E->getArg(I-1));
2756}
2757
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002758void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 AddTypeLoc(E->getQueriedTypeSourceInfo());
2760}
2761
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002762void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 EnqueueChildren(E);
2764}
2765
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002766void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 VisitOverloadExpr(U);
2768 if (!U->isImplicitAccess())
2769 AddStmt(U->getBase());
2770}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002771void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 AddStmt(E->getSubExpr());
2773 AddTypeLoc(E->getWrittenTypeInfo());
2774}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002775void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 WL.push_back(SizeOfPackExprParts(E, Parent));
2777}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002778void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002779 // If the opaque value has a source expression, just transparently
2780 // visit that. This is useful for (e.g.) pseudo-object expressions.
2781 if (Expr *SourceExpr = E->getSourceExpr())
2782 return Visit(SourceExpr);
2783}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002784void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002785 AddStmt(E->getBody());
2786 WL.push_back(LambdaExprParts(E, Parent));
2787}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002788void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 // Treat the expression like its syntactic form.
2790 Visit(E->getSyntacticForm());
2791}
2792
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002793void EnqueueVisitor::VisitOMPExecutableDirective(
2794 const OMPExecutableDirective *D) {
2795 EnqueueChildren(D);
2796 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2797 E = D->clauses().end();
2798 I != E; ++I)
2799 EnqueueChildren(*I);
2800}
2801
Alexander Musman3aaab662014-08-19 11:27:13 +00002802void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2803 VisitOMPExecutableDirective(D);
2804}
2805
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002806void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2807 VisitOMPExecutableDirective(D);
2808}
2809
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002810void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002811 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002812}
2813
Alexey Bataevf29276e2014-06-18 04:14:57 +00002814void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002815 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002816}
2817
Alexander Musmanf82886e2014-09-18 05:12:34 +00002818void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2819 VisitOMPLoopDirective(D);
2820}
2821
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002822void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2823 VisitOMPExecutableDirective(D);
2824}
2825
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002826void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2827 VisitOMPExecutableDirective(D);
2828}
2829
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002830void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2831 VisitOMPExecutableDirective(D);
2832}
2833
Alexander Musman80c22892014-07-17 08:54:58 +00002834void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2835 VisitOMPExecutableDirective(D);
2836}
2837
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002838void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2839 VisitOMPExecutableDirective(D);
2840 AddDeclarationNameInfo(D);
2841}
2842
Alexey Bataev4acb8592014-07-07 13:01:15 +00002843void
2844EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002845 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002846}
2847
Alexander Musmane4e893b2014-09-23 09:33:00 +00002848void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2849 const OMPParallelForSimdDirective *D) {
2850 VisitOMPLoopDirective(D);
2851}
2852
cchen47d60942019-12-05 13:43:48 -05002853void EnqueueVisitor::VisitOMPParallelMasterDirective(
2854 const OMPParallelMasterDirective *D) {
2855 VisitOMPExecutableDirective(D);
2856}
2857
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002858void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2859 const OMPParallelSectionsDirective *D) {
2860 VisitOMPExecutableDirective(D);
2861}
2862
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002863void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2864 VisitOMPExecutableDirective(D);
2865}
2866
Alexey Bataev68446b72014-07-18 07:47:19 +00002867void
2868EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2869 VisitOMPExecutableDirective(D);
2870}
2871
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002872void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2873 VisitOMPExecutableDirective(D);
2874}
2875
Alexey Bataev2df347a2014-07-18 10:17:07 +00002876void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2877 VisitOMPExecutableDirective(D);
2878}
2879
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002880void EnqueueVisitor::VisitOMPTaskgroupDirective(
2881 const OMPTaskgroupDirective *D) {
2882 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002883 if (const Expr *E = D->getReductionRef())
2884 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002885}
2886
Alexey Bataev6125da92014-07-21 11:26:11 +00002887void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2888 VisitOMPExecutableDirective(D);
2889}
2890
Alexey Bataevc112e942020-02-28 09:52:15 -05002891void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) {
2892 VisitOMPExecutableDirective(D);
2893}
2894
Alexey Bataevfcba7c32020-03-20 07:03:01 -04002895void EnqueueVisitor::VisitOMPScanDirective(const OMPScanDirective *D) {
2896 VisitOMPExecutableDirective(D);
2897}
2898
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002899void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2900 VisitOMPExecutableDirective(D);
2901}
2902
Alexey Bataev0162e452014-07-22 10:10:35 +00002903void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2904 VisitOMPExecutableDirective(D);
2905}
2906
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002907void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2908 VisitOMPExecutableDirective(D);
2909}
2910
Alexey Bataevc112e942020-02-28 09:52:15 -05002911void EnqueueVisitor::VisitOMPTargetDataDirective(
2912 const OMPTargetDataDirective *D) {
Michael Wong65f367f2015-07-21 13:44:28 +00002913 VisitOMPExecutableDirective(D);
2914}
2915
Samuel Antaodf67fc42016-01-19 19:15:56 +00002916void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2917 const OMPTargetEnterDataDirective *D) {
2918 VisitOMPExecutableDirective(D);
2919}
2920
Samuel Antao72590762016-01-19 20:04:50 +00002921void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2922 const OMPTargetExitDataDirective *D) {
2923 VisitOMPExecutableDirective(D);
2924}
2925
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002926void EnqueueVisitor::VisitOMPTargetParallelDirective(
2927 const OMPTargetParallelDirective *D) {
2928 VisitOMPExecutableDirective(D);
2929}
2930
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002931void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2932 const OMPTargetParallelForDirective *D) {
2933 VisitOMPLoopDirective(D);
2934}
2935
Alexey Bataev13314bf2014-10-09 04:18:56 +00002936void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2937 VisitOMPExecutableDirective(D);
2938}
2939
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002940void EnqueueVisitor::VisitOMPCancellationPointDirective(
2941 const OMPCancellationPointDirective *D) {
2942 VisitOMPExecutableDirective(D);
2943}
2944
Alexey Bataev80909872015-07-02 11:25:17 +00002945void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2946 VisitOMPExecutableDirective(D);
2947}
2948
Alexey Bataev49f6e782015-12-01 04:18:41 +00002949void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2950 VisitOMPLoopDirective(D);
2951}
2952
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002953void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2954 const OMPTaskLoopSimdDirective *D) {
2955 VisitOMPLoopDirective(D);
2956}
2957
Alexey Bataev60e51c42019-10-10 20:13:02 +00002958void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2959 const OMPMasterTaskLoopDirective *D) {
2960 VisitOMPLoopDirective(D);
2961}
2962
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002963void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2964 const OMPMasterTaskLoopSimdDirective *D) {
2965 VisitOMPLoopDirective(D);
2966}
2967
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002968void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2969 const OMPParallelMasterTaskLoopDirective *D) {
2970 VisitOMPLoopDirective(D);
2971}
2972
Alexey Bataev14a388f2019-10-25 10:27:13 -04002973void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
2974 const OMPParallelMasterTaskLoopSimdDirective *D) {
2975 VisitOMPLoopDirective(D);
2976}
2977
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002978void EnqueueVisitor::VisitOMPDistributeDirective(
2979 const OMPDistributeDirective *D) {
2980 VisitOMPLoopDirective(D);
2981}
2982
Carlo Bertolli9925f152016-06-27 14:55:37 +00002983void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2984 const OMPDistributeParallelForDirective *D) {
2985 VisitOMPLoopDirective(D);
2986}
2987
Kelvin Li4a39add2016-07-05 05:00:15 +00002988void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2989 const OMPDistributeParallelForSimdDirective *D) {
2990 VisitOMPLoopDirective(D);
2991}
2992
Kelvin Li787f3fc2016-07-06 04:45:38 +00002993void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2994 const OMPDistributeSimdDirective *D) {
2995 VisitOMPLoopDirective(D);
2996}
2997
Kelvin Lia579b912016-07-14 02:54:56 +00002998void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2999 const OMPTargetParallelForSimdDirective *D) {
3000 VisitOMPLoopDirective(D);
3001}
3002
Kelvin Li986330c2016-07-20 22:57:10 +00003003void EnqueueVisitor::VisitOMPTargetSimdDirective(
3004 const OMPTargetSimdDirective *D) {
3005 VisitOMPLoopDirective(D);
3006}
3007
Kelvin Li02532872016-08-05 14:37:37 +00003008void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
3009 const OMPTeamsDistributeDirective *D) {
3010 VisitOMPLoopDirective(D);
3011}
3012
Kelvin Li4e325f72016-10-25 12:50:55 +00003013void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
3014 const OMPTeamsDistributeSimdDirective *D) {
3015 VisitOMPLoopDirective(D);
3016}
3017
Kelvin Li579e41c2016-11-30 23:51:03 +00003018void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
3019 const OMPTeamsDistributeParallelForSimdDirective *D) {
3020 VisitOMPLoopDirective(D);
3021}
3022
Kelvin Li7ade93f2016-12-09 03:24:30 +00003023void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
3024 const OMPTeamsDistributeParallelForDirective *D) {
3025 VisitOMPLoopDirective(D);
3026}
3027
Kelvin Libf594a52016-12-17 05:48:59 +00003028void EnqueueVisitor::VisitOMPTargetTeamsDirective(
3029 const OMPTargetTeamsDirective *D) {
3030 VisitOMPExecutableDirective(D);
3031}
3032
Kelvin Li83c451e2016-12-25 04:52:54 +00003033void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3034 const OMPTargetTeamsDistributeDirective *D) {
3035 VisitOMPLoopDirective(D);
3036}
3037
Kelvin Li80e8f562016-12-29 22:16:30 +00003038void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3039 const OMPTargetTeamsDistributeParallelForDirective *D) {
3040 VisitOMPLoopDirective(D);
3041}
3042
Kelvin Li1851df52017-01-03 05:23:48 +00003043void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3044 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3045 VisitOMPLoopDirective(D);
3046}
3047
Kelvin Lida681182017-01-10 18:08:18 +00003048void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3049 const OMPTargetTeamsDistributeSimdDirective *D) {
3050 VisitOMPLoopDirective(D);
3051}
3052
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003053void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
3055}
3056
3057bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3058 if (RegionOfInterest.isValid()) {
3059 SourceRange Range = getRawCursorExtent(C);
3060 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3061 return false;
3062 }
3063 return true;
3064}
3065
3066bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3067 while (!WL.empty()) {
3068 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003069 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003070
3071 // Set the Parent field, then back to its old value once we're done.
3072 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3073
3074 switch (LI.getKind()) {
3075 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003076 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 if (!D)
3078 continue;
3079
3080 // For now, perform default visitation for Decls.
3081 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3082 cast<DeclVisit>(&LI)->isFirst())))
3083 return true;
3084
3085 continue;
3086 }
3087 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003088 for (const TemplateArgumentLoc &Arg :
3089 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3090 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 return true;
3092 }
3093 continue;
3094 }
3095 case VisitorJob::TypeLocVisitKind: {
3096 // Perform default visitation for TypeLocs.
3097 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3098 return true;
3099 continue;
3100 }
3101 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003102 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 if (LabelStmt *stmt = LS->getStmt()) {
3104 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3105 TU))) {
3106 return true;
3107 }
3108 }
3109 continue;
3110 }
3111
3112 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3113 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3114 if (VisitNestedNameSpecifierLoc(V->get()))
3115 return true;
3116 continue;
3117 }
3118
3119 case VisitorJob::DeclarationNameInfoVisitKind: {
3120 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3121 ->get()))
3122 return true;
3123 continue;
3124 }
3125 case VisitorJob::MemberRefVisitKind: {
3126 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3127 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3128 return true;
3129 continue;
3130 }
3131 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003132 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 if (!S)
3134 continue;
3135
3136 // Update the current cursor.
3137 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3138 if (!IsInRegionOfInterest(Cursor))
3139 continue;
3140 switch (Visitor(Cursor, Parent, ClientData)) {
3141 case CXChildVisit_Break: return true;
3142 case CXChildVisit_Continue: break;
3143 case CXChildVisit_Recurse:
3144 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003145 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 EnqueueWorkList(WL, S);
3147 break;
3148 }
3149 continue;
3150 }
3151 case VisitorJob::MemberExprPartsKind: {
3152 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003153 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003154
3155 // Visit the nested-name-specifier
3156 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3157 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3158 return true;
3159
3160 // Visit the declaration name.
3161 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3162 return true;
3163
3164 // Visit the explicitly-specified template arguments, if any.
3165 if (M->hasExplicitTemplateArgs()) {
3166 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3167 *ArgEnd = Arg + M->getNumTemplateArgs();
3168 Arg != ArgEnd; ++Arg) {
3169 if (VisitTemplateArgumentLoc(*Arg))
3170 return true;
3171 }
3172 }
3173 continue;
3174 }
3175 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003176 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 // Visit nested-name-specifier, if present.
3178 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3179 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3180 return true;
3181 // Visit declaration name.
3182 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3183 return true;
3184 continue;
3185 }
3186 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003187 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003188 // Visit the nested-name-specifier.
3189 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3190 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3191 return true;
3192 // Visit the declaration name.
3193 if (VisitDeclarationNameInfo(O->getNameInfo()))
3194 return true;
3195 // Visit the overloaded declaration reference.
3196 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3197 return true;
3198 continue;
3199 }
3200 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003201 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 NamedDecl *Pack = E->getPack();
3203 if (isa<TemplateTypeParmDecl>(Pack)) {
3204 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3205 E->getPackLoc(), TU)))
3206 return true;
3207
3208 continue;
3209 }
3210
3211 if (isa<TemplateTemplateParmDecl>(Pack)) {
3212 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3213 E->getPackLoc(), TU)))
3214 return true;
3215
3216 continue;
3217 }
3218
3219 // Non-type template parameter packs and function parameter packs are
3220 // treated like DeclRefExpr cursors.
3221 continue;
3222 }
3223
3224 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003225 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003226 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3228 CEnd = E->explicit_capture_end();
3229 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003230 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003232
Guy Benyei11169dd2012-12-18 14:30:41 +00003233 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3234 C->getLocation(),
3235 TU)))
3236 return true;
3237 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003238 // Visit init captures
3239 for (auto InitExpr : E->capture_inits()) {
3240 if (Visit(InitExpr))
3241 return true;
3242 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003243
Haojian Wuef87c262018-12-18 15:29:12 +00003244 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003246 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3247 if (E->hasExplicitParameters()) {
3248 // Visit parameters.
3249 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3250 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003251 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003252 }
3253 if (E->hasExplicitResultType()) {
3254 // Visit result type.
3255 if (Visit(Proto.getReturnLoc()))
3256 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 }
3258 }
3259 break;
3260 }
3261
3262 case VisitorJob::PostChildrenVisitKind:
3263 if (PostChildrenVisitor(Parent, ClientData))
3264 return true;
3265 break;
3266 }
3267 }
3268 return false;
3269}
3270
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003271bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003272 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003273 if (!WorkListFreeList.empty()) {
3274 WL = WorkListFreeList.back();
3275 WL->clear();
3276 WorkListFreeList.pop_back();
3277 }
3278 else {
3279 WL = new VisitorWorkList();
3280 WorkListCache.push_back(WL);
3281 }
3282 EnqueueWorkList(*WL, S);
3283 bool result = RunVisitorWorkList(*WL);
3284 WorkListFreeList.push_back(WL);
3285 return result;
3286}
3287
3288namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003289typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003290RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3291 const DeclarationNameInfo &NI, SourceRange QLoc,
3292 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3294 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3295 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3296
3297 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3298
3299 RefNamePieces Pieces;
3300
3301 if (WantQualifier && QLoc.isValid())
3302 Pieces.push_back(QLoc);
3303
3304 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3305 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003306
3307 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3308 Pieces.push_back(*TemplateArgsLoc);
3309
Guy Benyei11169dd2012-12-18 14:30:41 +00003310 if (Kind == DeclarationName::CXXOperatorName) {
3311 Pieces.push_back(SourceLocation::getFromRawEncoding(
3312 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3313 Pieces.push_back(SourceLocation::getFromRawEncoding(
3314 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3315 }
3316
3317 if (WantSinglePiece) {
3318 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3319 Pieces.clear();
3320 Pieces.push_back(R);
3321 }
3322
3323 return Pieces;
3324}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003325}
Guy Benyei11169dd2012-12-18 14:30:41 +00003326
3327//===----------------------------------------------------------------------===//
3328// Misc. API hooks.
3329//===----------------------------------------------------------------------===//
3330
Chandler Carruth66660742014-06-27 16:37:27 +00003331namespace {
3332struct RegisterFatalErrorHandler {
3333 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003334 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003335 }
3336};
3337}
3338
3339static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3340
Guy Benyei11169dd2012-12-18 14:30:41 +00003341CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3342 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 // We use crash recovery to make some of our APIs more reliable, implicitly
3344 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003345 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3346 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003347
Chandler Carruth66660742014-06-27 16:37:27 +00003348 // Look through the managed static to trigger construction of the managed
3349 // static which registers our fatal error handler. This ensures it is only
3350 // registered once.
3351 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003352
Adrian Prantlbc068582015-07-08 01:00:30 +00003353 // Initialize targets for clang module support.
3354 llvm::InitializeAllTargets();
3355 llvm::InitializeAllTargetMCs();
3356 llvm::InitializeAllAsmPrinters();
3357 llvm::InitializeAllAsmParsers();
3358
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003359 CIndexer *CIdxr = new CIndexer();
3360
Guy Benyei11169dd2012-12-18 14:30:41 +00003361 if (excludeDeclarationsFromPCH)
3362 CIdxr->setOnlyLocalDecls();
3363 if (displayDiagnostics)
3364 CIdxr->setDisplayDiagnostics();
3365
3366 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3367 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3368 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3369 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3370 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3371 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3372
3373 return CIdxr;
3374}
3375
3376void clang_disposeIndex(CXIndex CIdx) {
3377 if (CIdx)
3378 delete static_cast<CIndexer *>(CIdx);
3379}
3380
3381void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3382 if (CIdx)
3383 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3384}
3385
3386unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3387 if (CIdx)
3388 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3389 return 0;
3390}
3391
Alex Lorenz08615792017-12-04 21:56:36 +00003392void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3393 const char *Path) {
3394 if (CIdx)
3395 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3396}
3397
Guy Benyei11169dd2012-12-18 14:30:41 +00003398void clang_toggleCrashRecovery(unsigned isEnabled) {
3399 if (isEnabled)
3400 llvm::CrashRecoveryContext::Enable();
3401 else
3402 llvm::CrashRecoveryContext::Disable();
3403}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003404
Guy Benyei11169dd2012-12-18 14:30:41 +00003405CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3406 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003407 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003408 enum CXErrorCode Result =
3409 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003410 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003411 assert((TU && Result == CXError_Success) ||
3412 (!TU && Result != CXError_Success));
3413 return TU;
3414}
3415
3416enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3417 const char *ast_filename,
3418 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003419 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003420 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003421
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003422 if (!CIdx || !ast_filename || !out_TU)
3423 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003424
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003425 LOG_FUNC_SECTION {
3426 *Log << ast_filename;
3427 }
3428
Guy Benyei11169dd2012-12-18 14:30:41 +00003429 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3430 FileSystemOptions FileSystemOpts;
3431
Justin Bognerd512c1e2014-10-15 00:33:06 +00003432 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3433 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003434 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003435 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3436 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003437 FileSystemOpts, /*UseDebugInfo=*/false,
3438 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003439 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003440 /*AllowPCHWithCompilerErrors=*/true,
3441 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003442 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003443 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003444}
3445
3446unsigned clang_defaultEditingTranslationUnitOptions() {
3447 return CXTranslationUnit_PrecompiledPreamble |
3448 CXTranslationUnit_CacheCompletionResults;
3449}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003450
Guy Benyei11169dd2012-12-18 14:30:41 +00003451CXTranslationUnit
3452clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3453 const char *source_filename,
3454 int num_command_line_args,
3455 const char * const *command_line_args,
3456 unsigned num_unsaved_files,
3457 struct CXUnsavedFile *unsaved_files) {
3458 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3459 return clang_parseTranslationUnit(CIdx, source_filename,
3460 command_line_args, num_command_line_args,
3461 unsaved_files, num_unsaved_files,
3462 Options);
3463}
3464
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003465static CXErrorCode
3466clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3467 const char *const *command_line_args,
3468 int num_command_line_args,
3469 ArrayRef<CXUnsavedFile> unsaved_files,
3470 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003471 // Set up the initial return values.
3472 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003473 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003474
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003475 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003476 if (!CIdx || !out_TU)
3477 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003478
Guy Benyei11169dd2012-12-18 14:30:41 +00003479 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3480
3481 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3482 setThreadBackgroundPriority();
3483
3484 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003485 bool CreatePreambleOnFirstParse =
3486 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 // FIXME: Add a flag for modules.
3488 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003489 = (options & (CXTranslationUnit_Incomplete |
3490 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003491 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003492 = options & CXTranslationUnit_CacheCompletionResults;
3493 bool IncludeBriefCommentsInCodeCompletion
3494 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003495 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3496 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003497 bool RetainExcludedCB = options &
3498 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003499 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3500 if (options & CXTranslationUnit_SkipFunctionBodies) {
3501 SkipFunctionBodies =
3502 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3503 ? SkipFunctionBodiesScope::Preamble
3504 : SkipFunctionBodiesScope::PreambleAndMainFile;
3505 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003506
3507 // Configure the diagnostics.
3508 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003509 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003510
Manuel Klimek016c0242016-03-01 10:56:19 +00003511 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003512 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003513
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003514 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3515 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3516 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3517
Guy Benyei11169dd2012-12-18 14:30:41 +00003518 // Recover resources if we crash before exiting this function.
3519 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3520 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003521 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003522
Ahmed Charlesb8984322014-03-07 20:03:18 +00003523 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3524 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003525
3526 // Recover resources if we crash before exiting this function.
3527 llvm::CrashRecoveryContextCleanupRegistrar<
3528 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3529
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003530 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003531 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003532 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003533 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003534 }
3535
Ahmed Charlesb8984322014-03-07 20:03:18 +00003536 std::unique_ptr<std::vector<const char *>> Args(
3537 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003538
3539 // Recover resources if we crash before exiting this method.
3540 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3541 ArgsCleanup(Args.get());
3542
3543 // Since the Clang C library is primarily used by batch tools dealing with
3544 // (often very broken) source code, where spell-checking can have a
3545 // significant negative impact on performance (particularly when
3546 // precompiled headers are involved), we disable it by default.
3547 // Only do this if we haven't found a spell-checking-related argument.
3548 bool FoundSpellCheckingArgument = false;
3549 for (int I = 0; I != num_command_line_args; ++I) {
3550 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3551 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3552 FoundSpellCheckingArgument = true;
3553 break;
3554 }
3555 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003556 Args->insert(Args->end(), command_line_args,
3557 command_line_args + num_command_line_args);
3558
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003559 if (!FoundSpellCheckingArgument)
3560 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3561
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 // The 'source_filename' argument is optional. If the caller does not
3563 // specify it then it is assumed that the source file is specified
3564 // in the actual argument list.
3565 // Put the source file after command_line_args otherwise if '-x' flag is
3566 // present it will be unused.
3567 if (source_filename)
3568 Args->push_back(source_filename);
3569
3570 // Do we need the detailed preprocessing record?
3571 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3572 Args->push_back("-Xclang");
3573 Args->push_back("-detailed-preprocessing-record");
3574 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003575
3576 // Suppress any editor placeholder diagnostics.
3577 Args->push_back("-fallow-editor-placeholders");
3578
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003580 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003581 // Unless the user specified that they want the preamble on the first parse
3582 // set it up to be created on the first reparse. This makes the first parse
3583 // faster, trading for a slower (first) reparse.
3584 unsigned PrecompilePreambleAfterNParses =
3585 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003586
Alex Lorenz08615792017-12-04 21:56:36 +00003587 LibclangInvocationReporter InvocationReporter(
3588 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003589 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3590 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003591 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003592 Args->data(), Args->data() + Args->size(),
3593 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003594 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003595 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003596 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3597 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003598 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003599 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003600 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3601 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003602
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003603 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003604 if (!Unit && !ErrUnit)
3605 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003606
Guy Benyei11169dd2012-12-18 14:30:41 +00003607 if (NumErrors != Diags->getClient()->getNumErrors()) {
3608 // Make sure to check that 'Unit' is non-NULL.
3609 if (CXXIdx->getDisplayDiagnostics())
3610 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3611 }
3612
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003613 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3614 return CXError_ASTReadError;
3615
David Blaikieea4395e2017-01-06 19:49:01 +00003616 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003617 if (CXTranslationUnitImpl *TU = *out_TU) {
3618 TU->ParsingOptions = options;
3619 TU->Arguments.reserve(Args->size());
3620 for (const char *Arg : *Args)
3621 TU->Arguments.push_back(Arg);
3622 return CXError_Success;
3623 }
3624 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003625}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003626
3627CXTranslationUnit
3628clang_parseTranslationUnit(CXIndex CIdx,
3629 const char *source_filename,
3630 const char *const *command_line_args,
3631 int num_command_line_args,
3632 struct CXUnsavedFile *unsaved_files,
3633 unsigned num_unsaved_files,
3634 unsigned options) {
3635 CXTranslationUnit TU;
3636 enum CXErrorCode Result = clang_parseTranslationUnit2(
3637 CIdx, source_filename, command_line_args, num_command_line_args,
3638 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003639 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003640 assert((TU && Result == CXError_Success) ||
3641 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003642 return TU;
3643}
3644
3645enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003646 CXIndex CIdx, const char *source_filename,
3647 const char *const *command_line_args, int num_command_line_args,
3648 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3649 unsigned options, CXTranslationUnit *out_TU) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003650 noteBottomOfStack();
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003651 SmallVector<const char *, 4> Args;
3652 Args.push_back("clang");
3653 Args.append(command_line_args, command_line_args + num_command_line_args);
3654 return clang_parseTranslationUnit2FullArgv(
3655 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3656 num_unsaved_files, options, out_TU);
3657}
3658
3659enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3660 CXIndex CIdx, const char *source_filename,
3661 const char *const *command_line_args, int num_command_line_args,
3662 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3663 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003664 LOG_FUNC_SECTION {
3665 *Log << source_filename << ": ";
3666 for (int i = 0; i != num_command_line_args; ++i)
3667 *Log << command_line_args[i] << " ";
3668 }
3669
Alp Toker9d85b182014-07-07 01:23:14 +00003670 if (num_unsaved_files && !unsaved_files)
3671 return CXError_InvalidArguments;
3672
Alp Toker5c532982014-07-07 22:42:03 +00003673 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003674 auto ParseTranslationUnitImpl = [=, &result] {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003675 noteBottomOfStack();
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003676 result = clang_parseTranslationUnit_Impl(
3677 CIdx, source_filename, command_line_args, num_command_line_args,
3678 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3679 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003680
Guy Benyei11169dd2012-12-18 14:30:41 +00003681 llvm::CrashRecoveryContext CRC;
3682
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003683 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003684 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3685 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3686 fprintf(stderr, " 'command_line_args' : [");
3687 for (int i = 0; i != num_command_line_args; ++i) {
3688 if (i)
3689 fprintf(stderr, ", ");
3690 fprintf(stderr, "'%s'", command_line_args[i]);
3691 }
3692 fprintf(stderr, "],\n");
3693 fprintf(stderr, " 'unsaved_files' : [");
3694 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3695 if (i)
3696 fprintf(stderr, ", ");
3697 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3698 unsaved_files[i].Length);
3699 }
3700 fprintf(stderr, "],\n");
3701 fprintf(stderr, " 'options' : %d,\n", options);
3702 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003703
3704 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003705 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003706 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003707 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 }
Alp Toker5c532982014-07-07 22:42:03 +00003709
3710 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003711}
3712
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003713CXString clang_Type_getObjCEncoding(CXType CT) {
3714 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3715 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3716 std::string encoding;
3717 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3718 encoding);
3719
3720 return cxstring::createDup(encoding);
3721}
3722
3723static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3724 if (C.kind == CXCursor_MacroDefinition) {
3725 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3726 return MDR->getName();
3727 } else if (C.kind == CXCursor_MacroExpansion) {
3728 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3729 return ME.getName();
3730 }
3731 return nullptr;
3732}
3733
3734unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3735 const IdentifierInfo *II = getMacroIdentifier(C);
3736 if (!II) {
3737 return false;
3738 }
3739 ASTUnit *ASTU = getCursorASTUnit(C);
3740 Preprocessor &PP = ASTU->getPreprocessor();
3741 if (const MacroInfo *MI = PP.getMacroInfo(II))
3742 return MI->isFunctionLike();
3743 return false;
3744}
3745
3746unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3747 const IdentifierInfo *II = getMacroIdentifier(C);
3748 if (!II) {
3749 return false;
3750 }
3751 ASTUnit *ASTU = getCursorASTUnit(C);
3752 Preprocessor &PP = ASTU->getPreprocessor();
3753 if (const MacroInfo *MI = PP.getMacroInfo(II))
3754 return MI->isBuiltinMacro();
3755 return false;
3756}
3757
3758unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3759 const Decl *D = getCursorDecl(C);
3760 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3761 if (!FD) {
3762 return false;
3763 }
3764 return FD->isInlined();
3765}
3766
3767static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3768 if (callExpr->getNumArgs() != 1) {
3769 return nullptr;
3770 }
3771
3772 StringLiteral *S = nullptr;
3773 auto *arg = callExpr->getArg(0);
3774 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3775 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3776 auto *subExpr = I->getSubExprAsWritten();
3777
3778 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3779 return nullptr;
3780 }
3781
3782 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3783 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3784 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3785 } else {
3786 return nullptr;
3787 }
3788 return S;
3789}
3790
David Blaikie59272572016-04-13 18:23:33 +00003791struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003792 CXEvalResultKind EvalType;
3793 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003794 unsigned long long unsignedVal;
3795 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003796 double floatVal;
3797 char *stringVal;
3798 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003799 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003800 ~ExprEvalResult() {
3801 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3802 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003803 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003804 }
3805 }
3806};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003807
3808void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003809 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003810}
3811
3812CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3813 if (!E) {
3814 return CXEval_UnExposed;
3815 }
3816 return ((ExprEvalResult *)E)->EvalType;
3817}
3818
3819int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003820 return clang_EvalResult_getAsLongLong(E);
3821}
3822
3823long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003824 if (!E) {
3825 return 0;
3826 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003827 ExprEvalResult *Result = (ExprEvalResult*)E;
3828 if (Result->IsUnsignedInt)
3829 return Result->EvalData.unsignedVal;
3830 return Result->EvalData.intVal;
3831}
3832
3833unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3834 return ((ExprEvalResult *)E)->IsUnsignedInt;
3835}
3836
3837unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3838 if (!E) {
3839 return 0;
3840 }
3841
3842 ExprEvalResult *Result = (ExprEvalResult*)E;
3843 if (Result->IsUnsignedInt)
3844 return Result->EvalData.unsignedVal;
3845 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003846}
3847
3848double clang_EvalResult_getAsDouble(CXEvalResult E) {
3849 if (!E) {
3850 return 0;
3851 }
3852 return ((ExprEvalResult *)E)->EvalData.floatVal;
3853}
3854
3855const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3856 if (!E) {
3857 return nullptr;
3858 }
3859 return ((ExprEvalResult *)E)->EvalData.stringVal;
3860}
3861
3862static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3863 Expr::EvalResult ER;
3864 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003865 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003866 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003867
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003868 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003869 if (expr->isValueDependent())
3870 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003871 if (!expr->EvaluateAsRValue(ER, ctx))
3872 return nullptr;
3873
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003874 QualType rettype;
3875 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003876 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003877 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003878 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003879
David Blaikiebbc00882016-04-13 18:36:19 +00003880 if (ER.Val.isInt()) {
3881 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003882
3883 auto& val = ER.Val.getInt();
3884 if (val.isUnsigned()) {
3885 result->IsUnsignedInt = true;
3886 result->EvalData.unsignedVal = val.getZExtValue();
3887 } else {
3888 result->EvalData.intVal = val.getExtValue();
3889 }
3890
David Blaikiebbc00882016-04-13 18:36:19 +00003891 return result.release();
3892 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003893
David Blaikiebbc00882016-04-13 18:36:19 +00003894 if (ER.Val.isFloat()) {
3895 llvm::SmallVector<char, 100> Buffer;
3896 ER.Val.getFloat().toString(Buffer);
3897 std::string floatStr(Buffer.data(), Buffer.size());
3898 result->EvalType = CXEval_Float;
3899 bool ignored;
3900 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003901 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003902 llvm::APFloat::rmNearestTiesToEven, &ignored);
3903 result->EvalData.floatVal = apFloat.convertToDouble();
3904 return result.release();
3905 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003906
David Blaikiebbc00882016-04-13 18:36:19 +00003907 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3908 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3909 auto *subExpr = I->getSubExprAsWritten();
3910 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3911 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003912 const StringLiteral *StrE = nullptr;
3913 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003914 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003915
3916 if (ObjCExpr) {
3917 StrE = ObjCExpr->getString();
3918 result->EvalType = CXEval_ObjCStrLiteral;
3919 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003920 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003921 result->EvalType = CXEval_StrLiteral;
3922 }
3923
3924 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003925 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003926 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3927 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003928 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003929 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003930 }
3931 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3932 expr->getStmtClass() == Stmt::StringLiteralClass) {
3933 const StringLiteral *StrE = nullptr;
3934 const ObjCStringLiteral *ObjCExpr;
3935 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003936
David Blaikiebbc00882016-04-13 18:36:19 +00003937 if (ObjCExpr) {
3938 StrE = ObjCExpr->getString();
3939 result->EvalType = CXEval_ObjCStrLiteral;
3940 } else {
3941 StrE = cast<StringLiteral>(expr);
3942 result->EvalType = CXEval_StrLiteral;
3943 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003944
David Blaikiebbc00882016-04-13 18:36:19 +00003945 std::string strRef(StrE->getString().str());
3946 result->EvalData.stringVal = new char[strRef.size() + 1];
3947 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3948 result->EvalData.stringVal[strRef.size()] = '\0';
3949 return result.release();
3950 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003951
David Blaikiebbc00882016-04-13 18:36:19 +00003952 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3953 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003954
David Blaikiebbc00882016-04-13 18:36:19 +00003955 rettype = CC->getType();
3956 if (rettype.getAsString() == "CFStringRef" &&
3957 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003958
David Blaikiebbc00882016-04-13 18:36:19 +00003959 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3960 StringLiteral *S = getCFSTR_value(callExpr);
3961 if (S) {
3962 std::string strLiteral(S->getString().str());
3963 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003964
David Blaikiebbc00882016-04-13 18:36:19 +00003965 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3966 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3967 strLiteral.size());
3968 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003969 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003970 }
3971 }
3972
David Blaikiebbc00882016-04-13 18:36:19 +00003973 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3974 callExpr = static_cast<CallExpr *>(expr);
3975 rettype = callExpr->getCallReturnType(ctx);
3976
3977 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3978 return nullptr;
3979
3980 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3981 if (callExpr->getNumArgs() == 1 &&
3982 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3983 return nullptr;
3984 } else if (rettype.getAsString() == "CFStringRef") {
3985
3986 StringLiteral *S = getCFSTR_value(callExpr);
3987 if (S) {
3988 std::string strLiteral(S->getString().str());
3989 result->EvalType = CXEval_CFStr;
3990 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3991 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3992 strLiteral.size());
3993 result->EvalData.stringVal[strLiteral.size()] = '\0';
3994 return result.release();
3995 }
3996 }
3997 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3998 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3999 ValueDecl *V = D->getDecl();
4000 if (V->getKind() == Decl::Function) {
4001 std::string strName = V->getNameAsString();
4002 result->EvalType = CXEval_Other;
4003 result->EvalData.stringVal = new char[strName.size() + 1];
4004 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
4005 result->EvalData.stringVal[strName.size()] = '\0';
4006 return result.release();
4007 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004008 }
4009
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004010 return nullptr;
4011}
4012
Alex Lorenz65317e12019-01-08 22:32:51 +00004013static const Expr *evaluateDeclExpr(const Decl *D) {
4014 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00004015 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00004016 if (auto *Var = dyn_cast<VarDecl>(D))
4017 return Var->getInit();
4018 else if (auto *Field = dyn_cast<FieldDecl>(D))
4019 return Field->getInClassInitializer();
4020 return nullptr;
4021}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00004022
Alex Lorenz65317e12019-01-08 22:32:51 +00004023static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
4024 assert(CS && "invalid compound statement");
4025 for (auto *bodyIterator : CS->body()) {
4026 if (const auto *E = dyn_cast<Expr>(bodyIterator))
4027 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00004028 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00004029 return nullptr;
4030}
4031
Alex Lorenz65317e12019-01-08 22:32:51 +00004032CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4033 if (const Expr *E =
4034 clang_getCursorKind(C) == CXCursor_CompoundStmt
4035 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
4036 : evaluateDeclExpr(getCursorDecl(C)))
4037 return const_cast<CXEvalResult>(
4038 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4039 return nullptr;
4040}
4041
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004042unsigned clang_Cursor_hasAttrs(CXCursor C) {
4043 const Decl *D = getCursorDecl(C);
4044 if (!D) {
4045 return 0;
4046 }
4047
4048 if (D->hasAttrs()) {
4049 return 1;
4050 }
4051
4052 return 0;
4053}
Guy Benyei11169dd2012-12-18 14:30:41 +00004054unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4055 return CXSaveTranslationUnit_None;
4056}
4057
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004058static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4059 const char *FileName,
4060 unsigned options) {
4061 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4063 setThreadBackgroundPriority();
4064
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004065 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4066 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004067}
4068
4069int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4070 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004071 LOG_FUNC_SECTION {
4072 *Log << TU << ' ' << FileName;
4073 }
4074
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004075 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004076 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004078 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004079
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004080 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4082 if (!CXXUnit->hasSema())
4083 return CXSaveError_InvalidTU;
4084
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004085 CXSaveError result;
4086 auto SaveTranslationUnitImpl = [=, &result]() {
4087 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4088 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004089
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004090 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004091 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004092
4093 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4094 PrintLibclangResourceUsage(TU);
4095
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004096 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 }
4098
4099 // We have an AST that has invalid nodes due to compiler errors.
4100 // Use a crash recovery thread for protection.
4101
4102 llvm::CrashRecoveryContext CRC;
4103
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004104 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4106 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4107 fprintf(stderr, " 'options' : %d,\n", options);
4108 fprintf(stderr, "}\n");
4109
4110 return CXSaveError_Unknown;
4111
4112 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4113 PrintLibclangResourceUsage(TU);
4114 }
4115
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004116 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004117}
4118
4119void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4120 if (CTUnit) {
4121 // If the translation unit has been marked as unsafe to free, just discard
4122 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004123 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4124 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 return;
4126
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004127 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004128 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4130 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004131 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004132 delete CTUnit;
4133 }
4134}
4135
Erik Verbruggen346066b2017-05-30 14:25:54 +00004136unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4137 if (CTUnit) {
4138 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4139
4140 if (Unit && Unit->isUnsafeToFree())
4141 return false;
4142
4143 Unit->ResetForParse();
4144 return true;
4145 }
4146
4147 return false;
4148}
4149
Guy Benyei11169dd2012-12-18 14:30:41 +00004150unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4151 return CXReparse_None;
4152}
4153
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004154static CXErrorCode
4155clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4156 ArrayRef<CXUnsavedFile> unsaved_files,
4157 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004158 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004159 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004160 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004161 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004162 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004163
4164 // Reset the associated diagnostics.
4165 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004166 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004167
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004168 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004169 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4170 setThreadBackgroundPriority();
4171
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004172 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004174
4175 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4176 new std::vector<ASTUnit::RemappedFile>());
4177
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 // Recover resources if we crash before exiting this function.
4179 llvm::CrashRecoveryContextCleanupRegistrar<
4180 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004181
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004182 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004183 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004184 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004185 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004187
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004188 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4189 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004190 return CXError_Success;
4191 if (isASTReadError(CXXUnit))
4192 return CXError_ASTReadError;
4193 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004194}
4195
4196int clang_reparseTranslationUnit(CXTranslationUnit TU,
4197 unsigned num_unsaved_files,
4198 struct CXUnsavedFile *unsaved_files,
4199 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004200 LOG_FUNC_SECTION {
4201 *Log << TU;
4202 }
4203
Alp Toker9d85b182014-07-07 01:23:14 +00004204 if (num_unsaved_files && !unsaved_files)
4205 return CXError_InvalidArguments;
4206
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004207 CXErrorCode result;
4208 auto ReparseTranslationUnitImpl = [=, &result]() {
4209 result = clang_reparseTranslationUnit_Impl(
4210 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4211 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004212
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 llvm::CrashRecoveryContext CRC;
4214
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004215 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004217 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004218 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4220 PrintLibclangResourceUsage(TU);
4221
Alp Toker5c532982014-07-07 22:42:03 +00004222 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004223}
4224
4225
4226CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004227 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004228 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004229 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004230 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004231
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004232 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004233 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004234}
4235
4236CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004237 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004238 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004239 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004240 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004241
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004242 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4244}
4245
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004246CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4247 if (isNotUsableTU(CTUnit)) {
4248 LOG_BAD_TU(CTUnit);
4249 return nullptr;
4250 }
4251
4252 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4253 impl->TranslationUnit = CTUnit;
4254 return impl;
4255}
4256
4257CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4258 if (!TargetInfo)
4259 return cxstring::createEmpty();
4260
4261 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4262 assert(!isNotUsableTU(CTUnit) &&
4263 "Unexpected unusable translation unit in TargetInfo");
4264
4265 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4266 std::string Triple =
4267 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4268 return cxstring::createDup(Triple);
4269}
4270
4271int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4272 if (!TargetInfo)
4273 return -1;
4274
4275 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4276 assert(!isNotUsableTU(CTUnit) &&
4277 "Unexpected unusable translation unit in TargetInfo");
4278
4279 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4280 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4281}
4282
4283void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4284 if (!TargetInfo)
4285 return;
4286
4287 delete TargetInfo;
4288}
4289
Guy Benyei11169dd2012-12-18 14:30:41 +00004290//===----------------------------------------------------------------------===//
4291// CXFile Operations.
4292//===----------------------------------------------------------------------===//
4293
Guy Benyei11169dd2012-12-18 14:30:41 +00004294CXString clang_getFileName(CXFile SFile) {
4295 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004296 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004297
4298 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004299 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004300}
4301
4302time_t clang_getFileTime(CXFile SFile) {
4303 if (!SFile)
4304 return 0;
4305
4306 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4307 return FEnt->getModificationTime();
4308}
4309
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004310CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004311 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004312 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004313 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004314 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004315
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004316 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004317
4318 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004319 auto File = FMgr.getFile(file_name);
4320 if (!File)
4321 return nullptr;
4322 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004323}
4324
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004325const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4326 size_t *size) {
4327 if (isNotUsableTU(TU)) {
4328 LOG_BAD_TU(TU);
4329 return nullptr;
4330 }
4331
4332 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4333 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4334 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004335 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004336 if (Invalid) {
4337 if (size)
4338 *size = 0;
4339 return nullptr;
4340 }
4341 if (size)
4342 *size = buf->getBufferSize();
4343 return buf->getBufferStart();
4344}
4345
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004346unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4347 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004348 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004349 LOG_BAD_TU(TU);
4350 return 0;
4351 }
4352
4353 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 return 0;
4355
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004356 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 FileEntry *FEnt = static_cast<FileEntry *>(file);
4358 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4359 .isFileMultipleIncludeGuarded(FEnt);
4360}
4361
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004362int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4363 if (!file || !outID)
4364 return 1;
4365
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004366 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004367 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4368 outID->data[0] = ID.getDevice();
4369 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004370 outID->data[2] = FEnt->getModificationTime();
4371 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004372}
4373
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004374int clang_File_isEqual(CXFile file1, CXFile file2) {
4375 if (file1 == file2)
4376 return true;
4377
4378 if (!file1 || !file2)
4379 return false;
4380
4381 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4382 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4383 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4384}
4385
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004386CXString clang_File_tryGetRealPathName(CXFile SFile) {
4387 if (!SFile)
4388 return cxstring::createNull();
4389
4390 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4391 return cxstring::createRef(FEnt->tryGetRealPathName());
4392}
4393
Guy Benyei11169dd2012-12-18 14:30:41 +00004394//===----------------------------------------------------------------------===//
4395// CXCursor Operations.
4396//===----------------------------------------------------------------------===//
4397
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004398static const Decl *getDeclFromExpr(const Stmt *E) {
4399 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 return getDeclFromExpr(CE->getSubExpr());
4401
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004402 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004404 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004406 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004408 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 if (PRE->isExplicitProperty())
4410 return PRE->getExplicitProperty();
4411 // It could be messaging both getter and setter as in:
4412 // ++myobj.myprop;
4413 // in which case prefer to associate the setter since it is less obvious
4414 // from inspecting the source that the setter is going to get called.
4415 if (PRE->isMessagingSetter())
4416 return PRE->getImplicitPropertySetter();
4417 return PRE->getImplicitPropertyGetter();
4418 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004419 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004421 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 if (Expr *Src = OVE->getSourceExpr())
4423 return getDeclFromExpr(Src);
4424
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004425 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004427 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 if (!CE->isElidable())
4429 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004430 if (const CXXInheritedCtorInitExpr *CE =
4431 dyn_cast<CXXInheritedCtorInitExpr>(E))
4432 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004433 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 return OME->getMethodDecl();
4435
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004436 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004438 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4440 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004441 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4443 isa<ParmVarDecl>(SizeOfPack->getPack()))
4444 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004445
4446 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004447}
4448
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004449static SourceLocation getLocationFromExpr(const Expr *E) {
4450 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 return getLocationFromExpr(CE->getSubExpr());
4452
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004453 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004455 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004457 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004459 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004461 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004463 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004465
4466 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004467}
4468
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004469extern "C" {
4470
Guy Benyei11169dd2012-12-18 14:30:41 +00004471unsigned clang_visitChildren(CXCursor parent,
4472 CXCursorVisitor visitor,
4473 CXClientData client_data) {
4474 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4475 /*VisitPreprocessorLast=*/false);
4476 return CursorVis.VisitChildren(parent);
4477}
4478
4479#ifndef __has_feature
4480#define __has_feature(x) 0
4481#endif
4482#if __has_feature(blocks)
4483typedef enum CXChildVisitResult
4484 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4485
4486static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4487 CXClientData client_data) {
4488 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4489 return block(cursor, parent);
4490}
4491#else
4492// If we are compiled with a compiler that doesn't have native blocks support,
4493// define and call the block manually, so the
4494typedef struct _CXChildVisitResult
4495{
4496 void *isa;
4497 int flags;
4498 int reserved;
4499 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4500 CXCursor);
4501} *CXCursorVisitorBlock;
4502
4503static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4504 CXClientData client_data) {
4505 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4506 return block->invoke(block, cursor, parent);
4507}
4508#endif
4509
4510
4511unsigned clang_visitChildrenWithBlock(CXCursor parent,
4512 CXCursorVisitorBlock block) {
4513 return clang_visitChildren(parent, visitWithBlock, block);
4514}
4515
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004516static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004518 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004519
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004520 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004522 if (const ObjCPropertyImplDecl *PropImpl =
4523 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004525 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004526
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004527 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004529 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004530
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004531 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 }
4533
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004534 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004535 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004536
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004537 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4539 // and returns different names. NamedDecl returns the class name and
4540 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004541 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004542
4543 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004544 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004545
4546 SmallString<1024> S;
4547 llvm::raw_svector_ostream os(S);
4548 ND->printName(os);
4549
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004550 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004551}
4552
4553CXString clang_getCursorSpelling(CXCursor C) {
4554 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004555 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004556
4557 if (clang_isReference(C.kind)) {
4558 switch (C.kind) {
4559 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004560 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004561 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004562 }
4563 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004564 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004565 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 }
4567 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004568 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004570 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 }
4572 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004573 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004574 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 }
4576 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004577 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 assert(Type && "Missing type decl");
4579
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004580 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 getAsString());
4582 }
4583 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004584 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 assert(Template && "Missing template decl");
4586
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004587 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004588 }
4589
4590 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004591 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 assert(NS && "Missing namespace decl");
4593
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004594 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 }
4596
4597 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004598 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 assert(Field && "Missing member decl");
4600
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004601 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 }
4603
4604 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004605 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 assert(Label && "Missing label");
4607
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004608 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 }
4610
4611 case CXCursor_OverloadedDeclRef: {
4612 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004613 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4614 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004615 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004616 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004618 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004619 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 OverloadedTemplateStorage *Ovl
4621 = Storage.get<OverloadedTemplateStorage*>();
4622 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004623 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004624 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 }
4626
4627 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004628 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 assert(Var && "Missing variable decl");
4630
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004631 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 }
4633
4634 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004635 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 }
4637 }
4638
4639 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004640 const Expr *E = getCursorExpr(C);
4641
4642 if (C.kind == CXCursor_ObjCStringLiteral ||
4643 C.kind == CXCursor_StringLiteral) {
4644 const StringLiteral *SLit;
4645 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4646 SLit = OSL->getString();
4647 } else {
4648 SLit = cast<StringLiteral>(E);
4649 }
4650 SmallString<256> Buf;
4651 llvm::raw_svector_ostream OS(Buf);
4652 SLit->outputString(OS);
4653 return cxstring::createDup(OS.str());
4654 }
4655
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004656 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 if (D)
4658 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004659 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 }
4661
4662 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004663 const Stmt *S = getCursorStmt(C);
4664 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004665 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004666
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004667 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 }
4669
4670 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004671 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 ->getNameStart());
4673
4674 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004675 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004676 ->getNameStart());
4677
4678 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004679 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004680
4681 if (clang_isDeclaration(C.kind))
4682 return getDeclSpelling(getCursorDecl(C));
4683
4684 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004685 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004686 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 }
4688
4689 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004690 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004691 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 }
4693
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004694 if (C.kind == CXCursor_PackedAttr) {
4695 return cxstring::createRef("packed");
4696 }
4697
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004698 if (C.kind == CXCursor_VisibilityAttr) {
4699 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4700 switch (AA->getVisibility()) {
4701 case VisibilityAttr::VisibilityType::Default:
4702 return cxstring::createRef("default");
4703 case VisibilityAttr::VisibilityType::Hidden:
4704 return cxstring::createRef("hidden");
4705 case VisibilityAttr::VisibilityType::Protected:
4706 return cxstring::createRef("protected");
4707 }
4708 llvm_unreachable("unknown visibility type");
4709 }
4710
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004711 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004712}
4713
4714CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4715 unsigned pieceIndex,
4716 unsigned options) {
4717 if (clang_Cursor_isNull(C))
4718 return clang_getNullRange();
4719
4720 ASTContext &Ctx = getCursorContext(C);
4721
4722 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004723 const Stmt *S = getCursorStmt(C);
4724 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 if (pieceIndex > 0)
4726 return clang_getNullRange();
4727 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4728 }
4729
4730 return clang_getNullRange();
4731 }
4732
4733 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004734 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4736 if (pieceIndex >= ME->getNumSelectorLocs())
4737 return clang_getNullRange();
4738 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4739 }
4740 }
4741
4742 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4743 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004744 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4746 if (pieceIndex >= MD->getNumSelectorLocs())
4747 return clang_getNullRange();
4748 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4749 }
4750 }
4751
4752 if (C.kind == CXCursor_ObjCCategoryDecl ||
4753 C.kind == CXCursor_ObjCCategoryImplDecl) {
4754 if (pieceIndex > 0)
4755 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004756 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4758 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004759 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4761 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4762 }
4763
4764 if (C.kind == CXCursor_ModuleImportDecl) {
4765 if (pieceIndex > 0)
4766 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004767 if (const ImportDecl *ImportD =
4768 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4770 if (!Locs.empty())
4771 return cxloc::translateSourceRange(Ctx,
4772 SourceRange(Locs.front(), Locs.back()));
4773 }
4774 return clang_getNullRange();
4775 }
4776
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004777 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004778 C.kind == CXCursor_ConversionFunction ||
4779 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004780 if (pieceIndex > 0)
4781 return clang_getNullRange();
4782 if (const FunctionDecl *FD =
4783 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4784 DeclarationNameInfo FunctionName = FD->getNameInfo();
4785 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4786 }
4787 return clang_getNullRange();
4788 }
4789
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 // FIXME: A CXCursor_InclusionDirective should give the location of the
4791 // filename, but we don't keep track of this.
4792
4793 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4794 // but we don't keep track of this.
4795
4796 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4797 // but we don't keep track of this.
4798
4799 // Default handling, give the location of the cursor.
4800
4801 if (pieceIndex > 0)
4802 return clang_getNullRange();
4803
4804 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4805 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4806 return cxloc::translateSourceRange(Ctx, Loc);
4807}
4808
Eli Bendersky44a206f2014-07-31 18:04:56 +00004809CXString clang_Cursor_getMangling(CXCursor C) {
4810 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4811 return cxstring::createEmpty();
4812
Eli Bendersky44a206f2014-07-31 18:04:56 +00004813 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004814 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004815 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4816 return cxstring::createEmpty();
4817
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004818 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004819 ASTNameGenerator ASTNameGen(Ctx);
4820 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004821}
4822
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004823CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4824 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4825 return nullptr;
4826
4827 const Decl *D = getCursorDecl(C);
4828 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4829 return nullptr;
4830
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004831 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004832 ASTNameGenerator ASTNameGen(Ctx);
4833 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004834 return cxstring::createSet(Manglings);
4835}
4836
Dave Lee1a532c92017-09-22 16:58:57 +00004837CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4838 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4839 return nullptr;
4840
4841 const Decl *D = getCursorDecl(C);
4842 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4843 return nullptr;
4844
4845 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004846 ASTNameGenerator ASTNameGen(Ctx);
4847 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004848 return cxstring::createSet(Manglings);
4849}
4850
Jonathan Coe45ef5032018-01-16 10:19:56 +00004851CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4852 if (clang_Cursor_isNull(C))
4853 return 0;
4854 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4855}
4856
4857void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4858 if (Policy)
4859 delete static_cast<PrintingPolicy *>(Policy);
4860}
4861
4862unsigned
4863clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4864 enum CXPrintingPolicyProperty Property) {
4865 if (!Policy)
4866 return 0;
4867
4868 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4869 switch (Property) {
4870 case CXPrintingPolicy_Indentation:
4871 return P->Indentation;
4872 case CXPrintingPolicy_SuppressSpecifiers:
4873 return P->SuppressSpecifiers;
4874 case CXPrintingPolicy_SuppressTagKeyword:
4875 return P->SuppressTagKeyword;
4876 case CXPrintingPolicy_IncludeTagDefinition:
4877 return P->IncludeTagDefinition;
4878 case CXPrintingPolicy_SuppressScope:
4879 return P->SuppressScope;
4880 case CXPrintingPolicy_SuppressUnwrittenScope:
4881 return P->SuppressUnwrittenScope;
4882 case CXPrintingPolicy_SuppressInitializers:
4883 return P->SuppressInitializers;
4884 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4885 return P->ConstantArraySizeAsWritten;
4886 case CXPrintingPolicy_AnonymousTagLocations:
4887 return P->AnonymousTagLocations;
4888 case CXPrintingPolicy_SuppressStrongLifetime:
4889 return P->SuppressStrongLifetime;
4890 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4891 return P->SuppressLifetimeQualifiers;
4892 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4893 return P->SuppressTemplateArgsInCXXConstructors;
4894 case CXPrintingPolicy_Bool:
4895 return P->Bool;
4896 case CXPrintingPolicy_Restrict:
4897 return P->Restrict;
4898 case CXPrintingPolicy_Alignof:
4899 return P->Alignof;
4900 case CXPrintingPolicy_UnderscoreAlignof:
4901 return P->UnderscoreAlignof;
4902 case CXPrintingPolicy_UseVoidForZeroParams:
4903 return P->UseVoidForZeroParams;
4904 case CXPrintingPolicy_TerseOutput:
4905 return P->TerseOutput;
4906 case CXPrintingPolicy_PolishForDeclaration:
4907 return P->PolishForDeclaration;
4908 case CXPrintingPolicy_Half:
4909 return P->Half;
4910 case CXPrintingPolicy_MSWChar:
4911 return P->MSWChar;
4912 case CXPrintingPolicy_IncludeNewlines:
4913 return P->IncludeNewlines;
4914 case CXPrintingPolicy_MSVCFormatting:
4915 return P->MSVCFormatting;
4916 case CXPrintingPolicy_ConstantsAsWritten:
4917 return P->ConstantsAsWritten;
4918 case CXPrintingPolicy_SuppressImplicitBase:
4919 return P->SuppressImplicitBase;
4920 case CXPrintingPolicy_FullyQualifiedName:
4921 return P->FullyQualifiedName;
4922 }
4923
4924 assert(false && "Invalid CXPrintingPolicyProperty");
4925 return 0;
4926}
4927
4928void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4929 enum CXPrintingPolicyProperty Property,
4930 unsigned Value) {
4931 if (!Policy)
4932 return;
4933
4934 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4935 switch (Property) {
4936 case CXPrintingPolicy_Indentation:
4937 P->Indentation = Value;
4938 return;
4939 case CXPrintingPolicy_SuppressSpecifiers:
4940 P->SuppressSpecifiers = Value;
4941 return;
4942 case CXPrintingPolicy_SuppressTagKeyword:
4943 P->SuppressTagKeyword = Value;
4944 return;
4945 case CXPrintingPolicy_IncludeTagDefinition:
4946 P->IncludeTagDefinition = Value;
4947 return;
4948 case CXPrintingPolicy_SuppressScope:
4949 P->SuppressScope = Value;
4950 return;
4951 case CXPrintingPolicy_SuppressUnwrittenScope:
4952 P->SuppressUnwrittenScope = Value;
4953 return;
4954 case CXPrintingPolicy_SuppressInitializers:
4955 P->SuppressInitializers = Value;
4956 return;
4957 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4958 P->ConstantArraySizeAsWritten = Value;
4959 return;
4960 case CXPrintingPolicy_AnonymousTagLocations:
4961 P->AnonymousTagLocations = Value;
4962 return;
4963 case CXPrintingPolicy_SuppressStrongLifetime:
4964 P->SuppressStrongLifetime = Value;
4965 return;
4966 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4967 P->SuppressLifetimeQualifiers = Value;
4968 return;
4969 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4970 P->SuppressTemplateArgsInCXXConstructors = Value;
4971 return;
4972 case CXPrintingPolicy_Bool:
4973 P->Bool = Value;
4974 return;
4975 case CXPrintingPolicy_Restrict:
4976 P->Restrict = Value;
4977 return;
4978 case CXPrintingPolicy_Alignof:
4979 P->Alignof = Value;
4980 return;
4981 case CXPrintingPolicy_UnderscoreAlignof:
4982 P->UnderscoreAlignof = Value;
4983 return;
4984 case CXPrintingPolicy_UseVoidForZeroParams:
4985 P->UseVoidForZeroParams = Value;
4986 return;
4987 case CXPrintingPolicy_TerseOutput:
4988 P->TerseOutput = Value;
4989 return;
4990 case CXPrintingPolicy_PolishForDeclaration:
4991 P->PolishForDeclaration = Value;
4992 return;
4993 case CXPrintingPolicy_Half:
4994 P->Half = Value;
4995 return;
4996 case CXPrintingPolicy_MSWChar:
4997 P->MSWChar = Value;
4998 return;
4999 case CXPrintingPolicy_IncludeNewlines:
5000 P->IncludeNewlines = Value;
5001 return;
5002 case CXPrintingPolicy_MSVCFormatting:
5003 P->MSVCFormatting = Value;
5004 return;
5005 case CXPrintingPolicy_ConstantsAsWritten:
5006 P->ConstantsAsWritten = Value;
5007 return;
5008 case CXPrintingPolicy_SuppressImplicitBase:
5009 P->SuppressImplicitBase = Value;
5010 return;
5011 case CXPrintingPolicy_FullyQualifiedName:
5012 P->FullyQualifiedName = Value;
5013 return;
5014 }
5015
5016 assert(false && "Invalid CXPrintingPolicyProperty");
5017}
5018
5019CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
5020 if (clang_Cursor_isNull(C))
5021 return cxstring::createEmpty();
5022
5023 if (clang_isDeclaration(C.kind)) {
5024 const Decl *D = getCursorDecl(C);
5025 if (!D)
5026 return cxstring::createEmpty();
5027
5028 SmallString<128> Str;
5029 llvm::raw_svector_ostream OS(Str);
5030 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
5031 D->print(OS, UserPolicy ? *UserPolicy
5032 : getCursorContext(C).getPrintingPolicy());
5033
5034 return cxstring::createDup(OS.str());
5035 }
5036
5037 return cxstring::createEmpty();
5038}
5039
Guy Benyei11169dd2012-12-18 14:30:41 +00005040CXString clang_getCursorDisplayName(CXCursor C) {
5041 if (!clang_isDeclaration(C.kind))
5042 return clang_getCursorSpelling(C);
5043
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005044 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005046 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005047
5048 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005049 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 D = FunTmpl->getTemplatedDecl();
5051
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005052 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 SmallString<64> Str;
5054 llvm::raw_svector_ostream OS(Str);
5055 OS << *Function;
5056 if (Function->getPrimaryTemplate())
5057 OS << "<>";
5058 OS << "(";
5059 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5060 if (I)
5061 OS << ", ";
5062 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5063 }
5064
5065 if (Function->isVariadic()) {
5066 if (Function->getNumParams())
5067 OS << ", ";
5068 OS << "...";
5069 }
5070 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005071 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 }
5073
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005074 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 SmallString<64> Str;
5076 llvm::raw_svector_ostream OS(Str);
5077 OS << *ClassTemplate;
5078 OS << "<";
5079 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5080 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5081 if (I)
5082 OS << ", ";
5083
5084 NamedDecl *Param = Params->getParam(I);
5085 if (Param->getIdentifier()) {
5086 OS << Param->getIdentifier()->getName();
5087 continue;
5088 }
5089
5090 // There is no parameter name, which makes this tricky. Try to come up
5091 // with something useful that isn't too long.
5092 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Saar Razff1e0fc2020-01-15 02:48:42 +02005093 if (const auto *TC = TTP->getTypeConstraint()) {
5094 TC->getConceptNameInfo().printName(OS, Policy);
5095 if (TC->hasExplicitTemplateArgs())
5096 OS << "<...>";
5097 } else
5098 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 else if (NonTypeTemplateParmDecl *NTTP
5100 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5101 OS << NTTP->getType().getAsString(Policy);
5102 else
5103 OS << "template<...> class";
5104 }
5105
5106 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005107 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 }
5109
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005110 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5112 // If the type was explicitly written, use that.
5113 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005114 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005115
Benjamin Kramer9170e912013-02-22 15:46:01 +00005116 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 llvm::raw_svector_ostream OS(Str);
5118 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005119 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5120 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005121 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 }
5123
5124 return clang_getCursorSpelling(C);
5125}
5126
5127CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5128 switch (Kind) {
5129 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005193 case CXCursor_FixedPointLiteral:
5194 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005209 case CXCursor_OMPArraySectionExpr:
5210 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005261 case CXCursor_ObjCAvailabilityCheckExpr:
5262 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005263 case CXCursor_ObjCSelfExpr:
5264 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005268 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005270 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005272 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005273 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005274 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005275 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005276 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005278 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005280 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005282 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005284 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005286 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005288 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005290 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005291 case CXCursor_BuiltinBitCastExpr:
5292 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005294 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005295 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005296 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005298 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005300 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005301 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005302 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005303 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005304 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005305 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005306 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005307 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005308 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005309 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005310 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005312 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005313 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005314 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005316 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005317 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005318 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005319 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005320 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005321 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005322 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005323 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005324 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005325 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005326 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005327 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005328 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005329 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005330 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005332 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005334 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005336 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005338 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005340 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005342 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005344 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005346 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005348 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005350 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005354 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005355 case CXCursor_SEHLeaveStmt:
5356 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005358 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005360 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005362 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005364 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005365 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005366 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005368 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005369 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005370 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005371 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005372 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005374 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005375 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005376 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005378 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005379 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005380 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005381 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005382 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005384 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005385 case CXCursor_PackedAttr:
5386 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005387 case CXCursor_PureAttr:
5388 return cxstring::createRef("attribute(pure)");
5389 case CXCursor_ConstAttr:
5390 return cxstring::createRef("attribute(const)");
5391 case CXCursor_NoDuplicateAttr:
5392 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005393 case CXCursor_CUDAConstantAttr:
5394 return cxstring::createRef("attribute(constant)");
5395 case CXCursor_CUDADeviceAttr:
5396 return cxstring::createRef("attribute(device)");
5397 case CXCursor_CUDAGlobalAttr:
5398 return cxstring::createRef("attribute(global)");
5399 case CXCursor_CUDAHostAttr:
5400 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005401 case CXCursor_CUDASharedAttr:
5402 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005403 case CXCursor_VisibilityAttr:
5404 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005405 case CXCursor_DLLExport:
5406 return cxstring::createRef("attribute(dllexport)");
5407 case CXCursor_DLLImport:
5408 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005409 case CXCursor_NSReturnsRetained:
5410 return cxstring::createRef("attribute(ns_returns_retained)");
5411 case CXCursor_NSReturnsNotRetained:
5412 return cxstring::createRef("attribute(ns_returns_not_retained)");
5413 case CXCursor_NSReturnsAutoreleased:
5414 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5415 case CXCursor_NSConsumesSelf:
5416 return cxstring::createRef("attribute(ns_consumes_self)");
5417 case CXCursor_NSConsumed:
5418 return cxstring::createRef("attribute(ns_consumed)");
5419 case CXCursor_ObjCException:
5420 return cxstring::createRef("attribute(objc_exception)");
5421 case CXCursor_ObjCNSObject:
5422 return cxstring::createRef("attribute(NSObject)");
5423 case CXCursor_ObjCIndependentClass:
5424 return cxstring::createRef("attribute(objc_independent_class)");
5425 case CXCursor_ObjCPreciseLifetime:
5426 return cxstring::createRef("attribute(objc_precise_lifetime)");
5427 case CXCursor_ObjCReturnsInnerPointer:
5428 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5429 case CXCursor_ObjCRequiresSuper:
5430 return cxstring::createRef("attribute(objc_requires_super)");
5431 case CXCursor_ObjCRootClass:
5432 return cxstring::createRef("attribute(objc_root_class)");
5433 case CXCursor_ObjCSubclassingRestricted:
5434 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5435 case CXCursor_ObjCExplicitProtocolImpl:
5436 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5437 case CXCursor_ObjCDesignatedInitializer:
5438 return cxstring::createRef("attribute(objc_designated_initializer)");
5439 case CXCursor_ObjCRuntimeVisible:
5440 return cxstring::createRef("attribute(objc_runtime_visible)");
5441 case CXCursor_ObjCBoxable:
5442 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005443 case CXCursor_FlagEnum:
5444 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005445 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005446 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005447 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005448 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005449 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005450 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005451 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005452 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005453 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005454 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005455 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005456 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005457 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005458 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005459 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005460 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005461 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005462 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005463 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005464 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005465 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005466 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005467 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005468 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005469 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005470 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005471 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005472 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005473 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005474 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005475 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005476 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005477 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005478 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005479 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005480 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005481 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005482 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005483 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005484 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005485 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005486 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005487 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005488 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005489 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005490 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005491 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005492 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005493 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005494 return cxstring::createRef("OMPParallelDirective");
5495 case CXCursor_OMPSimdDirective:
5496 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005497 case CXCursor_OMPForDirective:
5498 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005499 case CXCursor_OMPForSimdDirective:
5500 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005501 case CXCursor_OMPSectionsDirective:
5502 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005503 case CXCursor_OMPSectionDirective:
5504 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005505 case CXCursor_OMPSingleDirective:
5506 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005507 case CXCursor_OMPMasterDirective:
5508 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005509 case CXCursor_OMPCriticalDirective:
5510 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005511 case CXCursor_OMPParallelForDirective:
5512 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005513 case CXCursor_OMPParallelForSimdDirective:
5514 return cxstring::createRef("OMPParallelForSimdDirective");
cchen47d60942019-12-05 13:43:48 -05005515 case CXCursor_OMPParallelMasterDirective:
5516 return cxstring::createRef("OMPParallelMasterDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005517 case CXCursor_OMPParallelSectionsDirective:
5518 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005519 case CXCursor_OMPTaskDirective:
5520 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005521 case CXCursor_OMPTaskyieldDirective:
5522 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005523 case CXCursor_OMPBarrierDirective:
5524 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005525 case CXCursor_OMPTaskwaitDirective:
5526 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005527 case CXCursor_OMPTaskgroupDirective:
5528 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005529 case CXCursor_OMPFlushDirective:
5530 return cxstring::createRef("OMPFlushDirective");
Alexey Bataevc112e942020-02-28 09:52:15 -05005531 case CXCursor_OMPDepobjDirective:
5532 return cxstring::createRef("OMPDepobjDirective");
Alexey Bataevfcba7c32020-03-20 07:03:01 -04005533 case CXCursor_OMPScanDirective:
5534 return cxstring::createRef("OMPScanDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005535 case CXCursor_OMPOrderedDirective:
5536 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005537 case CXCursor_OMPAtomicDirective:
5538 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005539 case CXCursor_OMPTargetDirective:
5540 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005541 case CXCursor_OMPTargetDataDirective:
5542 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005543 case CXCursor_OMPTargetEnterDataDirective:
5544 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005545 case CXCursor_OMPTargetExitDataDirective:
5546 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005547 case CXCursor_OMPTargetParallelDirective:
5548 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005549 case CXCursor_OMPTargetParallelForDirective:
5550 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005551 case CXCursor_OMPTargetUpdateDirective:
5552 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005553 case CXCursor_OMPTeamsDirective:
5554 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005555 case CXCursor_OMPCancellationPointDirective:
5556 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005557 case CXCursor_OMPCancelDirective:
5558 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005559 case CXCursor_OMPTaskLoopDirective:
5560 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005561 case CXCursor_OMPTaskLoopSimdDirective:
5562 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005563 case CXCursor_OMPMasterTaskLoopDirective:
5564 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005565 case CXCursor_OMPMasterTaskLoopSimdDirective:
5566 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005567 case CXCursor_OMPParallelMasterTaskLoopDirective:
5568 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Alexey Bataev14a388f2019-10-25 10:27:13 -04005569 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5570 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005571 case CXCursor_OMPDistributeDirective:
5572 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005573 case CXCursor_OMPDistributeParallelForDirective:
5574 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005575 case CXCursor_OMPDistributeParallelForSimdDirective:
5576 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005577 case CXCursor_OMPDistributeSimdDirective:
5578 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005579 case CXCursor_OMPTargetParallelForSimdDirective:
5580 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005581 case CXCursor_OMPTargetSimdDirective:
5582 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005583 case CXCursor_OMPTeamsDistributeDirective:
5584 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005585 case CXCursor_OMPTeamsDistributeSimdDirective:
5586 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005587 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5588 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005589 case CXCursor_OMPTeamsDistributeParallelForDirective:
5590 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005591 case CXCursor_OMPTargetTeamsDirective:
5592 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005593 case CXCursor_OMPTargetTeamsDistributeDirective:
5594 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005595 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5596 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005597 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5598 return cxstring::createRef(
5599 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005600 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5601 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005602 case CXCursor_OverloadCandidate:
5603 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005604 case CXCursor_TypeAliasTemplateDecl:
5605 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005606 case CXCursor_StaticAssert:
5607 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005608 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005609 return cxstring::createRef("FriendDecl");
5610 case CXCursor_ConvergentAttr:
5611 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005612 case CXCursor_WarnUnusedAttr:
5613 return cxstring::createRef("attribute(warn_unused)");
5614 case CXCursor_WarnUnusedResultAttr:
5615 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005616 case CXCursor_AlignedAttr:
5617 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005618 }
5619
5620 llvm_unreachable("Unhandled CXCursorKind");
5621}
5622
5623struct GetCursorData {
5624 SourceLocation TokenBeginLoc;
5625 bool PointsAtMacroArgExpansion;
5626 bool VisitedObjCPropertyImplDecl;
5627 SourceLocation VisitedDeclaratorDeclStartLoc;
5628 CXCursor &BestCursor;
5629
5630 GetCursorData(SourceManager &SM,
5631 SourceLocation tokenBegin, CXCursor &outputCursor)
5632 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5633 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5634 VisitedObjCPropertyImplDecl = false;
5635 }
5636};
5637
5638static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5639 CXCursor parent,
5640 CXClientData client_data) {
5641 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5642 CXCursor *BestCursor = &Data->BestCursor;
5643
5644 // If we point inside a macro argument we should provide info of what the
5645 // token is so use the actual cursor, don't replace it with a macro expansion
5646 // cursor.
5647 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5648 return CXChildVisit_Recurse;
5649
5650 if (clang_isDeclaration(cursor.kind)) {
5651 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005652 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005653 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5654 if (MD->isImplicit())
5655 return CXChildVisit_Break;
5656
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005657 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5659 // Check that when we have multiple @class references in the same line,
5660 // that later ones do not override the previous ones.
5661 // If we have:
5662 // @class Foo, Bar;
5663 // source ranges for both start at '@', so 'Bar' will end up overriding
5664 // 'Foo' even though the cursor location was at 'Foo'.
5665 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5666 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005667 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005668 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5669 if (PrevID != ID &&
5670 !PrevID->isThisDeclarationADefinition() &&
5671 !ID->isThisDeclarationADefinition())
5672 return CXChildVisit_Break;
5673 }
5674
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005675 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005676 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5677 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5678 // Check that when we have multiple declarators in the same line,
5679 // that later ones do not override the previous ones.
5680 // If we have:
5681 // int Foo, Bar;
5682 // source ranges for both start at 'int', so 'Bar' will end up overriding
5683 // 'Foo' even though the cursor location was at 'Foo'.
5684 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5685 return CXChildVisit_Break;
5686 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5687
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005688 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005689 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5690 (void)PropImp;
5691 // Check that when we have multiple @synthesize in the same line,
5692 // that later ones do not override the previous ones.
5693 // If we have:
5694 // @synthesize Foo, Bar;
5695 // source ranges for both start at '@', so 'Bar' will end up overriding
5696 // 'Foo' even though the cursor location was at 'Foo'.
5697 if (Data->VisitedObjCPropertyImplDecl)
5698 return CXChildVisit_Break;
5699 Data->VisitedObjCPropertyImplDecl = true;
5700 }
5701 }
5702
5703 if (clang_isExpression(cursor.kind) &&
5704 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005705 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005706 // Avoid having the cursor of an expression replace the declaration cursor
5707 // when the expression source range overlaps the declaration range.
5708 // This can happen for C++ constructor expressions whose range generally
5709 // include the variable declaration, e.g.:
5710 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5711 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5712 D->getLocation() == Data->TokenBeginLoc)
5713 return CXChildVisit_Break;
5714 }
5715 }
5716
5717 // If our current best cursor is the construction of a temporary object,
5718 // don't replace that cursor with a type reference, because we want
5719 // clang_getCursor() to point at the constructor.
5720 if (clang_isExpression(BestCursor->kind) &&
5721 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5722 cursor.kind == CXCursor_TypeRef) {
5723 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5724 // as having the actual point on the type reference.
5725 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5726 return CXChildVisit_Recurse;
5727 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005728
5729 // If we already have an Objective-C superclass reference, don't
5730 // update it further.
5731 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5732 return CXChildVisit_Break;
5733
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 *BestCursor = cursor;
5735 return CXChildVisit_Recurse;
5736}
5737
5738CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005739 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005740 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005741 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005742 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005743
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005744 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005745 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5746
5747 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5748 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5749
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005750 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005751 CXFile SearchFile;
5752 unsigned SearchLine, SearchColumn;
5753 CXFile ResultFile;
5754 unsigned ResultLine, ResultColumn;
5755 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5756 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5757 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005758
5759 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5760 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005761 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005762 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005763 SearchFileName = clang_getFileName(SearchFile);
5764 ResultFileName = clang_getFileName(ResultFile);
5765 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5766 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005767 *Log << llvm::format("(%s:%d:%d) = %s",
5768 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5769 clang_getCString(KindSpelling))
5770 << llvm::format("(%s:%d:%d):%s%s",
5771 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5772 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005773 clang_disposeString(SearchFileName);
5774 clang_disposeString(ResultFileName);
5775 clang_disposeString(KindSpelling);
5776 clang_disposeString(USR);
5777
5778 CXCursor Definition = clang_getCursorDefinition(Result);
5779 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5780 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5781 CXString DefinitionKindSpelling
5782 = clang_getCursorKindSpelling(Definition.kind);
5783 CXFile DefinitionFile;
5784 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005785 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005786 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005787 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005788 *Log << llvm::format(" -> %s(%s:%d:%d)",
5789 clang_getCString(DefinitionKindSpelling),
5790 clang_getCString(DefinitionFileName),
5791 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 clang_disposeString(DefinitionFileName);
5793 clang_disposeString(DefinitionKindSpelling);
5794 }
5795 }
5796
5797 return Result;
5798}
5799
5800CXCursor clang_getNullCursor(void) {
5801 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5802}
5803
5804unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005805 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5806 // can't set consistently. For example, when visiting a DeclStmt we will set
5807 // it but we don't set it on the result of clang_getCursorDefinition for
5808 // a reference of the same declaration.
5809 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5810 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5811 // to provide that kind of info.
5812 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005813 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005814 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005815 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005816
Guy Benyei11169dd2012-12-18 14:30:41 +00005817 return X == Y;
5818}
5819
5820unsigned clang_hashCursor(CXCursor C) {
5821 unsigned Index = 0;
5822 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5823 Index = 1;
5824
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005825 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005826 std::make_pair(C.kind, C.data[Index]));
5827}
5828
5829unsigned clang_isInvalid(enum CXCursorKind K) {
5830 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5831}
5832
5833unsigned clang_isDeclaration(enum CXCursorKind K) {
5834 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005835 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5836}
5837
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005838unsigned clang_isInvalidDeclaration(CXCursor C) {
5839 if (clang_isDeclaration(C.kind)) {
5840 if (const Decl *D = getCursorDecl(C))
5841 return D->isInvalidDecl();
5842 }
5843
5844 return 0;
5845}
5846
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005847unsigned clang_isReference(enum CXCursorKind K) {
5848 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5849}
Guy Benyei11169dd2012-12-18 14:30:41 +00005850
5851unsigned clang_isExpression(enum CXCursorKind K) {
5852 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5853}
5854
5855unsigned clang_isStatement(enum CXCursorKind K) {
5856 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5857}
5858
5859unsigned clang_isAttribute(enum CXCursorKind K) {
5860 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5861}
5862
5863unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5864 return K == CXCursor_TranslationUnit;
5865}
5866
5867unsigned clang_isPreprocessing(enum CXCursorKind K) {
5868 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5869}
5870
5871unsigned clang_isUnexposed(enum CXCursorKind K) {
5872 switch (K) {
5873 case CXCursor_UnexposedDecl:
5874 case CXCursor_UnexposedExpr:
5875 case CXCursor_UnexposedStmt:
5876 case CXCursor_UnexposedAttr:
5877 return true;
5878 default:
5879 return false;
5880 }
5881}
5882
5883CXCursorKind clang_getCursorKind(CXCursor C) {
5884 return C.kind;
5885}
5886
5887CXSourceLocation clang_getCursorLocation(CXCursor C) {
5888 if (clang_isReference(C.kind)) {
5889 switch (C.kind) {
5890 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005891 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005892 = getCursorObjCSuperClassRef(C);
5893 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5894 }
5895
5896 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005897 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005898 = getCursorObjCProtocolRef(C);
5899 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5900 }
5901
5902 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005903 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 = getCursorObjCClassRef(C);
5905 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5906 }
5907
5908 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005909 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005910 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5911 }
5912
5913 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005914 std::pair<const TemplateDecl *, SourceLocation> P =
5915 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005916 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5917 }
5918
5919 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005920 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005921 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5922 }
5923
5924 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005925 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005926 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5927 }
5928
5929 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005930 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005931 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5932 }
5933
5934 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005935 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005936 if (!BaseSpec)
5937 return clang_getNullLocation();
5938
5939 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5940 return cxloc::translateSourceLocation(getCursorContext(C),
5941 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005942
Guy Benyei11169dd2012-12-18 14:30:41 +00005943 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005944 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005945 }
5946
5947 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005948 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005949 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5950 }
5951
5952 case CXCursor_OverloadedDeclRef:
5953 return cxloc::translateSourceLocation(getCursorContext(C),
5954 getCursorOverloadedDeclRef(C).second);
5955
5956 default:
5957 // FIXME: Need a way to enumerate all non-reference cases.
5958 llvm_unreachable("Missed a reference kind");
5959 }
5960 }
5961
5962 if (clang_isExpression(C.kind))
5963 return cxloc::translateSourceLocation(getCursorContext(C),
5964 getLocationFromExpr(getCursorExpr(C)));
5965
5966 if (clang_isStatement(C.kind))
5967 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005968 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005969
5970 if (C.kind == CXCursor_PreprocessingDirective) {
5971 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5972 return cxloc::translateSourceLocation(getCursorContext(C), L);
5973 }
5974
5975 if (C.kind == CXCursor_MacroExpansion) {
5976 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005977 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005978 return cxloc::translateSourceLocation(getCursorContext(C), L);
5979 }
5980
5981 if (C.kind == CXCursor_MacroDefinition) {
5982 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5983 return cxloc::translateSourceLocation(getCursorContext(C), L);
5984 }
5985
5986 if (C.kind == CXCursor_InclusionDirective) {
5987 SourceLocation L
5988 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5989 return cxloc::translateSourceLocation(getCursorContext(C), L);
5990 }
5991
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005992 if (clang_isAttribute(C.kind)) {
5993 SourceLocation L
5994 = cxcursor::getCursorAttr(C)->getLocation();
5995 return cxloc::translateSourceLocation(getCursorContext(C), L);
5996 }
5997
Guy Benyei11169dd2012-12-18 14:30:41 +00005998 if (!clang_isDeclaration(C.kind))
5999 return clang_getNullLocation();
6000
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006001 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006002 if (!D)
6003 return clang_getNullLocation();
6004
6005 SourceLocation Loc = D->getLocation();
6006 // FIXME: Multiple variables declared in a single declaration
6007 // currently lack the information needed to correctly determine their
6008 // ranges when accounting for the type-specifier. We use context
6009 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6010 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006011 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006012 if (!cxcursor::isFirstInDeclGroup(C))
6013 Loc = VD->getLocation();
6014 }
6015
6016 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006017 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006018 Loc = MD->getSelectorStartLoc();
6019
6020 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
6021}
6022
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00006023} // end extern "C"
6024
Guy Benyei11169dd2012-12-18 14:30:41 +00006025CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
6026 assert(TU);
6027
6028 // Guard against an invalid SourceLocation, or we may assert in one
6029 // of the following calls.
6030 if (SLoc.isInvalid())
6031 return clang_getNullCursor();
6032
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006033 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006034
6035 // Translate the given source location to make it point at the beginning of
6036 // the token under the cursor.
6037 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
6038 CXXUnit->getASTContext().getLangOpts());
6039
6040 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
6041 if (SLoc.isValid()) {
6042 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
6043 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
6044 /*VisitPreprocessorLast=*/true,
6045 /*VisitIncludedEntities=*/false,
6046 SourceLocation(SLoc));
6047 CursorVis.visitFileRegion();
6048 }
6049
6050 return Result;
6051}
6052
6053static SourceRange getRawCursorExtent(CXCursor C) {
6054 if (clang_isReference(C.kind)) {
6055 switch (C.kind) {
6056 case CXCursor_ObjCSuperClassRef:
6057 return getCursorObjCSuperClassRef(C).second;
6058
6059 case CXCursor_ObjCProtocolRef:
6060 return getCursorObjCProtocolRef(C).second;
6061
6062 case CXCursor_ObjCClassRef:
6063 return getCursorObjCClassRef(C).second;
6064
6065 case CXCursor_TypeRef:
6066 return getCursorTypeRef(C).second;
6067
6068 case CXCursor_TemplateRef:
6069 return getCursorTemplateRef(C).second;
6070
6071 case CXCursor_NamespaceRef:
6072 return getCursorNamespaceRef(C).second;
6073
6074 case CXCursor_MemberRef:
6075 return getCursorMemberRef(C).second;
6076
6077 case CXCursor_CXXBaseSpecifier:
6078 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6079
6080 case CXCursor_LabelRef:
6081 return getCursorLabelRef(C).second;
6082
6083 case CXCursor_OverloadedDeclRef:
6084 return getCursorOverloadedDeclRef(C).second;
6085
6086 case CXCursor_VariableRef:
6087 return getCursorVariableRef(C).second;
6088
6089 default:
6090 // FIXME: Need a way to enumerate all non-reference cases.
6091 llvm_unreachable("Missed a reference kind");
6092 }
6093 }
6094
6095 if (clang_isExpression(C.kind))
6096 return getCursorExpr(C)->getSourceRange();
6097
6098 if (clang_isStatement(C.kind))
6099 return getCursorStmt(C)->getSourceRange();
6100
6101 if (clang_isAttribute(C.kind))
6102 return getCursorAttr(C)->getRange();
6103
6104 if (C.kind == CXCursor_PreprocessingDirective)
6105 return cxcursor::getCursorPreprocessingDirective(C);
6106
6107 if (C.kind == CXCursor_MacroExpansion) {
6108 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006109 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006110 return TU->mapRangeFromPreamble(Range);
6111 }
6112
6113 if (C.kind == CXCursor_MacroDefinition) {
6114 ASTUnit *TU = getCursorASTUnit(C);
6115 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6116 return TU->mapRangeFromPreamble(Range);
6117 }
6118
6119 if (C.kind == CXCursor_InclusionDirective) {
6120 ASTUnit *TU = getCursorASTUnit(C);
6121 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6122 return TU->mapRangeFromPreamble(Range);
6123 }
6124
6125 if (C.kind == CXCursor_TranslationUnit) {
6126 ASTUnit *TU = getCursorASTUnit(C);
6127 FileID MainID = TU->getSourceManager().getMainFileID();
6128 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6129 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6130 return SourceRange(Start, End);
6131 }
6132
6133 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006134 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 if (!D)
6136 return SourceRange();
6137
6138 SourceRange R = D->getSourceRange();
6139 // FIXME: Multiple variables declared in a single declaration
6140 // currently lack the information needed to correctly determine their
6141 // ranges when accounting for the type-specifier. We use context
6142 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6143 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006144 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 if (!cxcursor::isFirstInDeclGroup(C))
6146 R.setBegin(VD->getLocation());
6147 }
6148 return R;
6149 }
6150 return SourceRange();
6151}
6152
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006153/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006154/// the decl-specifier-seq for declarations.
6155static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6156 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006157 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 if (!D)
6159 return SourceRange();
6160
6161 SourceRange R = D->getSourceRange();
6162
6163 // Adjust the start of the location for declarations preceded by
6164 // declaration specifiers.
6165 SourceLocation StartLoc;
6166 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6167 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006168 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006169 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006170 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006171 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006172 }
6173
6174 if (StartLoc.isValid() && R.getBegin().isValid() &&
6175 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6176 R.setBegin(StartLoc);
6177
6178 // FIXME: Multiple variables declared in a single declaration
6179 // currently lack the information needed to correctly determine their
6180 // ranges when accounting for the type-specifier. We use context
6181 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6182 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006183 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006184 if (!cxcursor::isFirstInDeclGroup(C))
6185 R.setBegin(VD->getLocation());
6186 }
6187
6188 return R;
6189 }
6190
6191 return getRawCursorExtent(C);
6192}
6193
Guy Benyei11169dd2012-12-18 14:30:41 +00006194CXSourceRange clang_getCursorExtent(CXCursor C) {
6195 SourceRange R = getRawCursorExtent(C);
6196 if (R.isInvalid())
6197 return clang_getNullRange();
6198
6199 return cxloc::translateSourceRange(getCursorContext(C), R);
6200}
6201
6202CXCursor clang_getCursorReferenced(CXCursor C) {
6203 if (clang_isInvalid(C.kind))
6204 return clang_getNullCursor();
6205
6206 CXTranslationUnit tu = getCursorTU(C);
6207 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006208 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006209 if (!D)
6210 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006211 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006212 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006213 if (const ObjCPropertyImplDecl *PropImpl =
6214 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006215 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6216 return MakeCXCursor(Property, tu);
6217
6218 return C;
6219 }
6220
6221 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006222 const Expr *E = getCursorExpr(C);
6223 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 if (D) {
6225 CXCursor declCursor = MakeCXCursor(D, tu);
6226 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6227 declCursor);
6228 return declCursor;
6229 }
6230
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006231 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 return MakeCursorOverloadedDeclRef(Ovl, tu);
6233
6234 return clang_getNullCursor();
6235 }
6236
6237 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006238 const Stmt *S = getCursorStmt(C);
6239 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006240 if (LabelDecl *label = Goto->getLabel())
6241 if (LabelStmt *labelS = label->getStmt())
6242 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6243
6244 return clang_getNullCursor();
6245 }
Richard Smith66a81862015-05-04 02:25:31 +00006246
Guy Benyei11169dd2012-12-18 14:30:41 +00006247 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006248 if (const MacroDefinitionRecord *Def =
6249 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006250 return MakeMacroDefinitionCursor(Def, tu);
6251 }
6252
6253 if (!clang_isReference(C.kind))
6254 return clang_getNullCursor();
6255
6256 switch (C.kind) {
6257 case CXCursor_ObjCSuperClassRef:
6258 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6259
6260 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006261 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6262 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006263 return MakeCXCursor(Def, tu);
6264
6265 return MakeCXCursor(Prot, tu);
6266 }
6267
6268 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006269 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6270 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006271 return MakeCXCursor(Def, tu);
6272
6273 return MakeCXCursor(Class, tu);
6274 }
6275
6276 case CXCursor_TypeRef:
6277 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6278
6279 case CXCursor_TemplateRef:
6280 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6281
6282 case CXCursor_NamespaceRef:
6283 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6284
6285 case CXCursor_MemberRef:
6286 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6287
6288 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006289 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6291 tu ));
6292 }
6293
6294 case CXCursor_LabelRef:
6295 // FIXME: We end up faking the "parent" declaration here because we
6296 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006297 return MakeCXCursor(getCursorLabelRef(C).first,
6298 cxtu::getASTUnit(tu)->getASTContext()
6299 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006300 tu);
6301
6302 case CXCursor_OverloadedDeclRef:
6303 return C;
6304
6305 case CXCursor_VariableRef:
6306 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6307
6308 default:
6309 // We would prefer to enumerate all non-reference cursor kinds here.
6310 llvm_unreachable("Unhandled reference cursor kind");
6311 }
6312}
6313
6314CXCursor clang_getCursorDefinition(CXCursor C) {
6315 if (clang_isInvalid(C.kind))
6316 return clang_getNullCursor();
6317
6318 CXTranslationUnit TU = getCursorTU(C);
6319
6320 bool WasReference = false;
6321 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6322 C = clang_getCursorReferenced(C);
6323 WasReference = true;
6324 }
6325
6326 if (C.kind == CXCursor_MacroExpansion)
6327 return clang_getCursorReferenced(C);
6328
6329 if (!clang_isDeclaration(C.kind))
6330 return clang_getNullCursor();
6331
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006332 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006333 if (!D)
6334 return clang_getNullCursor();
6335
6336 switch (D->getKind()) {
6337 // Declaration kinds that don't really separate the notions of
6338 // declaration and definition.
6339 case Decl::Namespace:
6340 case Decl::Typedef:
6341 case Decl::TypeAlias:
6342 case Decl::TypeAliasTemplate:
6343 case Decl::TemplateTypeParm:
6344 case Decl::EnumConstant:
6345 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006346 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006347 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006348 case Decl::IndirectField:
6349 case Decl::ObjCIvar:
6350 case Decl::ObjCAtDefsField:
6351 case Decl::ImplicitParam:
6352 case Decl::ParmVar:
6353 case Decl::NonTypeTemplateParm:
6354 case Decl::TemplateTemplateParm:
6355 case Decl::ObjCCategoryImpl:
6356 case Decl::ObjCImplementation:
6357 case Decl::AccessSpec:
6358 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006359 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006360 case Decl::ObjCPropertyImpl:
6361 case Decl::FileScopeAsm:
6362 case Decl::StaticAssert:
6363 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006364 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006365 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006366 case Decl::Label: // FIXME: Is this right??
6367 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006368 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006369 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006370 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006371 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006372 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006373 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006374 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006375 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006376 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006377 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006378 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006379 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006380 case Decl::Concept:
Tykerb0561b32019-11-17 11:41:55 +01006381 case Decl::LifetimeExtendedTemporary:
Saar Raza0f50d72020-01-18 09:11:43 +02006382 case Decl::RequiresExprBody:
Guy Benyei11169dd2012-12-18 14:30:41 +00006383 return C;
6384
6385 // Declaration kinds that don't make any sense here, but are
6386 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006387 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006388 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006389 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 break;
6391
6392 // Declaration kinds for which the definition is not resolvable.
6393 case Decl::UnresolvedUsingTypename:
6394 case Decl::UnresolvedUsingValue:
6395 break;
6396
6397 case Decl::UsingDirective:
6398 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6399 TU);
6400
6401 case Decl::NamespaceAlias:
6402 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6403
6404 case Decl::Enum:
6405 case Decl::Record:
6406 case Decl::CXXRecord:
6407 case Decl::ClassTemplateSpecialization:
6408 case Decl::ClassTemplatePartialSpecialization:
6409 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6410 return MakeCXCursor(Def, TU);
6411 return clang_getNullCursor();
6412
6413 case Decl::Function:
6414 case Decl::CXXMethod:
6415 case Decl::CXXConstructor:
6416 case Decl::CXXDestructor:
6417 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006418 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006419 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006420 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006421 return clang_getNullCursor();
6422 }
6423
Larisse Voufo39a1e502013-08-06 01:03:05 +00006424 case Decl::Var:
6425 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006426 case Decl::VarTemplatePartialSpecialization:
6427 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006428 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006429 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 return MakeCXCursor(Def, TU);
6431 return clang_getNullCursor();
6432 }
6433
6434 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006435 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006436 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6437 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6438 return clang_getNullCursor();
6439 }
6440
6441 case Decl::ClassTemplate: {
6442 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6443 ->getDefinition())
6444 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6445 TU);
6446 return clang_getNullCursor();
6447 }
6448
Larisse Voufo39a1e502013-08-06 01:03:05 +00006449 case Decl::VarTemplate: {
6450 if (VarDecl *Def =
6451 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6452 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6453 return clang_getNullCursor();
6454 }
6455
Guy Benyei11169dd2012-12-18 14:30:41 +00006456 case Decl::Using:
6457 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6458 D->getLocation(), TU);
6459
6460 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006461 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006462 return clang_getCursorDefinition(
6463 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6464 TU));
6465
6466 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006467 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006468 if (Method->isThisDeclarationADefinition())
6469 return C;
6470
6471 // Dig out the method definition in the associated
6472 // @implementation, if we have it.
6473 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006474 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6476 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6477 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6478 Method->isInstanceMethod()))
6479 if (Def->isThisDeclarationADefinition())
6480 return MakeCXCursor(Def, TU);
6481
6482 return clang_getNullCursor();
6483 }
6484
6485 case Decl::ObjCCategory:
6486 if (ObjCCategoryImplDecl *Impl
6487 = cast<ObjCCategoryDecl>(D)->getImplementation())
6488 return MakeCXCursor(Impl, TU);
6489 return clang_getNullCursor();
6490
6491 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006492 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006493 return MakeCXCursor(Def, TU);
6494 return clang_getNullCursor();
6495
6496 case Decl::ObjCInterface: {
6497 // There are two notions of a "definition" for an Objective-C
6498 // class: the interface and its implementation. When we resolved a
6499 // reference to an Objective-C class, produce the @interface as
6500 // the definition; when we were provided with the interface,
6501 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006502 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006503 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006504 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006505 return MakeCXCursor(Def, TU);
6506 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6507 return MakeCXCursor(Impl, TU);
6508 return clang_getNullCursor();
6509 }
6510
6511 case Decl::ObjCProperty:
6512 // FIXME: We don't really know where to find the
6513 // ObjCPropertyImplDecls that implement this property.
6514 return clang_getNullCursor();
6515
6516 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006517 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006518 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006519 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006520 return MakeCXCursor(Def, TU);
6521
6522 return clang_getNullCursor();
6523
6524 case Decl::Friend:
6525 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6526 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6527 return clang_getNullCursor();
6528
6529 case Decl::FriendTemplate:
6530 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6531 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6532 return clang_getNullCursor();
6533 }
6534
6535 return clang_getNullCursor();
6536}
6537
6538unsigned clang_isCursorDefinition(CXCursor C) {
6539 if (!clang_isDeclaration(C.kind))
6540 return 0;
6541
6542 return clang_getCursorDefinition(C) == C;
6543}
6544
6545CXCursor clang_getCanonicalCursor(CXCursor C) {
6546 if (!clang_isDeclaration(C.kind))
6547 return C;
6548
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006549 if (const Decl *D = getCursorDecl(C)) {
6550 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006551 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6552 return MakeCXCursor(CatD, getCursorTU(C));
6553
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006554 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6555 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 return MakeCXCursor(IFD, getCursorTU(C));
6557
6558 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6559 }
6560
6561 return C;
6562}
6563
6564int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6565 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6566}
6567
6568unsigned clang_getNumOverloadedDecls(CXCursor C) {
6569 if (C.kind != CXCursor_OverloadedDeclRef)
6570 return 0;
6571
6572 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006573 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006574 return E->getNumDecls();
6575
6576 if (OverloadedTemplateStorage *S
6577 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6578 return S->size();
6579
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006580 const Decl *D = Storage.get<const Decl *>();
6581 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006582 return Using->shadow_size();
6583
6584 return 0;
6585}
6586
6587CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6588 if (cursor.kind != CXCursor_OverloadedDeclRef)
6589 return clang_getNullCursor();
6590
6591 if (index >= clang_getNumOverloadedDecls(cursor))
6592 return clang_getNullCursor();
6593
6594 CXTranslationUnit TU = getCursorTU(cursor);
6595 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006596 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006597 return MakeCXCursor(E->decls_begin()[index], TU);
6598
6599 if (OverloadedTemplateStorage *S
6600 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6601 return MakeCXCursor(S->begin()[index], TU);
6602
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006603 const Decl *D = Storage.get<const Decl *>();
6604 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 // FIXME: This is, unfortunately, linear time.
6606 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6607 std::advance(Pos, index);
6608 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6609 }
6610
6611 return clang_getNullCursor();
6612}
6613
6614void clang_getDefinitionSpellingAndExtent(CXCursor C,
6615 const char **startBuf,
6616 const char **endBuf,
6617 unsigned *startLine,
6618 unsigned *startColumn,
6619 unsigned *endLine,
6620 unsigned *endColumn) {
6621 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006622 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006623 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6624
6625 SourceManager &SM = FD->getASTContext().getSourceManager();
6626 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6627 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6628 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6629 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6630 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6631 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6632}
6633
6634
6635CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6636 unsigned PieceIndex) {
6637 RefNamePieces Pieces;
6638
6639 switch (C.kind) {
6640 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006641 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006642 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6643 E->getQualifierLoc().getSourceRange());
6644 break;
6645
6646 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006647 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6648 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6649 Pieces =
6650 buildPieces(NameFlags, false, E->getNameInfo(),
6651 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6652 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006653 break;
6654
6655 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006656 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006657 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006658 const Expr *Callee = OCE->getCallee();
6659 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006660 Callee = ICE->getSubExpr();
6661
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006662 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006663 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6664 DRE->getQualifierLoc().getSourceRange());
6665 }
6666 break;
6667
6668 default:
6669 break;
6670 }
6671
6672 if (Pieces.empty()) {
6673 if (PieceIndex == 0)
6674 return clang_getCursorExtent(C);
6675 } else if (PieceIndex < Pieces.size()) {
6676 SourceRange R = Pieces[PieceIndex];
6677 if (R.isValid())
6678 return cxloc::translateSourceRange(getCursorContext(C), R);
6679 }
6680
6681 return clang_getNullRange();
6682}
6683
6684void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006685 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6686 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006687}
6688
6689void clang_executeOnThread(void (*fn)(void*), void *user_data,
6690 unsigned stack_size) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05006691 llvm::llvm_execute_on_thread(fn, user_data,
6692 stack_size == 0
6693 ? clang::DesiredStackSize
6694 : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006695}
6696
Guy Benyei11169dd2012-12-18 14:30:41 +00006697//===----------------------------------------------------------------------===//
6698// Token-based Operations.
6699//===----------------------------------------------------------------------===//
6700
6701/* CXToken layout:
6702 * int_data[0]: a CXTokenKind
6703 * int_data[1]: starting token location
6704 * int_data[2]: token length
6705 * int_data[3]: reserved
6706 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6707 * otherwise unused.
6708 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006709CXTokenKind clang_getTokenKind(CXToken CXTok) {
6710 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6711}
6712
6713CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6714 switch (clang_getTokenKind(CXTok)) {
6715 case CXToken_Identifier:
6716 case CXToken_Keyword:
6717 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006718 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006719 ->getNameStart());
6720
6721 case CXToken_Literal: {
6722 // We have stashed the starting pointer in the ptr_data field. Use it.
6723 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006724 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 }
6726
6727 case CXToken_Punctuation:
6728 case CXToken_Comment:
6729 break;
6730 }
6731
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006732 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006733 LOG_BAD_TU(TU);
6734 return cxstring::createEmpty();
6735 }
6736
Guy Benyei11169dd2012-12-18 14:30:41 +00006737 // We have to find the starting buffer pointer the hard way, by
6738 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006739 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006740 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006741 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006742
6743 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6744 std::pair<FileID, unsigned> LocInfo
6745 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6746 bool Invalid = false;
6747 StringRef Buffer
6748 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6749 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006750 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006751
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006752 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006753}
6754
6755CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006756 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006757 LOG_BAD_TU(TU);
6758 return clang_getNullLocation();
6759 }
6760
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006761 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006762 if (!CXXUnit)
6763 return clang_getNullLocation();
6764
6765 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6766 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6767}
6768
6769CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006770 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006771 LOG_BAD_TU(TU);
6772 return clang_getNullRange();
6773 }
6774
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006775 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006776 if (!CXXUnit)
6777 return clang_getNullRange();
6778
6779 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6780 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6781}
6782
6783static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6784 SmallVectorImpl<CXToken> &CXTokens) {
6785 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6786 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006787 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006788 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006789 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006790
6791 // Cannot tokenize across files.
6792 if (BeginLocInfo.first != EndLocInfo.first)
6793 return;
6794
6795 // Create a lexer
6796 bool Invalid = false;
6797 StringRef Buffer
6798 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6799 if (Invalid)
6800 return;
6801
6802 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6803 CXXUnit->getASTContext().getLangOpts(),
6804 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6805 Lex.SetCommentRetentionState(true);
6806
6807 // Lex tokens until we hit the end of the range.
6808 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6809 Token Tok;
6810 bool previousWasAt = false;
6811 do {
6812 // Lex the next token
6813 Lex.LexFromRawLexer(Tok);
6814 if (Tok.is(tok::eof))
6815 break;
6816
6817 // Initialize the CXToken.
6818 CXToken CXTok;
6819
6820 // - Common fields
6821 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6822 CXTok.int_data[2] = Tok.getLength();
6823 CXTok.int_data[3] = 0;
6824
6825 // - Kind-specific fields
6826 if (Tok.isLiteral()) {
6827 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006828 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006829 } else if (Tok.is(tok::raw_identifier)) {
6830 // Lookup the identifier to determine whether we have a keyword.
6831 IdentifierInfo *II
6832 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6833
6834 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6835 CXTok.int_data[0] = CXToken_Keyword;
6836 }
6837 else {
6838 CXTok.int_data[0] = Tok.is(tok::identifier)
6839 ? CXToken_Identifier
6840 : CXToken_Keyword;
6841 }
6842 CXTok.ptr_data = II;
6843 } else if (Tok.is(tok::comment)) {
6844 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006845 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006846 } else {
6847 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006848 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006849 }
6850 CXTokens.push_back(CXTok);
6851 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006852 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006853}
6854
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006855CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6856 LOG_FUNC_SECTION {
6857 *Log << TU << ' ' << Location;
6858 }
6859
6860 if (isNotUsableTU(TU)) {
6861 LOG_BAD_TU(TU);
6862 return NULL;
6863 }
6864
6865 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6866 if (!CXXUnit)
6867 return NULL;
6868
6869 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6870 if (Begin.isInvalid())
6871 return NULL;
6872 SourceManager &SM = CXXUnit->getSourceManager();
6873 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6874 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6875
6876 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6877
6878 SmallVector<CXToken, 32> CXTokens;
6879 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6880
6881 if (CXTokens.empty())
6882 return NULL;
6883
6884 CXTokens.resize(1);
6885 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6886
6887 memmove(Token, CXTokens.data(), sizeof(CXToken));
6888 return Token;
6889}
6890
Guy Benyei11169dd2012-12-18 14:30:41 +00006891void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6892 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006893 LOG_FUNC_SECTION {
6894 *Log << TU << ' ' << Range;
6895 }
6896
Guy Benyei11169dd2012-12-18 14:30:41 +00006897 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006898 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006899 if (NumTokens)
6900 *NumTokens = 0;
6901
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006902 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006903 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006904 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006905 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006906
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006907 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 if (!CXXUnit || !Tokens || !NumTokens)
6909 return;
6910
6911 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6912
6913 SourceRange R = cxloc::translateCXSourceRange(Range);
6914 if (R.isInvalid())
6915 return;
6916
6917 SmallVector<CXToken, 32> CXTokens;
6918 getTokens(CXXUnit, R, CXTokens);
6919
6920 if (CXTokens.empty())
6921 return;
6922
Serge Pavlov52525732018-02-21 02:02:39 +00006923 *Tokens = static_cast<CXToken *>(
6924 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006925 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6926 *NumTokens = CXTokens.size();
6927}
6928
6929void clang_disposeTokens(CXTranslationUnit TU,
6930 CXToken *Tokens, unsigned NumTokens) {
6931 free(Tokens);
6932}
6933
Guy Benyei11169dd2012-12-18 14:30:41 +00006934//===----------------------------------------------------------------------===//
6935// Token annotation APIs.
6936//===----------------------------------------------------------------------===//
6937
Guy Benyei11169dd2012-12-18 14:30:41 +00006938static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6939 CXCursor parent,
6940 CXClientData client_data);
6941static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6942 CXClientData client_data);
6943
6944namespace {
6945class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006946 CXToken *Tokens;
6947 CXCursor *Cursors;
6948 unsigned NumTokens;
6949 unsigned TokIdx;
6950 unsigned PreprocessingTokIdx;
6951 CursorVisitor AnnotateVis;
6952 SourceManager &SrcMgr;
6953 bool HasContextSensitiveKeywords;
6954
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006955 struct PostChildrenAction {
6956 CXCursor cursor;
6957 enum Action { Invalid, Ignore, Postpone } action;
6958 };
6959 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6960
Guy Benyei11169dd2012-12-18 14:30:41 +00006961 struct PostChildrenInfo {
6962 CXCursor Cursor;
6963 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006964 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006965 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006966 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006967 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006968 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006969
6970 CXToken &getTok(unsigned Idx) {
6971 assert(Idx < NumTokens);
6972 return Tokens[Idx];
6973 }
6974 const CXToken &getTok(unsigned Idx) const {
6975 assert(Idx < NumTokens);
6976 return Tokens[Idx];
6977 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006978 bool MoreTokens() const { return TokIdx < NumTokens; }
6979 unsigned NextToken() const { return TokIdx; }
6980 void AdvanceToken() { ++TokIdx; }
6981 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006982 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 }
6984 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006985 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006986 }
6987 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006988 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006989 }
6990
6991 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006992 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006993 SourceRange);
6994
6995public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006996 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006997 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006998 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006999 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007000 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00007001 AnnotateTokensVisitor, this,
7002 /*VisitPreprocessorLast=*/true,
7003 /*VisitIncludedEntities=*/false,
7004 RegionOfInterest,
7005 /*VisitDeclsOnly=*/false,
7006 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007007 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00007008 HasContextSensitiveKeywords(false) { }
7009
7010 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
7011 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007012 bool IsIgnoredChildCursor(CXCursor cursor) const;
7013 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
7014
Guy Benyei11169dd2012-12-18 14:30:41 +00007015 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007016 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
7017 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
7018
Guy Benyei11169dd2012-12-18 14:30:41 +00007019 void AnnotateTokens();
7020
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007021 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00007022 /// context-sensitive keywords.
7023 bool hasContextSensitiveKeywords() const {
7024 return HasContextSensitiveKeywords;
7025 }
7026
7027 ~AnnotateTokensWorker() {
7028 assert(PostChildrenInfos.empty());
7029 }
7030};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007031}
Guy Benyei11169dd2012-12-18 14:30:41 +00007032
7033void AnnotateTokensWorker::AnnotateTokens() {
7034 // Walk the AST within the region of interest, annotating tokens
7035 // along the way.
7036 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007037}
Guy Benyei11169dd2012-12-18 14:30:41 +00007038
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007039bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
7040 if (PostChildrenInfos.empty())
7041 return false;
7042
7043 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
7044 if (ChildAction.cursor == cursor &&
7045 ChildAction.action == PostChildrenAction::Ignore) {
7046 return true;
7047 }
7048 }
7049
7050 return false;
7051}
7052
7053const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
7054 if (!clang_isExpression(Cursor.kind))
7055 return nullptr;
7056
7057 const Expr *E = getCursorExpr(Cursor);
7058 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7059 const OverloadedOperatorKind Kind = OCE->getOperator();
7060 if (Kind == OO_Call || Kind == OO_Subscript)
7061 return OCE;
7062 }
7063
7064 return nullptr;
7065}
7066
7067AnnotateTokensWorker::PostChildrenActions
7068AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7069 PostChildrenActions actions;
7070
7071 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
7072 // visited before the arguments to the operator call. For the Call and
7073 // Subscript operator the range of this DeclRefExpr includes the whole call
7074 // expression, so that all tokens in that range would be mapped to the
7075 // operator function, including the tokens of the arguments. To avoid that,
7076 // ensure to visit this DeclRefExpr as last node.
7077 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7078 const Expr *Callee = OCE->getCallee();
7079 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7080 const Expr *SubExpr = ICE->getSubExpr();
7081 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007082 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007083 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7084
7085 // Visit the DeclRefExpr as last.
7086 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7087 actions.push_back({cxChild, PostChildrenAction::Postpone});
7088
7089 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7090 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7091 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7092 actions.push_back({cxChild, PostChildrenAction::Ignore});
7093 }
7094 }
7095 }
7096
7097 return actions;
7098}
7099
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007100static inline void updateCursorAnnotation(CXCursor &Cursor,
7101 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007102 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007103 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007104 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007105}
7106
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007107/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007108//// between the cursor location and the source range is the same as
7109/// \arg compResult.
7110///
7111/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7112/// Pass RangeOverlap to annotate tokens inside a range.
7113void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7114 RangeComparisonResult compResult,
7115 SourceRange range) {
7116 while (MoreTokens()) {
7117 const unsigned I = NextToken();
7118 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007119 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7120 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007121
7122 SourceLocation TokLoc = GetTokenLoc(I);
7123 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007124 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007125 AdvanceToken();
7126 continue;
7127 }
7128 break;
7129 }
7130}
7131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007132/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007133/// \returns true if it advanced beyond all macro tokens, false otherwise.
7134bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007135 CXCursor updateC,
7136 RangeComparisonResult compResult,
7137 SourceRange range) {
7138 assert(MoreTokens());
7139 assert(isFunctionMacroToken(NextToken()) &&
7140 "Should be called only for macro arg tokens");
7141
7142 // This works differently than annotateAndAdvanceTokens; because expanded
7143 // macro arguments can have arbitrary translation-unit source order, we do not
7144 // advance the token index one by one until a token fails the range test.
7145 // We only advance once past all of the macro arg tokens if all of them
7146 // pass the range test. If one of them fails we keep the token index pointing
7147 // at the start of the macro arg tokens so that the failing token will be
7148 // annotated by a subsequent annotation try.
7149
7150 bool atLeastOneCompFail = false;
7151
7152 unsigned I = NextToken();
7153 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7154 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7155 if (TokLoc.isFileID())
7156 continue; // not macro arg token, it's parens or comma.
7157 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7158 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7159 Cursors[I] = updateC;
7160 } else
7161 atLeastOneCompFail = true;
7162 }
7163
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007164 if (atLeastOneCompFail)
7165 return false;
7166
7167 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7168 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007169}
7170
7171enum CXChildVisitResult
7172AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007173 SourceRange cursorRange = getRawCursorExtent(cursor);
7174 if (cursorRange.isInvalid())
7175 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007176
7177 if (IsIgnoredChildCursor(cursor))
7178 return CXChildVisit_Continue;
7179
Guy Benyei11169dd2012-12-18 14:30:41 +00007180 if (!HasContextSensitiveKeywords) {
7181 // Objective-C properties can have context-sensitive keywords.
7182 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007183 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007184 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7185 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7186 }
7187 // Objective-C methods can have context-sensitive keywords.
7188 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7189 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007190 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007191 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7192 if (Method->getObjCDeclQualifier())
7193 HasContextSensitiveKeywords = true;
7194 else {
David Majnemer59f77922016-06-24 04:05:48 +00007195 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007196 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007197 HasContextSensitiveKeywords = true;
7198 break;
7199 }
7200 }
7201 }
7202 }
7203 }
7204 // C++ methods can have context-sensitive keywords.
7205 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007206 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007207 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7208 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7209 HasContextSensitiveKeywords = true;
7210 }
7211 }
7212 // C++ classes can have context-sensitive keywords.
7213 else if (cursor.kind == CXCursor_StructDecl ||
7214 cursor.kind == CXCursor_ClassDecl ||
7215 cursor.kind == CXCursor_ClassTemplate ||
7216 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007217 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007218 if (D->hasAttr<FinalAttr>())
7219 HasContextSensitiveKeywords = true;
7220 }
7221 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007222
7223 // Don't override a property annotation with its getter/setter method.
7224 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7225 parent.kind == CXCursor_ObjCPropertyDecl)
7226 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007227
7228 if (clang_isPreprocessing(cursor.kind)) {
7229 // Items in the preprocessing record are kept separate from items in
7230 // declarations, so we keep a separate token index.
7231 unsigned SavedTokIdx = TokIdx;
7232 TokIdx = PreprocessingTokIdx;
7233
7234 // Skip tokens up until we catch up to the beginning of the preprocessing
7235 // entry.
7236 while (MoreTokens()) {
7237 const unsigned I = NextToken();
7238 SourceLocation TokLoc = GetTokenLoc(I);
7239 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7240 case RangeBefore:
7241 AdvanceToken();
7242 continue;
7243 case RangeAfter:
7244 case RangeOverlap:
7245 break;
7246 }
7247 break;
7248 }
7249
7250 // Look at all of the tokens within this range.
7251 while (MoreTokens()) {
7252 const unsigned I = NextToken();
7253 SourceLocation TokLoc = GetTokenLoc(I);
7254 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7255 case RangeBefore:
7256 llvm_unreachable("Infeasible");
7257 case RangeAfter:
7258 break;
7259 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007260 // For macro expansions, just note where the beginning of the macro
7261 // expansion occurs.
7262 if (cursor.kind == CXCursor_MacroExpansion) {
7263 if (TokLoc == cursorRange.getBegin())
7264 Cursors[I] = cursor;
7265 AdvanceToken();
7266 break;
7267 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007268 // We may have already annotated macro names inside macro definitions.
7269 if (Cursors[I].kind != CXCursor_MacroExpansion)
7270 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007272 continue;
7273 }
7274 break;
7275 }
7276
7277 // Save the preprocessing token index; restore the non-preprocessing
7278 // token index.
7279 PreprocessingTokIdx = TokIdx;
7280 TokIdx = SavedTokIdx;
7281 return CXChildVisit_Recurse;
7282 }
7283
7284 if (cursorRange.isInvalid())
7285 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007286
7287 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007288 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 const enum CXCursorKind K = clang_getCursorKind(parent);
7290 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007291 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7292 // Attributes are annotated out-of-order, skip tokens until we reach it.
7293 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007294 ? clang_getNullCursor() : parent;
7295
7296 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7297
7298 // Avoid having the cursor of an expression "overwrite" the annotation of the
7299 // variable declaration that it belongs to.
7300 // This can happen for C++ constructor expressions whose range generally
7301 // include the variable declaration, e.g.:
7302 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007303 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007304 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007305 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007306 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007307 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7308 E->getBeginLoc() == D->getLocation() &&
7309 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007310 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007311 AdvanceToken();
7312 }
7313 }
7314 }
7315
7316 // Before recursing into the children keep some state that we are going
7317 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7318 // extra work after the child nodes are visited.
7319 // Note that we don't call VisitChildren here to avoid traversing statements
7320 // code-recursively which can blow the stack.
7321
7322 PostChildrenInfo Info;
7323 Info.Cursor = cursor;
7324 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007325 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007326 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007327 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007328 PostChildrenInfos.push_back(Info);
7329
7330 return CXChildVisit_Recurse;
7331}
7332
7333bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7334 if (PostChildrenInfos.empty())
7335 return false;
7336 const PostChildrenInfo &Info = PostChildrenInfos.back();
7337 if (!clang_equalCursors(Info.Cursor, cursor))
7338 return false;
7339
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007340 HandlePostPonedChildCursors(Info);
7341
Guy Benyei11169dd2012-12-18 14:30:41 +00007342 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7343 const unsigned AfterChildren = NextToken();
7344 SourceRange cursorRange = Info.CursorRange;
7345
7346 // Scan the tokens that are at the end of the cursor, but are not captured
7347 // but the child cursors.
7348 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7349
7350 // Scan the tokens that are at the beginning of the cursor, but are not
7351 // capture by the child cursors.
7352 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7353 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7354 break;
7355
7356 Cursors[I] = cursor;
7357 }
7358
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007359 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7360 // encountered the attribute cursor.
7361 if (clang_isAttribute(cursor.kind))
7362 TokIdx = Info.BeforeReachingCursorIdx;
7363
Guy Benyei11169dd2012-12-18 14:30:41 +00007364 PostChildrenInfos.pop_back();
7365 return false;
7366}
7367
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007368void AnnotateTokensWorker::HandlePostPonedChildCursors(
7369 const PostChildrenInfo &Info) {
7370 for (const auto &ChildAction : Info.ChildActions) {
7371 if (ChildAction.action == PostChildrenAction::Postpone) {
7372 HandlePostPonedChildCursor(ChildAction.cursor,
7373 Info.BeforeChildrenTokenIdx);
7374 }
7375 }
7376}
7377
7378void AnnotateTokensWorker::HandlePostPonedChildCursor(
7379 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007380 unsigned I = StartTokenIndex;
7381
7382 // The bracket tokens of a Call or Subscript operator are mapped to
7383 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7384 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7385 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007386 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7387 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007388 if (clang_Range_isNull(CXRefNameRange))
7389 break; // All ranges handled.
7390
7391 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7392 while (I < NumTokens) {
7393 const SourceLocation TokenLocation = GetTokenLoc(I);
7394 if (!TokenLocation.isValid())
7395 break;
7396
7397 // Adapt the end range, because LocationCompare() reports
7398 // RangeOverlap even for the not-inclusive end location.
7399 const SourceLocation fixedEnd =
7400 RefNameRange.getEnd().getLocWithOffset(-1);
7401 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7402
7403 const RangeComparisonResult ComparisonResult =
7404 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7405
7406 if (ComparisonResult == RangeOverlap) {
7407 Cursors[I++] = Cursor;
7408 } else if (ComparisonResult == RangeBefore) {
7409 ++I; // Not relevant token, check next one.
7410 } else if (ComparisonResult == RangeAfter) {
7411 break; // All tokens updated for current range, check next.
7412 }
7413 }
7414 }
7415}
7416
Guy Benyei11169dd2012-12-18 14:30:41 +00007417static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7418 CXCursor parent,
7419 CXClientData client_data) {
7420 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7421}
7422
7423static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7424 CXClientData client_data) {
7425 return static_cast<AnnotateTokensWorker*>(client_data)->
7426 postVisitChildren(cursor);
7427}
7428
7429namespace {
7430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007431/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007432/// and mark tokens that are macro arguments. This info is used by the
7433/// AnnotateTokensWorker.
7434class MarkMacroArgTokensVisitor {
7435 SourceManager &SM;
7436 CXToken *Tokens;
7437 unsigned NumTokens;
7438 unsigned CurIdx;
7439
7440public:
7441 MarkMacroArgTokensVisitor(SourceManager &SM,
7442 CXToken *tokens, unsigned numTokens)
7443 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7444
7445 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7446 if (cursor.kind != CXCursor_MacroExpansion)
7447 return CXChildVisit_Continue;
7448
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007449 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007450 if (macroRange.getBegin() == macroRange.getEnd())
7451 return CXChildVisit_Continue; // it's not a function macro.
7452
7453 for (; CurIdx < NumTokens; ++CurIdx) {
7454 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7455 macroRange.getBegin()))
7456 break;
7457 }
7458
7459 if (CurIdx == NumTokens)
7460 return CXChildVisit_Break;
7461
7462 for (; CurIdx < NumTokens; ++CurIdx) {
7463 SourceLocation tokLoc = getTokenLoc(CurIdx);
7464 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7465 break;
7466
7467 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7468 }
7469
7470 if (CurIdx == NumTokens)
7471 return CXChildVisit_Break;
7472
7473 return CXChildVisit_Continue;
7474 }
7475
7476private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007477 CXToken &getTok(unsigned Idx) {
7478 assert(Idx < NumTokens);
7479 return Tokens[Idx];
7480 }
7481 const CXToken &getTok(unsigned Idx) const {
7482 assert(Idx < NumTokens);
7483 return Tokens[Idx];
7484 }
7485
Guy Benyei11169dd2012-12-18 14:30:41 +00007486 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007487 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007488 }
7489
7490 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7491 // The third field is reserved and currently not used. Use it here
7492 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007493 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007494 }
7495};
7496
7497} // end anonymous namespace
7498
7499static CXChildVisitResult
7500MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7501 CXClientData client_data) {
7502 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7503 parent);
7504}
7505
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007506/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007507/// \returns true if lexing was finished, false otherwise.
7508static bool lexNext(Lexer &Lex, Token &Tok,
7509 unsigned &NextIdx, unsigned NumTokens) {
7510 if (NextIdx >= NumTokens)
7511 return true;
7512
7513 ++NextIdx;
7514 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007515 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007516}
7517
Guy Benyei11169dd2012-12-18 14:30:41 +00007518static void annotatePreprocessorTokens(CXTranslationUnit TU,
7519 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007520 CXCursor *Cursors,
7521 CXToken *Tokens,
7522 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007523 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007524
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007525 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007526 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7527 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007528 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007529 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007530 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007531
7532 if (BeginLocInfo.first != EndLocInfo.first)
7533 return;
7534
7535 StringRef Buffer;
7536 bool Invalid = false;
7537 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7538 if (Buffer.empty() || Invalid)
7539 return;
7540
7541 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7542 CXXUnit->getASTContext().getLangOpts(),
7543 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7544 Buffer.end());
7545 Lex.SetCommentRetentionState(true);
7546
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007547 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007548 // Lex tokens in raw mode until we hit the end of the range, to avoid
7549 // entering #includes or expanding macros.
7550 while (true) {
7551 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007552 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7553 break;
7554 unsigned TokIdx = NextIdx-1;
7555 assert(Tok.getLocation() ==
7556 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007557
7558 reprocess:
7559 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007560 // We have found a preprocessing directive. Annotate the tokens
7561 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007562 //
7563 // FIXME: Some simple tests here could identify macro definitions and
7564 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007565
7566 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007567 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7568 break;
7569
Craig Topper69186e72014-06-08 08:38:04 +00007570 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007571 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007572 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7573 break;
7574
7575 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007576 IdentifierInfo &II =
7577 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007578 SourceLocation MappedTokLoc =
7579 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7580 MI = getMacroInfo(II, MappedTokLoc, TU);
7581 }
7582 }
7583
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007584 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007585 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007586 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7587 finished = true;
7588 break;
7589 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007590 // If we are in a macro definition, check if the token was ever a
7591 // macro name and annotate it if that's the case.
7592 if (MI) {
7593 SourceLocation SaveLoc = Tok.getLocation();
7594 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007595 MacroDefinitionRecord *MacroDef =
7596 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007597 Tok.setLocation(SaveLoc);
7598 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007599 Cursors[NextIdx - 1] =
7600 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007601 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007602 } while (!Tok.isAtStartOfLine());
7603
7604 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7605 assert(TokIdx <= LastIdx);
7606 SourceLocation EndLoc =
7607 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7608 CXCursor Cursor =
7609 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7610
7611 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007612 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007613
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007614 if (finished)
7615 break;
7616 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007617 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007618 }
7619}
7620
7621// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007622static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7623 CXToken *Tokens, unsigned NumTokens,
7624 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007625 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007626 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7627 setThreadBackgroundPriority();
7628
7629 // Determine the region of interest, which contains all of the tokens.
7630 SourceRange RegionOfInterest;
7631 RegionOfInterest.setBegin(
7632 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7633 RegionOfInterest.setEnd(
7634 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7635 Tokens[NumTokens-1])));
7636
Guy Benyei11169dd2012-12-18 14:30:41 +00007637 // Relex the tokens within the source range to look for preprocessing
7638 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007639 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007640
7641 // If begin location points inside a macro argument, set it to the expansion
7642 // location so we can have the full context when annotating semantically.
7643 {
7644 SourceManager &SM = CXXUnit->getSourceManager();
7645 SourceLocation Loc =
7646 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7647 if (Loc.isMacroID())
7648 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7649 }
7650
Guy Benyei11169dd2012-12-18 14:30:41 +00007651 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7652 // Search and mark tokens that are macro argument expansions.
7653 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7654 Tokens, NumTokens);
7655 CursorVisitor MacroArgMarker(TU,
7656 MarkMacroArgTokensVisitorDelegate, &Visitor,
7657 /*VisitPreprocessorLast=*/true,
7658 /*VisitIncludedEntities=*/false,
7659 RegionOfInterest);
7660 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7661 }
7662
7663 // Annotate all of the source locations in the region of interest that map to
7664 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007665 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007666
7667 // FIXME: We use a ridiculous stack size here because the data-recursion
7668 // algorithm uses a large stack frame than the non-data recursive version,
7669 // and AnnotationTokensWorker currently transforms the data-recursion
7670 // algorithm back into a traditional recursion by explicitly calling
7671 // VisitChildren(). We will need to remove this explicit recursive call.
7672 W.AnnotateTokens();
7673
7674 // If we ran into any entities that involve context-sensitive keywords,
7675 // take another pass through the tokens to mark them as such.
7676 if (W.hasContextSensitiveKeywords()) {
7677 for (unsigned I = 0; I != NumTokens; ++I) {
7678 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7679 continue;
7680
7681 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7682 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007683 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007684 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7685 if (Property->getPropertyAttributesAsWritten() != 0 &&
7686 llvm::StringSwitch<bool>(II->getName())
7687 .Case("readonly", true)
7688 .Case("assign", true)
7689 .Case("unsafe_unretained", true)
7690 .Case("readwrite", true)
7691 .Case("retain", true)
7692 .Case("copy", true)
7693 .Case("nonatomic", true)
7694 .Case("atomic", true)
7695 .Case("getter", true)
7696 .Case("setter", true)
7697 .Case("strong", true)
7698 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007699 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 .Default(false))
7701 Tokens[I].int_data[0] = CXToken_Keyword;
7702 }
7703 continue;
7704 }
7705
7706 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7707 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7708 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7709 if (llvm::StringSwitch<bool>(II->getName())
7710 .Case("in", true)
7711 .Case("out", true)
7712 .Case("inout", true)
7713 .Case("oneway", true)
7714 .Case("bycopy", true)
7715 .Case("byref", true)
7716 .Default(false))
7717 Tokens[I].int_data[0] = CXToken_Keyword;
7718 continue;
7719 }
7720
7721 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7722 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7723 Tokens[I].int_data[0] = CXToken_Keyword;
7724 continue;
7725 }
7726 }
7727 }
7728}
7729
Guy Benyei11169dd2012-12-18 14:30:41 +00007730void clang_annotateTokens(CXTranslationUnit TU,
7731 CXToken *Tokens, unsigned NumTokens,
7732 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007733 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007734 LOG_BAD_TU(TU);
7735 return;
7736 }
7737 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007738 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007739 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007740 }
7741
7742 LOG_FUNC_SECTION {
7743 *Log << TU << ' ';
7744 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7745 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7746 *Log << clang_getRange(bloc, eloc);
7747 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007748
7749 // Any token we don't specifically annotate will have a NULL cursor.
7750 CXCursor C = clang_getNullCursor();
7751 for (unsigned I = 0; I != NumTokens; ++I)
7752 Cursors[I] = C;
7753
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007754 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007755 if (!CXXUnit)
7756 return;
7757
7758 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007759
7760 auto AnnotateTokensImpl = [=]() {
7761 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7762 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007763 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007764 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007765 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7766 }
7767}
7768
Guy Benyei11169dd2012-12-18 14:30:41 +00007769//===----------------------------------------------------------------------===//
7770// Operations for querying linkage of a cursor.
7771//===----------------------------------------------------------------------===//
7772
Guy Benyei11169dd2012-12-18 14:30:41 +00007773CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7774 if (!clang_isDeclaration(cursor.kind))
7775 return CXLinkage_Invalid;
7776
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007777 const Decl *D = cxcursor::getCursorDecl(cursor);
7778 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007779 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007780 case NoLinkage:
7781 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007782 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007783 case InternalLinkage: return CXLinkage_Internal;
7784 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007785 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007786 case ExternalLinkage: return CXLinkage_External;
7787 };
7788
7789 return CXLinkage_Invalid;
7790}
Guy Benyei11169dd2012-12-18 14:30:41 +00007791
7792//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007793// Operations for querying visibility of a cursor.
7794//===----------------------------------------------------------------------===//
7795
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007796CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7797 if (!clang_isDeclaration(cursor.kind))
7798 return CXVisibility_Invalid;
7799
7800 const Decl *D = cxcursor::getCursorDecl(cursor);
7801 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7802 switch (ND->getVisibility()) {
7803 case HiddenVisibility: return CXVisibility_Hidden;
7804 case ProtectedVisibility: return CXVisibility_Protected;
7805 case DefaultVisibility: return CXVisibility_Default;
7806 };
7807
7808 return CXVisibility_Invalid;
7809}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007810
7811//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007812// Operations for querying language of a cursor.
7813//===----------------------------------------------------------------------===//
7814
7815static CXLanguageKind getDeclLanguage(const Decl *D) {
7816 if (!D)
7817 return CXLanguage_C;
7818
7819 switch (D->getKind()) {
7820 default:
7821 break;
7822 case Decl::ImplicitParam:
7823 case Decl::ObjCAtDefsField:
7824 case Decl::ObjCCategory:
7825 case Decl::ObjCCategoryImpl:
7826 case Decl::ObjCCompatibleAlias:
7827 case Decl::ObjCImplementation:
7828 case Decl::ObjCInterface:
7829 case Decl::ObjCIvar:
7830 case Decl::ObjCMethod:
7831 case Decl::ObjCProperty:
7832 case Decl::ObjCPropertyImpl:
7833 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007834 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007835 return CXLanguage_ObjC;
7836 case Decl::CXXConstructor:
7837 case Decl::CXXConversion:
7838 case Decl::CXXDestructor:
7839 case Decl::CXXMethod:
7840 case Decl::CXXRecord:
7841 case Decl::ClassTemplate:
7842 case Decl::ClassTemplatePartialSpecialization:
7843 case Decl::ClassTemplateSpecialization:
7844 case Decl::Friend:
7845 case Decl::FriendTemplate:
7846 case Decl::FunctionTemplate:
7847 case Decl::LinkageSpec:
7848 case Decl::Namespace:
7849 case Decl::NamespaceAlias:
7850 case Decl::NonTypeTemplateParm:
7851 case Decl::StaticAssert:
7852 case Decl::TemplateTemplateParm:
7853 case Decl::TemplateTypeParm:
7854 case Decl::UnresolvedUsingTypename:
7855 case Decl::UnresolvedUsingValue:
7856 case Decl::Using:
7857 case Decl::UsingDirective:
7858 case Decl::UsingShadow:
7859 return CXLanguage_CPlusPlus;
7860 }
7861
7862 return CXLanguage_C;
7863}
7864
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007865static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7866 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007867 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007868
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007869 switch (D->getAvailability()) {
7870 case AR_Available:
7871 case AR_NotYetIntroduced:
7872 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007873 return getCursorAvailabilityForDecl(
7874 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007875 return CXAvailability_Available;
7876
7877 case AR_Deprecated:
7878 return CXAvailability_Deprecated;
7879
7880 case AR_Unavailable:
7881 return CXAvailability_NotAvailable;
7882 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007883
7884 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007885}
7886
Guy Benyei11169dd2012-12-18 14:30:41 +00007887enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7888 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007889 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7890 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007891
7892 return CXAvailability_Available;
7893}
7894
7895static CXVersion convertVersion(VersionTuple In) {
7896 CXVersion Out = { -1, -1, -1 };
7897 if (In.empty())
7898 return Out;
7899
7900 Out.Major = In.getMajor();
7901
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007902 Optional<unsigned> Minor = In.getMinor();
7903 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007904 Out.Minor = *Minor;
7905 else
7906 return Out;
7907
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007908 Optional<unsigned> Subminor = In.getSubminor();
7909 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007910 Out.Subminor = *Subminor;
7911
7912 return Out;
7913}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007914
Alex Lorenz1345ea22017-06-12 19:06:30 +00007915static void getCursorPlatformAvailabilityForDecl(
7916 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7917 int *always_unavailable, CXString *unavailable_message,
7918 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007919 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007920 for (auto A : D->attrs()) {
7921 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007922 HadAvailAttr = true;
7923 if (always_deprecated)
7924 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007925 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007926 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007927 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007928 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007929 continue;
7930 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007931
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007932 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007933 HadAvailAttr = true;
7934 if (always_unavailable)
7935 *always_unavailable = 1;
7936 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007937 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007938 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7939 }
7940 continue;
7941 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007942
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007943 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007944 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007945 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007946 }
7947 }
7948
7949 if (!HadAvailAttr)
7950 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7951 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007952 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7953 deprecated_message, always_unavailable, unavailable_message,
7954 AvailabilityAttrs);
7955
7956 if (AvailabilityAttrs.empty())
7957 return;
7958
Fangrui Song55fab262018-09-26 22:16:28 +00007959 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007960 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7961 return LHS->getPlatform()->getName() <
7962 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007963 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007964 ASTContext &Ctx = D->getASTContext();
7965 auto It = std::unique(
7966 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7967 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7968 if (LHS->getPlatform() != RHS->getPlatform())
7969 return false;
7970
7971 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7972 LHS->getDeprecated() == RHS->getDeprecated() &&
7973 LHS->getObsoleted() == RHS->getObsoleted() &&
7974 LHS->getMessage() == RHS->getMessage() &&
7975 LHS->getReplacement() == RHS->getReplacement())
7976 return true;
7977
7978 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7979 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7980 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7981 return false;
7982
7983 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7984 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7985
7986 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7987 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7988 if (LHS->getMessage().empty())
7989 LHS->setMessage(Ctx, RHS->getMessage());
7990 if (LHS->getReplacement().empty())
7991 LHS->setReplacement(Ctx, RHS->getReplacement());
7992 }
7993
7994 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7995 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7996 if (LHS->getMessage().empty())
7997 LHS->setMessage(Ctx, RHS->getMessage());
7998 if (LHS->getReplacement().empty())
7999 LHS->setReplacement(Ctx, RHS->getReplacement());
8000 }
8001
8002 return true;
8003 });
8004 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00008005}
8006
Alex Lorenz1345ea22017-06-12 19:06:30 +00008007int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00008008 CXString *deprecated_message,
8009 int *always_unavailable,
8010 CXString *unavailable_message,
8011 CXPlatformAvailability *availability,
8012 int availability_size) {
8013 if (always_deprecated)
8014 *always_deprecated = 0;
8015 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008016 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008017 if (always_unavailable)
8018 *always_unavailable = 0;
8019 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008020 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00008021
Guy Benyei11169dd2012-12-18 14:30:41 +00008022 if (!clang_isDeclaration(cursor.kind))
8023 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00008024
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008025 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00008026 if (!D)
8027 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00008028
Alex Lorenz1345ea22017-06-12 19:06:30 +00008029 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
8030 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
8031 always_unavailable, unavailable_message,
8032 AvailabilityAttrs);
8033 for (const auto &Avail :
8034 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
8035 .take_front(availability_size))) {
8036 availability[Avail.index()].Platform =
8037 cxstring::createDup(Avail.value()->getPlatform()->getName());
8038 availability[Avail.index()].Introduced =
8039 convertVersion(Avail.value()->getIntroduced());
8040 availability[Avail.index()].Deprecated =
8041 convertVersion(Avail.value()->getDeprecated());
8042 availability[Avail.index()].Obsoleted =
8043 convertVersion(Avail.value()->getObsoleted());
8044 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
8045 availability[Avail.index()].Message =
8046 cxstring::createDup(Avail.value()->getMessage());
8047 }
8048
8049 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008050}
Alex Lorenz1345ea22017-06-12 19:06:30 +00008051
Guy Benyei11169dd2012-12-18 14:30:41 +00008052void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
8053 clang_disposeString(availability->Platform);
8054 clang_disposeString(availability->Message);
8055}
8056
8057CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
8058 if (clang_isDeclaration(cursor.kind))
8059 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
8060
8061 return CXLanguage_Invalid;
8062}
8063
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00008064CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
8065 const Decl *D = cxcursor::getCursorDecl(cursor);
8066 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8067 switch (VD->getTLSKind()) {
8068 case VarDecl::TLS_None:
8069 return CXTLS_None;
8070 case VarDecl::TLS_Dynamic:
8071 return CXTLS_Dynamic;
8072 case VarDecl::TLS_Static:
8073 return CXTLS_Static;
8074 }
8075 }
8076
8077 return CXTLS_None;
8078}
8079
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008080 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008081 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008082 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008083static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008084 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008085 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008086
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008087 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008088 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8089 return FunTmpl;
8090
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008091 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008092 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8093 return ClassTmpl;
8094
8095 return D;
8096}
8097
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008098
8099enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8100 StorageClass sc = SC_None;
8101 const Decl *D = getCursorDecl(C);
8102 if (D) {
8103 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8104 sc = FD->getStorageClass();
8105 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8106 sc = VD->getStorageClass();
8107 } else {
8108 return CX_SC_Invalid;
8109 }
8110 } else {
8111 return CX_SC_Invalid;
8112 }
8113 switch (sc) {
8114 case SC_None:
8115 return CX_SC_None;
8116 case SC_Extern:
8117 return CX_SC_Extern;
8118 case SC_Static:
8119 return CX_SC_Static;
8120 case SC_PrivateExtern:
8121 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008122 case SC_Auto:
8123 return CX_SC_Auto;
8124 case SC_Register:
8125 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008126 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008127 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008128}
8129
Guy Benyei11169dd2012-12-18 14:30:41 +00008130CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8131 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008132 if (const Decl *D = getCursorDecl(cursor)) {
8133 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 if (!DC)
8135 return clang_getNullCursor();
8136
8137 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8138 getCursorTU(cursor));
8139 }
8140 }
8141
8142 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008143 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008144 return MakeCXCursor(D, getCursorTU(cursor));
8145 }
8146
8147 return clang_getNullCursor();
8148}
8149
8150CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8151 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008152 if (const Decl *D = getCursorDecl(cursor)) {
8153 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008154 if (!DC)
8155 return clang_getNullCursor();
8156
8157 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8158 getCursorTU(cursor));
8159 }
8160 }
8161
8162 // FIXME: Note that we can't easily compute the lexical context of a
8163 // statement or expression, so we return nothing.
8164 return clang_getNullCursor();
8165}
8166
8167CXFile clang_getIncludedFile(CXCursor cursor) {
8168 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008169 return nullptr;
8170
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008171 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008172 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008173}
8174
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008175unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8176 if (C.kind != CXCursor_ObjCPropertyDecl)
8177 return CXObjCPropertyAttr_noattr;
8178
8179 unsigned Result = CXObjCPropertyAttr_noattr;
8180 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8181 ObjCPropertyDecl::PropertyAttributeKind Attr =
8182 PD->getPropertyAttributesAsWritten();
8183
8184#define SET_CXOBJCPROP_ATTR(A) \
8185 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8186 Result |= CXObjCPropertyAttr_##A
8187 SET_CXOBJCPROP_ATTR(readonly);
8188 SET_CXOBJCPROP_ATTR(getter);
8189 SET_CXOBJCPROP_ATTR(assign);
8190 SET_CXOBJCPROP_ATTR(readwrite);
8191 SET_CXOBJCPROP_ATTR(retain);
8192 SET_CXOBJCPROP_ATTR(copy);
8193 SET_CXOBJCPROP_ATTR(nonatomic);
8194 SET_CXOBJCPROP_ATTR(setter);
8195 SET_CXOBJCPROP_ATTR(atomic);
8196 SET_CXOBJCPROP_ATTR(weak);
8197 SET_CXOBJCPROP_ATTR(strong);
8198 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008199 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008200#undef SET_CXOBJCPROP_ATTR
8201
8202 return Result;
8203}
8204
Michael Wu6e88f532018-08-03 05:38:29 +00008205CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8206 if (C.kind != CXCursor_ObjCPropertyDecl)
8207 return cxstring::createNull();
8208
8209 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8210 Selector sel = PD->getGetterName();
8211 if (sel.isNull())
8212 return cxstring::createNull();
8213
8214 return cxstring::createDup(sel.getAsString());
8215}
8216
8217CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8218 if (C.kind != CXCursor_ObjCPropertyDecl)
8219 return cxstring::createNull();
8220
8221 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8222 Selector sel = PD->getSetterName();
8223 if (sel.isNull())
8224 return cxstring::createNull();
8225
8226 return cxstring::createDup(sel.getAsString());
8227}
8228
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008229unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8230 if (!clang_isDeclaration(C.kind))
8231 return CXObjCDeclQualifier_None;
8232
8233 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8234 const Decl *D = getCursorDecl(C);
8235 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8236 QT = MD->getObjCDeclQualifier();
8237 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8238 QT = PD->getObjCDeclQualifier();
8239 if (QT == Decl::OBJC_TQ_None)
8240 return CXObjCDeclQualifier_None;
8241
8242 unsigned Result = CXObjCDeclQualifier_None;
8243 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8244 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8245 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8246 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8247 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8248 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8249
8250 return Result;
8251}
8252
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008253unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8254 if (!clang_isDeclaration(C.kind))
8255 return 0;
8256
8257 const Decl *D = getCursorDecl(C);
8258 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8259 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8260 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8261 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8262
8263 return 0;
8264}
8265
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008266unsigned clang_Cursor_isVariadic(CXCursor C) {
8267 if (!clang_isDeclaration(C.kind))
8268 return 0;
8269
8270 const Decl *D = getCursorDecl(C);
8271 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8272 return FD->isVariadic();
8273 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8274 return MD->isVariadic();
8275
8276 return 0;
8277}
8278
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008279unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8280 CXString *language, CXString *definedIn,
8281 unsigned *isGenerated) {
8282 if (!clang_isDeclaration(C.kind))
8283 return 0;
8284
8285 const Decl *D = getCursorDecl(C);
8286
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008287 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008288 if (language)
8289 *language = cxstring::createDup(attr->getLanguage());
8290 if (definedIn)
8291 *definedIn = cxstring::createDup(attr->getDefinedIn());
8292 if (isGenerated)
8293 *isGenerated = attr->getGeneratedDeclaration();
8294 return 1;
8295 }
8296 return 0;
8297}
8298
Guy Benyei11169dd2012-12-18 14:30:41 +00008299CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8300 if (!clang_isDeclaration(C.kind))
8301 return clang_getNullRange();
8302
8303 const Decl *D = getCursorDecl(C);
8304 ASTContext &Context = getCursorContext(C);
8305 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8306 if (!RC)
8307 return clang_getNullRange();
8308
8309 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8310}
8311
8312CXString clang_Cursor_getRawCommentText(CXCursor C) {
8313 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008314 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008315
8316 const Decl *D = getCursorDecl(C);
8317 ASTContext &Context = getCursorContext(C);
8318 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8319 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8320 StringRef();
8321
8322 // Don't duplicate the string because RawText points directly into source
8323 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008324 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008325}
8326
8327CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8328 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008329 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008330
8331 const Decl *D = getCursorDecl(C);
8332 const ASTContext &Context = getCursorContext(C);
8333 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8334
8335 if (RC) {
8336 StringRef BriefText = RC->getBriefText(Context);
8337
8338 // Don't duplicate the string because RawComment ensures that this memory
8339 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008340 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008341 }
8342
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008343 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008344}
8345
Guy Benyei11169dd2012-12-18 14:30:41 +00008346CXModule clang_Cursor_getModule(CXCursor C) {
8347 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008348 if (const ImportDecl *ImportD =
8349 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008350 return ImportD->getImportedModule();
8351 }
8352
Craig Topper69186e72014-06-08 08:38:04 +00008353 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008354}
8355
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008356CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8357 if (isNotUsableTU(TU)) {
8358 LOG_BAD_TU(TU);
8359 return nullptr;
8360 }
8361 if (!File)
8362 return nullptr;
8363 FileEntry *FE = static_cast<FileEntry *>(File);
8364
8365 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8366 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8367 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8368
Richard Smithfeb54b62014-10-23 02:01:19 +00008369 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008370}
8371
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008372CXFile clang_Module_getASTFile(CXModule CXMod) {
8373 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008374 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008375 Module *Mod = static_cast<Module*>(CXMod);
8376 return const_cast<FileEntry *>(Mod->getASTFile());
8377}
8378
Guy Benyei11169dd2012-12-18 14:30:41 +00008379CXModule clang_Module_getParent(CXModule CXMod) {
8380 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008381 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008382 Module *Mod = static_cast<Module*>(CXMod);
8383 return Mod->Parent;
8384}
8385
8386CXString clang_Module_getName(CXModule CXMod) {
8387 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008388 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008389 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008390 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008391}
8392
8393CXString clang_Module_getFullName(CXModule CXMod) {
8394 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008395 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008396 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008397 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008398}
8399
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008400int clang_Module_isSystem(CXModule CXMod) {
8401 if (!CXMod)
8402 return 0;
8403 Module *Mod = static_cast<Module*>(CXMod);
8404 return Mod->IsSystem;
8405}
8406
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008407unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8408 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008409 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008410 LOG_BAD_TU(TU);
8411 return 0;
8412 }
8413 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008414 return 0;
8415 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008416 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8417 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8418 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008419}
8420
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008421CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8422 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008423 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008424 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008425 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008426 }
8427 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008428 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008429 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008430 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008431
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008432 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8433 if (Index < TopHeaders.size())
8434 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008435
Craig Topper69186e72014-06-08 08:38:04 +00008436 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008437}
8438
Guy Benyei11169dd2012-12-18 14:30:41 +00008439//===----------------------------------------------------------------------===//
8440// C++ AST instrospection.
8441//===----------------------------------------------------------------------===//
8442
Jonathan Coe29565352016-04-27 12:48:25 +00008443unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8444 if (!clang_isDeclaration(C.kind))
8445 return 0;
8446
8447 const Decl *D = cxcursor::getCursorDecl(C);
8448 const CXXConstructorDecl *Constructor =
8449 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8450 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8451}
8452
8453unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8454 if (!clang_isDeclaration(C.kind))
8455 return 0;
8456
8457 const Decl *D = cxcursor::getCursorDecl(C);
8458 const CXXConstructorDecl *Constructor =
8459 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8460 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8461}
8462
8463unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8464 if (!clang_isDeclaration(C.kind))
8465 return 0;
8466
8467 const Decl *D = cxcursor::getCursorDecl(C);
8468 const CXXConstructorDecl *Constructor =
8469 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8470 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8471}
8472
8473unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8474 if (!clang_isDeclaration(C.kind))
8475 return 0;
8476
8477 const Decl *D = cxcursor::getCursorDecl(C);
8478 const CXXConstructorDecl *Constructor =
8479 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8480 // Passing 'false' excludes constructors marked 'explicit'.
8481 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8482}
8483
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008484unsigned clang_CXXField_isMutable(CXCursor C) {
8485 if (!clang_isDeclaration(C.kind))
8486 return 0;
8487
8488 if (const auto D = cxcursor::getCursorDecl(C))
8489 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8490 return FD->isMutable() ? 1 : 0;
8491 return 0;
8492}
8493
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008494unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8495 if (!clang_isDeclaration(C.kind))
8496 return 0;
8497
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008498 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008499 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008500 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008501 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8502}
8503
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008504unsigned clang_CXXMethod_isConst(CXCursor C) {
8505 if (!clang_isDeclaration(C.kind))
8506 return 0;
8507
8508 const Decl *D = cxcursor::getCursorDecl(C);
8509 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008510 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008511 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008512}
8513
Jonathan Coe29565352016-04-27 12:48:25 +00008514unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8515 if (!clang_isDeclaration(C.kind))
8516 return 0;
8517
8518 const Decl *D = cxcursor::getCursorDecl(C);
8519 const CXXMethodDecl *Method =
8520 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8521 return (Method && Method->isDefaulted()) ? 1 : 0;
8522}
8523
Guy Benyei11169dd2012-12-18 14:30:41 +00008524unsigned clang_CXXMethod_isStatic(CXCursor C) {
8525 if (!clang_isDeclaration(C.kind))
8526 return 0;
8527
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008528 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008529 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008530 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008531 return (Method && Method->isStatic()) ? 1 : 0;
8532}
8533
8534unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8535 if (!clang_isDeclaration(C.kind))
8536 return 0;
8537
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008538 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008539 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008540 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008541 return (Method && Method->isVirtual()) ? 1 : 0;
8542}
Guy Benyei11169dd2012-12-18 14:30:41 +00008543
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008544unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8545 if (!clang_isDeclaration(C.kind))
8546 return 0;
8547
8548 const auto *D = cxcursor::getCursorDecl(C);
8549 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8550 if (RD)
8551 RD = RD->getDefinition();
8552 return (RD && RD->isAbstract()) ? 1 : 0;
8553}
8554
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008555unsigned clang_EnumDecl_isScoped(CXCursor C) {
8556 if (!clang_isDeclaration(C.kind))
8557 return 0;
8558
8559 const Decl *D = cxcursor::getCursorDecl(C);
8560 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8561 return (Enum && Enum->isScoped()) ? 1 : 0;
8562}
8563
Guy Benyei11169dd2012-12-18 14:30:41 +00008564//===----------------------------------------------------------------------===//
8565// Attribute introspection.
8566//===----------------------------------------------------------------------===//
8567
Guy Benyei11169dd2012-12-18 14:30:41 +00008568CXType clang_getIBOutletCollectionType(CXCursor C) {
8569 if (C.kind != CXCursor_IBOutletCollectionAttr)
8570 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8571
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008572 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008573 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8574
8575 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8576}
Guy Benyei11169dd2012-12-18 14:30:41 +00008577
8578//===----------------------------------------------------------------------===//
8579// Inspecting memory usage.
8580//===----------------------------------------------------------------------===//
8581
8582typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8583
8584static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8585 enum CXTUResourceUsageKind k,
8586 unsigned long amount) {
8587 CXTUResourceUsageEntry entry = { k, amount };
8588 entries.push_back(entry);
8589}
8590
Guy Benyei11169dd2012-12-18 14:30:41 +00008591const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8592 const char *str = "";
8593 switch (kind) {
8594 case CXTUResourceUsage_AST:
8595 str = "ASTContext: expressions, declarations, and types";
8596 break;
8597 case CXTUResourceUsage_Identifiers:
8598 str = "ASTContext: identifiers";
8599 break;
8600 case CXTUResourceUsage_Selectors:
8601 str = "ASTContext: selectors";
8602 break;
8603 case CXTUResourceUsage_GlobalCompletionResults:
8604 str = "Code completion: cached global results";
8605 break;
8606 case CXTUResourceUsage_SourceManagerContentCache:
8607 str = "SourceManager: content cache allocator";
8608 break;
8609 case CXTUResourceUsage_AST_SideTables:
8610 str = "ASTContext: side tables";
8611 break;
8612 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8613 str = "SourceManager: malloc'ed memory buffers";
8614 break;
8615 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8616 str = "SourceManager: mmap'ed memory buffers";
8617 break;
8618 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8619 str = "ExternalASTSource: malloc'ed memory buffers";
8620 break;
8621 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8622 str = "ExternalASTSource: mmap'ed memory buffers";
8623 break;
8624 case CXTUResourceUsage_Preprocessor:
8625 str = "Preprocessor: malloc'ed memory";
8626 break;
8627 case CXTUResourceUsage_PreprocessingRecord:
8628 str = "Preprocessor: PreprocessingRecord";
8629 break;
8630 case CXTUResourceUsage_SourceManager_DataStructures:
8631 str = "SourceManager: data structures and tables";
8632 break;
8633 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8634 str = "Preprocessor: header search tables";
8635 break;
8636 }
8637 return str;
8638}
8639
8640CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008641 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008642 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008643 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008644 return usage;
8645 }
8646
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008647 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008648 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008649 ASTContext &astContext = astUnit->getASTContext();
8650
8651 // How much memory is used by AST nodes and types?
8652 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8653 (unsigned long) astContext.getASTAllocatedMemory());
8654
8655 // How much memory is used by identifiers?
8656 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8657 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8658
8659 // How much memory is used for selectors?
8660 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8661 (unsigned long) astContext.Selectors.getTotalMemory());
8662
8663 // How much memory is used by ASTContext's side tables?
8664 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8665 (unsigned long) astContext.getSideTableAllocatedMemory());
8666
8667 // How much memory is used for caching global code completion results?
8668 unsigned long completionBytes = 0;
8669 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008670 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008671 completionBytes = completionAllocator->getTotalMemory();
8672 }
8673 createCXTUResourceUsageEntry(*entries,
8674 CXTUResourceUsage_GlobalCompletionResults,
8675 completionBytes);
8676
8677 // How much memory is being used by SourceManager's content cache?
8678 createCXTUResourceUsageEntry(*entries,
8679 CXTUResourceUsage_SourceManagerContentCache,
8680 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8681
8682 // How much memory is being used by the MemoryBuffer's in SourceManager?
8683 const SourceManager::MemoryBufferSizes &srcBufs =
8684 astUnit->getSourceManager().getMemoryBufferSizes();
8685
8686 createCXTUResourceUsageEntry(*entries,
8687 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8688 (unsigned long) srcBufs.malloc_bytes);
8689 createCXTUResourceUsageEntry(*entries,
8690 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8691 (unsigned long) srcBufs.mmap_bytes);
8692 createCXTUResourceUsageEntry(*entries,
8693 CXTUResourceUsage_SourceManager_DataStructures,
8694 (unsigned long) astContext.getSourceManager()
8695 .getDataStructureSizes());
8696
8697 // How much memory is being used by the ExternalASTSource?
8698 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8699 const ExternalASTSource::MemoryBufferSizes &sizes =
8700 esrc->getMemoryBufferSizes();
8701
8702 createCXTUResourceUsageEntry(*entries,
8703 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8704 (unsigned long) sizes.malloc_bytes);
8705 createCXTUResourceUsageEntry(*entries,
8706 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8707 (unsigned long) sizes.mmap_bytes);
8708 }
8709
8710 // How much memory is being used by the Preprocessor?
8711 Preprocessor &pp = astUnit->getPreprocessor();
8712 createCXTUResourceUsageEntry(*entries,
8713 CXTUResourceUsage_Preprocessor,
8714 pp.getTotalMemory());
8715
8716 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8717 createCXTUResourceUsageEntry(*entries,
8718 CXTUResourceUsage_PreprocessingRecord,
8719 pRec->getTotalMemory());
8720 }
8721
8722 createCXTUResourceUsageEntry(*entries,
8723 CXTUResourceUsage_Preprocessor_HeaderSearch,
8724 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008725
Guy Benyei11169dd2012-12-18 14:30:41 +00008726 CXTUResourceUsage usage = { (void*) entries.get(),
8727 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008728 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008729 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008730 return usage;
8731}
8732
8733void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8734 if (usage.data)
8735 delete (MemUsageEntries*) usage.data;
8736}
8737
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008738CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8739 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008740 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008741 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008742
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008743 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008744 LOG_BAD_TU(TU);
8745 return skipped;
8746 }
8747
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008748 if (!file)
8749 return skipped;
8750
8751 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8752 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8753 if (!ppRec)
8754 return skipped;
8755
8756 ASTContext &Ctx = astUnit->getASTContext();
8757 SourceManager &sm = Ctx.getSourceManager();
8758 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8759 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008760 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008761
8762 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8763 std::vector<SourceRange> wantedRanges;
8764 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8765 i != ei; ++i) {
8766 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8767 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008768 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8769 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008770 }
8771
8772 skipped->count = wantedRanges.size();
8773 skipped->ranges = new CXSourceRange[skipped->count];
8774 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8775 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8776
8777 return skipped;
8778}
8779
Cameron Desrochersd8091282016-08-18 15:43:55 +00008780CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8781 CXSourceRangeList *skipped = new CXSourceRangeList;
8782 skipped->count = 0;
8783 skipped->ranges = nullptr;
8784
8785 if (isNotUsableTU(TU)) {
8786 LOG_BAD_TU(TU);
8787 return skipped;
8788 }
8789
8790 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8791 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8792 if (!ppRec)
8793 return skipped;
8794
8795 ASTContext &Ctx = astUnit->getASTContext();
8796
8797 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8798
8799 skipped->count = SkippedRanges.size();
8800 skipped->ranges = new CXSourceRange[skipped->count];
8801 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8802 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8803
8804 return skipped;
8805}
8806
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008807void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8808 if (ranges) {
8809 delete[] ranges->ranges;
8810 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008811 }
8812}
8813
Guy Benyei11169dd2012-12-18 14:30:41 +00008814void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8815 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8816 for (unsigned I = 0; I != Usage.numEntries; ++I)
8817 fprintf(stderr, " %s: %lu\n",
8818 clang_getTUResourceUsageName(Usage.entries[I].kind),
8819 Usage.entries[I].amount);
8820
8821 clang_disposeCXTUResourceUsage(Usage);
8822}
8823
8824//===----------------------------------------------------------------------===//
8825// Misc. utility functions.
8826//===----------------------------------------------------------------------===//
8827
Richard Smith0a7b2972018-07-03 21:34:13 +00008828/// Default to using our desired 8 MB stack size on "safety" threads.
8829static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008830
8831namespace clang {
8832
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008833bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008834 unsigned Size) {
8835 if (!Size)
8836 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008837 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008838 return CRC.RunSafelyOnThread(Fn, Size);
8839 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008840}
8841
8842unsigned GetSafetyThreadStackSize() {
8843 return SafetyStackThreadSize;
8844}
8845
8846void SetSafetyThreadStackSize(unsigned Value) {
8847 SafetyStackThreadSize = Value;
8848}
8849
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008850}
Guy Benyei11169dd2012-12-18 14:30:41 +00008851
8852void clang::setThreadBackgroundPriority() {
8853 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8854 return;
8855
Nico Weber18cfd9f2019-04-21 19:18:41 +00008856#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008857 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008858#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008859}
8860
8861void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8862 if (!Unit)
8863 return;
8864
8865 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8866 DEnd = Unit->stored_diag_end();
8867 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008868 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008869 CXString Msg = clang_formatDiagnostic(&Diag,
8870 clang_defaultDiagnosticDisplayOptions());
8871 fprintf(stderr, "%s\n", clang_getCString(Msg));
8872 clang_disposeString(Msg);
8873 }
Nico Weber1865df42018-04-27 19:11:14 +00008874#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008875 // On Windows, force a flush, since there may be multiple copies of
8876 // stderr and stdout in the file system, all with different buffers
8877 // but writing to the same device.
8878 fflush(stderr);
8879#endif
8880}
8881
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008882MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8883 SourceLocation MacroDefLoc,
8884 CXTranslationUnit TU){
8885 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008886 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008887 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008888 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008889
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008890 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008891 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008892 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008893 if (MD) {
8894 for (MacroDirective::DefInfo
8895 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8896 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8897 return Def.getMacroInfo();
8898 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008899 }
8900
Craig Topper69186e72014-06-08 08:38:04 +00008901 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008902}
8903
Richard Smith66a81862015-05-04 02:25:31 +00008904const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008905 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008906 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008907 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008908 const IdentifierInfo *II = MacroDef->getName();
8909 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008910 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008911
8912 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8913}
8914
Richard Smith66a81862015-05-04 02:25:31 +00008915MacroDefinitionRecord *
8916cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8917 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008918 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008919 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008920 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008921 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008922
8923 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008924 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008925 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8926 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008927 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008928
8929 // Check that the token is inside the definition and not its argument list.
8930 SourceManager &SM = Unit->getSourceManager();
8931 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008932 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008933 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008934 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008935
8936 Preprocessor &PP = Unit->getPreprocessor();
8937 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8938 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008939 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008940
Alp Toker2d57cea2014-05-17 04:53:25 +00008941 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008942 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008943 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008944
8945 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008946 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008947 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008948
Richard Smith20e883e2015-04-29 23:20:19 +00008949 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008950 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008951 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008952
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008953 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008954}
8955
Richard Smith66a81862015-05-04 02:25:31 +00008956MacroDefinitionRecord *
8957cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8958 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008959 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008960 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008961
8962 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008963 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008964 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008965 Preprocessor &PP = Unit->getPreprocessor();
8966 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008967 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008968 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8969 Token Tok;
8970 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008971 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008972
8973 return checkForMacroInMacroDefinition(MI, Tok, TU);
8974}
8975
Guy Benyei11169dd2012-12-18 14:30:41 +00008976CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008977 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008978}
8979
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008980Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8981 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008982 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008983 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008984 if (Unit->isMainFileAST())
8985 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008986 return *this;
8987 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008988 } else {
8989 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008990 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008991 return *this;
8992}
8993
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008994Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8995 *this << FE->getName();
8996 return *this;
8997}
8998
8999Logger &cxindex::Logger::operator<<(CXCursor cursor) {
9000 CXString cursorName = clang_getCursorDisplayName(cursor);
9001 *this << cursorName << "@" << clang_getCursorLocation(cursor);
9002 clang_disposeString(cursorName);
9003 return *this;
9004}
9005
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009006Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
9007 CXFile File;
9008 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00009009 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009010 CXString FileName = clang_getFileName(File);
9011 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
9012 clang_disposeString(FileName);
9013 return *this;
9014}
9015
9016Logger &cxindex::Logger::operator<<(CXSourceRange range) {
9017 CXSourceLocation BLoc = clang_getRangeStart(range);
9018 CXSourceLocation ELoc = clang_getRangeEnd(range);
9019
9020 CXFile BFile;
9021 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00009022 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009023
9024 CXFile EFile;
9025 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00009026 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009027
9028 CXString BFileName = clang_getFileName(BFile);
9029 if (BFile == EFile) {
9030 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
9031 BLine, BColumn, ELine, EColumn);
9032 } else {
9033 CXString EFileName = clang_getFileName(EFile);
9034 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
9035 BLine, BColumn)
9036 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
9037 ELine, EColumn);
9038 clang_disposeString(EFileName);
9039 }
9040 clang_disposeString(BFileName);
9041 return *this;
9042}
9043
9044Logger &cxindex::Logger::operator<<(CXString Str) {
9045 *this << clang_getCString(Str);
9046 return *this;
9047}
9048
9049Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
9050 LogOS << Fmt;
9051 return *this;
9052}
9053
Benjamin Kramer762bc332019-08-07 14:44:40 +00009054static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00009055
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009056cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00009057 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009058
9059 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
9060
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009061 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009062 OS << "[libclang:" << Name << ':';
9063
Alp Toker1a86ad22014-07-06 06:24:00 +00009064#ifdef USE_DARWIN_THREADS
9065 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009066 mach_port_t tid = pthread_mach_thread_np(pthread_self());
9067 OS << tid << ':';
9068#endif
9069
9070 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
9071 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00009072 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009073
9074 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00009075 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009076 OS << "--------------------------------------------------\n";
9077 }
9078}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00009079
9080#ifdef CLANG_TOOL_EXTRA_BUILD
9081// This anchor is used to force the linker to link the clang-tidy plugin.
9082extern volatile int ClangTidyPluginAnchorSource;
9083static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9084 ClangTidyPluginAnchorSource;
9085
9086// This anchor is used to force the linker to link the clang-include-fixer
9087// plugin.
9088extern volatile int ClangIncludeFixerPluginAnchorSource;
9089static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9090 ClangIncludeFixerPluginAnchorSource;
9091#endif