blob: df5530c73c6d6632dfdf26d9d6e8dac39a78c235 [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 Bataev9fb6e642014-07-22 06:45:04 +00002051 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002052 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002053 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002054 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002055 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002056 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002057 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002058 void
2059 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002060 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002061 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002062 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Alexey Bataev60e51c42019-10-10 20:13:02 +00002063 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002064 void
2065 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002066 void VisitOMPParallelMasterTaskLoopDirective(
2067 const OMPParallelMasterTaskLoopDirective *D);
Alexey Bataev14a388f2019-10-25 10:27:13 -04002068 void VisitOMPParallelMasterTaskLoopSimdDirective(
2069 const OMPParallelMasterTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002070 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002071 void VisitOMPDistributeParallelForDirective(
2072 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002073 void VisitOMPDistributeParallelForSimdDirective(
2074 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002075 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002076 void VisitOMPTargetParallelForSimdDirective(
2077 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002078 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002079 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002080 void VisitOMPTeamsDistributeSimdDirective(
2081 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002082 void VisitOMPTeamsDistributeParallelForSimdDirective(
2083 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002084 void VisitOMPTeamsDistributeParallelForDirective(
2085 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002086 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002087 void VisitOMPTargetTeamsDistributeDirective(
2088 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002089 void VisitOMPTargetTeamsDistributeParallelForDirective(
2090 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002091 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2092 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002093 void VisitOMPTargetTeamsDistributeSimdDirective(
2094 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002095
Guy Benyei11169dd2012-12-18 14:30:41 +00002096private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002097 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002099 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2100 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002101 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2102 void AddStmt(const Stmt *S);
2103 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002105 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002106 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002107};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002108} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002109
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002110void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 // 'S' should always be non-null, since it comes from the
2112 // statement we are visiting.
2113 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2114}
2115
2116void
2117EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2118 if (Qualifier)
2119 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2120}
2121
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002122void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002123 if (S)
2124 WL.push_back(StmtVisit(S, Parent));
2125}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002126void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 if (D)
2128 WL.push_back(DeclVisit(D, Parent, isFirst));
2129}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002130void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2131 unsigned NumTemplateArgs) {
2132 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002133}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002134void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002135 if (D)
2136 WL.push_back(MemberRefVisit(D, L, Parent));
2137}
2138void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2139 if (TI)
2140 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2141 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002142void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002143 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002144 for (const Stmt *SubStmt : S->children()) {
2145 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 }
2147 if (size == WL.size())
2148 return;
2149 // Now reverse the entries we just added. This will match the DFS
2150 // ordering performed by the worklist.
2151 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2152 std::reverse(I, E);
2153}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002154namespace {
2155class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2156 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002157 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002158 template <typename T>
2159 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002160public:
2161 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2162#define OPENMP_CLAUSE(Name, Class) \
2163 void Visit##Class(const Class *C);
2164#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002165 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002166 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002167};
2168
Alexey Bataev3392d762016-02-16 11:18:12 +00002169void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2170 const OMPClauseWithPreInit *C) {
2171 Visitor->AddStmt(C->getPreInitStmt());
2172}
2173
Alexey Bataev005248a2016-02-25 05:25:57 +00002174void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2175 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002176 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002177 Visitor->AddStmt(C->getPostUpdateExpr());
2178}
2179
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002180void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002181 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002182 Visitor->AddStmt(C->getCondition());
2183}
2184
Alexey Bataev3778b602014-07-17 07:32:53 +00002185void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2186 Visitor->AddStmt(C->getCondition());
2187}
2188
Alexey Bataev568a8332014-03-06 06:15:19 +00002189void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002190 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002191 Visitor->AddStmt(C->getNumThreads());
2192}
2193
Alexey Bataev62c87d22014-03-21 04:51:18 +00002194void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2195 Visitor->AddStmt(C->getSafelen());
2196}
2197
Alexey Bataev66b15b52015-08-21 11:14:16 +00002198void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2199 Visitor->AddStmt(C->getSimdlen());
2200}
2201
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002202void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2203 Visitor->AddStmt(C->getAllocator());
2204}
2205
Alexander Musman8bd31e62014-05-27 15:12:19 +00002206void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2207 Visitor->AddStmt(C->getNumForLoops());
2208}
2209
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002210void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002211
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002212void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2213
Alexey Bataev56dafe82014-06-20 07:16:17 +00002214void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002215 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002216 Visitor->AddStmt(C->getChunkSize());
2217}
2218
Alexey Bataev10e775f2015-07-30 11:36:16 +00002219void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2220 Visitor->AddStmt(C->getNumForLoops());
2221}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002222
Alexey Bataev0f0564b2020-03-17 09:17:42 -04002223void OMPClauseEnqueue::VisitOMPDetachClause(const OMPDetachClause *C) {
2224 Visitor->AddStmt(C->getEventHandler());
2225}
2226
Alexey Bataev236070f2014-06-20 11:19:47 +00002227void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2228
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002229void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2230
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002231void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2232
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002233void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2234
Alexey Bataevdea47612014-07-23 07:46:59 +00002235void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2236
Alexey Bataev67a4f222014-07-23 10:25:33 +00002237void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2238
Alexey Bataev459dec02014-07-24 06:46:57 +00002239void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2240
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002241void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2242
Alexey Bataevea9166b2020-02-06 16:30:23 -05002243void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
2244
Alexey Bataev04a830f2020-02-10 14:30:39 -05002245void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
2246
Alexey Bataev95598342020-02-10 15:49:05 -05002247void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {}
2248
Alexey Bataev9a8defc2020-02-11 11:10:43 -05002249void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {}
2250
Alexey Bataev346265e2015-09-25 10:37:12 +00002251void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2252
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002253void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2254
Alexey Bataevb825de12015-12-07 10:51:44 +00002255void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2256
Alexey Bataev375437a2020-03-02 14:21:20 -05002257void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *) {}
2258
Kelvin Li1408f912018-09-26 04:28:39 +00002259void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2260 const OMPUnifiedAddressClause *) {}
2261
Patrick Lyster4a370b92018-10-01 13:47:43 +00002262void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2263 const OMPUnifiedSharedMemoryClause *) {}
2264
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002265void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2266 const OMPReverseOffloadClause *) {}
2267
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002268void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2269 const OMPDynamicAllocatorsClause *) {}
2270
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002271void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2272 const OMPAtomicDefaultMemOrderClause *) {}
2273
Michael Wonge710d542015-08-07 16:16:36 +00002274void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2275 Visitor->AddStmt(C->getDevice());
2276}
2277
Kelvin Li099bb8c2015-11-24 20:50:12 +00002278void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002279 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002280 Visitor->AddStmt(C->getNumTeams());
2281}
2282
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002283void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002284 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002285 Visitor->AddStmt(C->getThreadLimit());
2286}
2287
Alexey Bataeva0569352015-12-01 10:17:31 +00002288void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2289 Visitor->AddStmt(C->getPriority());
2290}
2291
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002292void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2293 Visitor->AddStmt(C->getGrainsize());
2294}
2295
Alexey Bataev382967a2015-12-08 12:06:20 +00002296void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2297 Visitor->AddStmt(C->getNumTasks());
2298}
2299
Alexey Bataev28c75412015-12-15 08:19:24 +00002300void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2301 Visitor->AddStmt(C->getHint());
2302}
2303
Alexey Bataev756c1962013-09-24 03:17:45 +00002304template<typename T>
2305void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002306 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002307 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002308 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002309}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002310
Alexey Bataeve04483e2019-03-27 14:14:31 +00002311void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2312 VisitOMPClauseList(C);
2313 Visitor->AddStmt(C->getAllocator());
2314}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002315void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002316 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002317 for (const auto *E : C->private_copies()) {
2318 Visitor->AddStmt(E);
2319 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002320}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002321void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2322 const OMPFirstprivateClause *C) {
2323 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002324 VisitOMPClauseWithPreInit(C);
2325 for (const auto *E : C->private_copies()) {
2326 Visitor->AddStmt(E);
2327 }
2328 for (const auto *E : C->inits()) {
2329 Visitor->AddStmt(E);
2330 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002331}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002332void OMPClauseEnqueue::VisitOMPLastprivateClause(
2333 const OMPLastprivateClause *C) {
2334 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002335 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002336 for (auto *E : C->private_copies()) {
2337 Visitor->AddStmt(E);
2338 }
2339 for (auto *E : C->source_exprs()) {
2340 Visitor->AddStmt(E);
2341 }
2342 for (auto *E : C->destination_exprs()) {
2343 Visitor->AddStmt(E);
2344 }
2345 for (auto *E : C->assignment_ops()) {
2346 Visitor->AddStmt(E);
2347 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002348}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002349void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002350 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002351}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002352void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2353 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002354 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002355 for (auto *E : C->privates()) {
2356 Visitor->AddStmt(E);
2357 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002358 for (auto *E : C->lhs_exprs()) {
2359 Visitor->AddStmt(E);
2360 }
2361 for (auto *E : C->rhs_exprs()) {
2362 Visitor->AddStmt(E);
2363 }
2364 for (auto *E : C->reduction_ops()) {
2365 Visitor->AddStmt(E);
2366 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002367}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002368void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2369 const OMPTaskReductionClause *C) {
2370 VisitOMPClauseList(C);
2371 VisitOMPClauseWithPostUpdate(C);
2372 for (auto *E : C->privates()) {
2373 Visitor->AddStmt(E);
2374 }
2375 for (auto *E : C->lhs_exprs()) {
2376 Visitor->AddStmt(E);
2377 }
2378 for (auto *E : C->rhs_exprs()) {
2379 Visitor->AddStmt(E);
2380 }
2381 for (auto *E : C->reduction_ops()) {
2382 Visitor->AddStmt(E);
2383 }
2384}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002385void OMPClauseEnqueue::VisitOMPInReductionClause(
2386 const OMPInReductionClause *C) {
2387 VisitOMPClauseList(C);
2388 VisitOMPClauseWithPostUpdate(C);
2389 for (auto *E : C->privates()) {
2390 Visitor->AddStmt(E);
2391 }
2392 for (auto *E : C->lhs_exprs()) {
2393 Visitor->AddStmt(E);
2394 }
2395 for (auto *E : C->rhs_exprs()) {
2396 Visitor->AddStmt(E);
2397 }
2398 for (auto *E : C->reduction_ops()) {
2399 Visitor->AddStmt(E);
2400 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002401 for (auto *E : C->taskgroup_descriptors())
2402 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002403}
Alexander Musman8dba6642014-04-22 13:09:42 +00002404void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2405 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002406 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002407 for (const auto *E : C->privates()) {
2408 Visitor->AddStmt(E);
2409 }
Alexander Musman3276a272015-03-21 10:12:56 +00002410 for (const auto *E : C->inits()) {
2411 Visitor->AddStmt(E);
2412 }
2413 for (const auto *E : C->updates()) {
2414 Visitor->AddStmt(E);
2415 }
2416 for (const auto *E : C->finals()) {
2417 Visitor->AddStmt(E);
2418 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002419 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002420 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002421}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002422void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2423 VisitOMPClauseList(C);
2424 Visitor->AddStmt(C->getAlignment());
2425}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002426void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2427 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002428 for (auto *E : C->source_exprs()) {
2429 Visitor->AddStmt(E);
2430 }
2431 for (auto *E : C->destination_exprs()) {
2432 Visitor->AddStmt(E);
2433 }
2434 for (auto *E : C->assignment_ops()) {
2435 Visitor->AddStmt(E);
2436 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002437}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002438void
2439OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2440 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002441 for (auto *E : C->source_exprs()) {
2442 Visitor->AddStmt(E);
2443 }
2444 for (auto *E : C->destination_exprs()) {
2445 Visitor->AddStmt(E);
2446 }
2447 for (auto *E : C->assignment_ops()) {
2448 Visitor->AddStmt(E);
2449 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002450}
Alexey Bataev6125da92014-07-21 11:26:11 +00002451void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2452 VisitOMPClauseList(C);
2453}
Alexey Bataevc112e942020-02-28 09:52:15 -05002454void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) {
2455 Visitor->AddStmt(C->getDepobj());
2456}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002457void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2458 VisitOMPClauseList(C);
2459}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002460void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2461 VisitOMPClauseList(C);
2462}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002463void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2464 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002465 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002466 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002467}
Alexey Bataev3392d762016-02-16 11:18:12 +00002468void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2469 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002470void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2471 VisitOMPClauseList(C);
2472}
Samuel Antaoec172c62016-05-26 17:49:04 +00002473void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2474 VisitOMPClauseList(C);
2475}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002476void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2477 VisitOMPClauseList(C);
2478}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002479void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2480 VisitOMPClauseList(C);
2481}
Alexey Bataevb6e70842019-12-16 15:54:17 -05002482void OMPClauseEnqueue::VisitOMPNontemporalClause(
2483 const OMPNontemporalClause *C) {
2484 VisitOMPClauseList(C);
Alexey Bataev0860db92019-12-19 10:01:10 -05002485 for (const auto *E : C->private_refs())
2486 Visitor->AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05002487}
Alexey Bataevcb8e6912020-01-31 16:09:26 -05002488void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002489}
Alexey Bataev756c1962013-09-24 03:17:45 +00002490
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002491void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2492 unsigned size = WL.size();
2493 OMPClauseEnqueue Visitor(this);
2494 Visitor.Visit(S);
2495 if (size == WL.size())
2496 return;
2497 // Now reverse the entries we just added. This will match the DFS
2498 // ordering performed by the worklist.
2499 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2500 std::reverse(I, E);
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2504}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002505void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 AddDecl(B->getBlockDecl());
2507}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002508void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 EnqueueChildren(E);
2510 AddTypeLoc(E->getTypeSourceInfo());
2511}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002512void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002513 for (auto &I : llvm::reverse(S->body()))
2514 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002515}
2516void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002517VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 AddStmt(S->getSubStmt());
2519 AddDeclarationNameInfo(S);
2520 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2521 AddNestedNameSpecifierLoc(QualifierLoc);
2522}
2523
2524void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002525VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002526 if (E->hasExplicitTemplateArgs())
2527 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 AddDeclarationNameInfo(E);
2529 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2530 AddNestedNameSpecifierLoc(QualifierLoc);
2531 if (!E->isImplicitAccess())
2532 AddStmt(E->getBase());
2533}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 // Enqueue the initializer , if any.
2536 AddStmt(E->getInitializer());
2537 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002538 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 // Enqueue the allocated type.
2540 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2541 // Enqueue the placement arguments.
2542 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2543 AddStmt(E->getPlacementArg(I-1));
2544}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002545void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2547 AddStmt(CE->getArg(I-1));
2548 AddStmt(CE->getCallee());
2549 AddStmt(CE->getArg(0));
2550}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002551void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2552 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 // Visit the name of the type being destroyed.
2554 AddTypeLoc(E->getDestroyedTypeInfo());
2555 // Visit the scope type that looks disturbingly like the nested-name-specifier
2556 // but isn't.
2557 AddTypeLoc(E->getScopeTypeInfo());
2558 // Visit the nested-name-specifier.
2559 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2560 AddNestedNameSpecifierLoc(QualifierLoc);
2561 // Visit base expression.
2562 AddStmt(E->getBase());
2563}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002564void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2565 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 AddTypeLoc(E->getTypeSourceInfo());
2567}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002568void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2569 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 EnqueueChildren(E);
2571 AddTypeLoc(E->getTypeSourceInfo());
2572}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002573void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 EnqueueChildren(E);
2575 if (E->isTypeOperand())
2576 AddTypeLoc(E->getTypeOperandSourceInfo());
2577}
2578
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002579void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2580 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 EnqueueChildren(E);
2582 AddTypeLoc(E->getTypeSourceInfo());
2583}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002584void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 EnqueueChildren(E);
2586 if (E->isTypeOperand())
2587 AddTypeLoc(E->getTypeOperandSourceInfo());
2588}
2589
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002590void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 EnqueueChildren(S);
2592 AddDecl(S->getExceptionDecl());
2593}
2594
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002595void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002596 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002597 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002598 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002599}
2600
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002601void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002602 if (DR->hasExplicitTemplateArgs())
2603 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 WL.push_back(DeclRefExprParts(DR, Parent));
2605}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002606void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2607 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002608 if (E->hasExplicitTemplateArgs())
2609 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 AddDeclarationNameInfo(E);
2611 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2612}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002613void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 unsigned size = WL.size();
2615 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002616 for (const auto *D : S->decls()) {
2617 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 isFirst = false;
2619 }
2620 if (size == WL.size())
2621 return;
2622 // Now reverse the entries we just added. This will match the DFS
2623 // ordering performed by the worklist.
2624 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2625 std::reverse(I, E);
2626}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002627void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002629 for (const DesignatedInitExpr::Designator &D :
2630 llvm::reverse(E->designators())) {
2631 if (D.isFieldDesignator()) {
2632 if (FieldDecl *Field = D.getField())
2633 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 continue;
2635 }
David Majnemerf7e36092016-06-23 00:15:04 +00002636 if (D.isArrayDesignator()) {
2637 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 continue;
2639 }
David Majnemerf7e36092016-06-23 00:15:04 +00002640 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2641 AddStmt(E->getArrayRangeEnd(D));
2642 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 }
2644}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002645void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 EnqueueChildren(E);
2647 AddTypeLoc(E->getTypeInfoAsWritten());
2648}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002649void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 AddStmt(FS->getBody());
2651 AddStmt(FS->getInc());
2652 AddStmt(FS->getCond());
2653 AddDecl(FS->getConditionVariable());
2654 AddStmt(FS->getInit());
2655}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002656void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2658}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002659void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 AddStmt(If->getElse());
2661 AddStmt(If->getThen());
2662 AddStmt(If->getCond());
2663 AddDecl(If->getConditionVariable());
2664}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002665void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 // We care about the syntactic form of the initializer list, only.
2667 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2668 IE = Syntactic;
2669 EnqueueChildren(IE);
2670}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002671void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 WL.push_back(MemberExprParts(M, Parent));
2673
2674 // If the base of the member access expression is an implicit 'this', don't
2675 // visit it.
2676 // FIXME: If we ever want to show these implicit accesses, this will be
2677 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002678 if (M->isImplicitAccess())
2679 return;
2680
2681 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002682 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002683 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2684 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2685 if (FD->isAnonymousStructOrUnion()) {
2686 AddStmt(SubME->getBase());
2687 return;
2688 }
2689 }
2690 }
2691
2692 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002693}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002694void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 AddTypeLoc(E->getEncodedTypeSourceInfo());
2696}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002697void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 EnqueueChildren(M);
2699 AddTypeLoc(M->getClassReceiverTypeInfo());
2700}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002701void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 // Visit the components of the offsetof expression.
2703 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 const OffsetOfNode &Node = E->getComponent(I-1);
2705 switch (Node.getKind()) {
2706 case OffsetOfNode::Array:
2707 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2708 break;
2709 case OffsetOfNode::Field:
2710 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2711 break;
2712 case OffsetOfNode::Identifier:
2713 case OffsetOfNode::Base:
2714 continue;
2715 }
2716 }
2717 // Visit the type into which we're computing the offset.
2718 AddTypeLoc(E->getTypeSourceInfo());
2719}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002720void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002721 if (E->hasExplicitTemplateArgs())
2722 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 WL.push_back(OverloadExprParts(E, Parent));
2724}
2725void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002726 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 EnqueueChildren(E);
2728 if (E->isArgumentType())
2729 AddTypeLoc(E->getArgumentTypeInfo());
2730}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002731void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 EnqueueChildren(S);
2733}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002734void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 AddStmt(S->getBody());
2736 AddStmt(S->getCond());
2737 AddDecl(S->getConditionVariable());
2738}
2739
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002740void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 AddStmt(W->getBody());
2742 AddStmt(W->getCond());
2743 AddDecl(W->getConditionVariable());
2744}
2745
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002746void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 for (unsigned I = E->getNumArgs(); I > 0; --I)
2748 AddTypeLoc(E->getArg(I-1));
2749}
2750
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002751void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 AddTypeLoc(E->getQueriedTypeSourceInfo());
2753}
2754
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002755void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 EnqueueChildren(E);
2757}
2758
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002759void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 VisitOverloadExpr(U);
2761 if (!U->isImplicitAccess())
2762 AddStmt(U->getBase());
2763}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002764void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 AddStmt(E->getSubExpr());
2766 AddTypeLoc(E->getWrittenTypeInfo());
2767}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002768void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002769 WL.push_back(SizeOfPackExprParts(E, Parent));
2770}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002771void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 // If the opaque value has a source expression, just transparently
2773 // visit that. This is useful for (e.g.) pseudo-object expressions.
2774 if (Expr *SourceExpr = E->getSourceExpr())
2775 return Visit(SourceExpr);
2776}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002777void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 AddStmt(E->getBody());
2779 WL.push_back(LambdaExprParts(E, Parent));
2780}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002781void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 // Treat the expression like its syntactic form.
2783 Visit(E->getSyntacticForm());
2784}
2785
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002786void EnqueueVisitor::VisitOMPExecutableDirective(
2787 const OMPExecutableDirective *D) {
2788 EnqueueChildren(D);
2789 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2790 E = D->clauses().end();
2791 I != E; ++I)
2792 EnqueueChildren(*I);
2793}
2794
Alexander Musman3aaab662014-08-19 11:27:13 +00002795void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2796 VisitOMPExecutableDirective(D);
2797}
2798
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002799void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2800 VisitOMPExecutableDirective(D);
2801}
2802
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002803void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002804 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002805}
2806
Alexey Bataevf29276e2014-06-18 04:14:57 +00002807void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002808 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002809}
2810
Alexander Musmanf82886e2014-09-18 05:12:34 +00002811void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2812 VisitOMPLoopDirective(D);
2813}
2814
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002815void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2816 VisitOMPExecutableDirective(D);
2817}
2818
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002819void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2820 VisitOMPExecutableDirective(D);
2821}
2822
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002823void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2824 VisitOMPExecutableDirective(D);
2825}
2826
Alexander Musman80c22892014-07-17 08:54:58 +00002827void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2828 VisitOMPExecutableDirective(D);
2829}
2830
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002831void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2832 VisitOMPExecutableDirective(D);
2833 AddDeclarationNameInfo(D);
2834}
2835
Alexey Bataev4acb8592014-07-07 13:01:15 +00002836void
2837EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002838 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002839}
2840
Alexander Musmane4e893b2014-09-23 09:33:00 +00002841void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2842 const OMPParallelForSimdDirective *D) {
2843 VisitOMPLoopDirective(D);
2844}
2845
cchen47d60942019-12-05 13:43:48 -05002846void EnqueueVisitor::VisitOMPParallelMasterDirective(
2847 const OMPParallelMasterDirective *D) {
2848 VisitOMPExecutableDirective(D);
2849}
2850
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002851void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2852 const OMPParallelSectionsDirective *D) {
2853 VisitOMPExecutableDirective(D);
2854}
2855
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002856void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2857 VisitOMPExecutableDirective(D);
2858}
2859
Alexey Bataev68446b72014-07-18 07:47:19 +00002860void
2861EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2862 VisitOMPExecutableDirective(D);
2863}
2864
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002865void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2866 VisitOMPExecutableDirective(D);
2867}
2868
Alexey Bataev2df347a2014-07-18 10:17:07 +00002869void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2870 VisitOMPExecutableDirective(D);
2871}
2872
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002873void EnqueueVisitor::VisitOMPTaskgroupDirective(
2874 const OMPTaskgroupDirective *D) {
2875 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002876 if (const Expr *E = D->getReductionRef())
2877 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002878}
2879
Alexey Bataev6125da92014-07-21 11:26:11 +00002880void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2881 VisitOMPExecutableDirective(D);
2882}
2883
Alexey Bataevc112e942020-02-28 09:52:15 -05002884void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) {
2885 VisitOMPExecutableDirective(D);
2886}
2887
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002888void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2889 VisitOMPExecutableDirective(D);
2890}
2891
Alexey Bataev0162e452014-07-22 10:10:35 +00002892void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2893 VisitOMPExecutableDirective(D);
2894}
2895
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002896void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2897 VisitOMPExecutableDirective(D);
2898}
2899
Alexey Bataevc112e942020-02-28 09:52:15 -05002900void EnqueueVisitor::VisitOMPTargetDataDirective(
2901 const OMPTargetDataDirective *D) {
Michael Wong65f367f2015-07-21 13:44:28 +00002902 VisitOMPExecutableDirective(D);
2903}
2904
Samuel Antaodf67fc42016-01-19 19:15:56 +00002905void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2906 const OMPTargetEnterDataDirective *D) {
2907 VisitOMPExecutableDirective(D);
2908}
2909
Samuel Antao72590762016-01-19 20:04:50 +00002910void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2911 const OMPTargetExitDataDirective *D) {
2912 VisitOMPExecutableDirective(D);
2913}
2914
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002915void EnqueueVisitor::VisitOMPTargetParallelDirective(
2916 const OMPTargetParallelDirective *D) {
2917 VisitOMPExecutableDirective(D);
2918}
2919
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002920void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2921 const OMPTargetParallelForDirective *D) {
2922 VisitOMPLoopDirective(D);
2923}
2924
Alexey Bataev13314bf2014-10-09 04:18:56 +00002925void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2926 VisitOMPExecutableDirective(D);
2927}
2928
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002929void EnqueueVisitor::VisitOMPCancellationPointDirective(
2930 const OMPCancellationPointDirective *D) {
2931 VisitOMPExecutableDirective(D);
2932}
2933
Alexey Bataev80909872015-07-02 11:25:17 +00002934void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2935 VisitOMPExecutableDirective(D);
2936}
2937
Alexey Bataev49f6e782015-12-01 04:18:41 +00002938void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2939 VisitOMPLoopDirective(D);
2940}
2941
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002942void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2943 const OMPTaskLoopSimdDirective *D) {
2944 VisitOMPLoopDirective(D);
2945}
2946
Alexey Bataev60e51c42019-10-10 20:13:02 +00002947void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2948 const OMPMasterTaskLoopDirective *D) {
2949 VisitOMPLoopDirective(D);
2950}
2951
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002952void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2953 const OMPMasterTaskLoopSimdDirective *D) {
2954 VisitOMPLoopDirective(D);
2955}
2956
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002957void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2958 const OMPParallelMasterTaskLoopDirective *D) {
2959 VisitOMPLoopDirective(D);
2960}
2961
Alexey Bataev14a388f2019-10-25 10:27:13 -04002962void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
2963 const OMPParallelMasterTaskLoopSimdDirective *D) {
2964 VisitOMPLoopDirective(D);
2965}
2966
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002967void EnqueueVisitor::VisitOMPDistributeDirective(
2968 const OMPDistributeDirective *D) {
2969 VisitOMPLoopDirective(D);
2970}
2971
Carlo Bertolli9925f152016-06-27 14:55:37 +00002972void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2973 const OMPDistributeParallelForDirective *D) {
2974 VisitOMPLoopDirective(D);
2975}
2976
Kelvin Li4a39add2016-07-05 05:00:15 +00002977void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2978 const OMPDistributeParallelForSimdDirective *D) {
2979 VisitOMPLoopDirective(D);
2980}
2981
Kelvin Li787f3fc2016-07-06 04:45:38 +00002982void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2983 const OMPDistributeSimdDirective *D) {
2984 VisitOMPLoopDirective(D);
2985}
2986
Kelvin Lia579b912016-07-14 02:54:56 +00002987void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2988 const OMPTargetParallelForSimdDirective *D) {
2989 VisitOMPLoopDirective(D);
2990}
2991
Kelvin Li986330c2016-07-20 22:57:10 +00002992void EnqueueVisitor::VisitOMPTargetSimdDirective(
2993 const OMPTargetSimdDirective *D) {
2994 VisitOMPLoopDirective(D);
2995}
2996
Kelvin Li02532872016-08-05 14:37:37 +00002997void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2998 const OMPTeamsDistributeDirective *D) {
2999 VisitOMPLoopDirective(D);
3000}
3001
Kelvin Li4e325f72016-10-25 12:50:55 +00003002void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
3003 const OMPTeamsDistributeSimdDirective *D) {
3004 VisitOMPLoopDirective(D);
3005}
3006
Kelvin Li579e41c2016-11-30 23:51:03 +00003007void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
3008 const OMPTeamsDistributeParallelForSimdDirective *D) {
3009 VisitOMPLoopDirective(D);
3010}
3011
Kelvin Li7ade93f2016-12-09 03:24:30 +00003012void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
3013 const OMPTeamsDistributeParallelForDirective *D) {
3014 VisitOMPLoopDirective(D);
3015}
3016
Kelvin Libf594a52016-12-17 05:48:59 +00003017void EnqueueVisitor::VisitOMPTargetTeamsDirective(
3018 const OMPTargetTeamsDirective *D) {
3019 VisitOMPExecutableDirective(D);
3020}
3021
Kelvin Li83c451e2016-12-25 04:52:54 +00003022void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3023 const OMPTargetTeamsDistributeDirective *D) {
3024 VisitOMPLoopDirective(D);
3025}
3026
Kelvin Li80e8f562016-12-29 22:16:30 +00003027void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3028 const OMPTargetTeamsDistributeParallelForDirective *D) {
3029 VisitOMPLoopDirective(D);
3030}
3031
Kelvin Li1851df52017-01-03 05:23:48 +00003032void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3033 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3034 VisitOMPLoopDirective(D);
3035}
3036
Kelvin Lida681182017-01-10 18:08:18 +00003037void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3038 const OMPTargetTeamsDistributeSimdDirective *D) {
3039 VisitOMPLoopDirective(D);
3040}
3041
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003042void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
3044}
3045
3046bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3047 if (RegionOfInterest.isValid()) {
3048 SourceRange Range = getRawCursorExtent(C);
3049 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3050 return false;
3051 }
3052 return true;
3053}
3054
3055bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3056 while (!WL.empty()) {
3057 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003058 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003059
3060 // Set the Parent field, then back to its old value once we're done.
3061 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3062
3063 switch (LI.getKind()) {
3064 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003065 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003066 if (!D)
3067 continue;
3068
3069 // For now, perform default visitation for Decls.
3070 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3071 cast<DeclVisit>(&LI)->isFirst())))
3072 return true;
3073
3074 continue;
3075 }
3076 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003077 for (const TemplateArgumentLoc &Arg :
3078 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3079 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 return true;
3081 }
3082 continue;
3083 }
3084 case VisitorJob::TypeLocVisitKind: {
3085 // Perform default visitation for TypeLocs.
3086 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3087 return true;
3088 continue;
3089 }
3090 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003091 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003092 if (LabelStmt *stmt = LS->getStmt()) {
3093 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3094 TU))) {
3095 return true;
3096 }
3097 }
3098 continue;
3099 }
3100
3101 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3102 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3103 if (VisitNestedNameSpecifierLoc(V->get()))
3104 return true;
3105 continue;
3106 }
3107
3108 case VisitorJob::DeclarationNameInfoVisitKind: {
3109 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3110 ->get()))
3111 return true;
3112 continue;
3113 }
3114 case VisitorJob::MemberRefVisitKind: {
3115 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3116 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3117 return true;
3118 continue;
3119 }
3120 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003121 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003122 if (!S)
3123 continue;
3124
3125 // Update the current cursor.
3126 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3127 if (!IsInRegionOfInterest(Cursor))
3128 continue;
3129 switch (Visitor(Cursor, Parent, ClientData)) {
3130 case CXChildVisit_Break: return true;
3131 case CXChildVisit_Continue: break;
3132 case CXChildVisit_Recurse:
3133 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003134 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 EnqueueWorkList(WL, S);
3136 break;
3137 }
3138 continue;
3139 }
3140 case VisitorJob::MemberExprPartsKind: {
3141 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003142 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003143
3144 // Visit the nested-name-specifier
3145 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3146 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3147 return true;
3148
3149 // Visit the declaration name.
3150 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3151 return true;
3152
3153 // Visit the explicitly-specified template arguments, if any.
3154 if (M->hasExplicitTemplateArgs()) {
3155 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3156 *ArgEnd = Arg + M->getNumTemplateArgs();
3157 Arg != ArgEnd; ++Arg) {
3158 if (VisitTemplateArgumentLoc(*Arg))
3159 return true;
3160 }
3161 }
3162 continue;
3163 }
3164 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003165 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003166 // Visit nested-name-specifier, if present.
3167 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3168 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3169 return true;
3170 // Visit declaration name.
3171 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3172 return true;
3173 continue;
3174 }
3175 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003176 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 // Visit the nested-name-specifier.
3178 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3179 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3180 return true;
3181 // Visit the declaration name.
3182 if (VisitDeclarationNameInfo(O->getNameInfo()))
3183 return true;
3184 // Visit the overloaded declaration reference.
3185 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3186 return true;
3187 continue;
3188 }
3189 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003190 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003191 NamedDecl *Pack = E->getPack();
3192 if (isa<TemplateTypeParmDecl>(Pack)) {
3193 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3194 E->getPackLoc(), TU)))
3195 return true;
3196
3197 continue;
3198 }
3199
3200 if (isa<TemplateTemplateParmDecl>(Pack)) {
3201 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3202 E->getPackLoc(), TU)))
3203 return true;
3204
3205 continue;
3206 }
3207
3208 // Non-type template parameter packs and function parameter packs are
3209 // treated like DeclRefExpr cursors.
3210 continue;
3211 }
3212
3213 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003214 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003215 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003216 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3217 CEnd = E->explicit_capture_end();
3218 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003219 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003220 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003221
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3223 C->getLocation(),
3224 TU)))
3225 return true;
3226 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003227 // Visit init captures
3228 for (auto InitExpr : E->capture_inits()) {
3229 if (Visit(InitExpr))
3230 return true;
3231 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003232
Haojian Wuef87c262018-12-18 15:29:12 +00003233 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003235 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3236 if (E->hasExplicitParameters()) {
3237 // Visit parameters.
3238 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3239 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003241 }
3242 if (E->hasExplicitResultType()) {
3243 // Visit result type.
3244 if (Visit(Proto.getReturnLoc()))
3245 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003246 }
3247 }
3248 break;
3249 }
3250
3251 case VisitorJob::PostChildrenVisitKind:
3252 if (PostChildrenVisitor(Parent, ClientData))
3253 return true;
3254 break;
3255 }
3256 }
3257 return false;
3258}
3259
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003260bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003261 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 if (!WorkListFreeList.empty()) {
3263 WL = WorkListFreeList.back();
3264 WL->clear();
3265 WorkListFreeList.pop_back();
3266 }
3267 else {
3268 WL = new VisitorWorkList();
3269 WorkListCache.push_back(WL);
3270 }
3271 EnqueueWorkList(*WL, S);
3272 bool result = RunVisitorWorkList(*WL);
3273 WorkListFreeList.push_back(WL);
3274 return result;
3275}
3276
3277namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003278typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003279RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3280 const DeclarationNameInfo &NI, SourceRange QLoc,
3281 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3283 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3284 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3285
3286 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3287
3288 RefNamePieces Pieces;
3289
3290 if (WantQualifier && QLoc.isValid())
3291 Pieces.push_back(QLoc);
3292
3293 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3294 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003295
3296 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3297 Pieces.push_back(*TemplateArgsLoc);
3298
Guy Benyei11169dd2012-12-18 14:30:41 +00003299 if (Kind == DeclarationName::CXXOperatorName) {
3300 Pieces.push_back(SourceLocation::getFromRawEncoding(
3301 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3302 Pieces.push_back(SourceLocation::getFromRawEncoding(
3303 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3304 }
3305
3306 if (WantSinglePiece) {
3307 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3308 Pieces.clear();
3309 Pieces.push_back(R);
3310 }
3311
3312 return Pieces;
3313}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003314}
Guy Benyei11169dd2012-12-18 14:30:41 +00003315
3316//===----------------------------------------------------------------------===//
3317// Misc. API hooks.
3318//===----------------------------------------------------------------------===//
3319
Chandler Carruth66660742014-06-27 16:37:27 +00003320namespace {
3321struct RegisterFatalErrorHandler {
3322 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003323 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003324 }
3325};
3326}
3327
3328static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3329
Guy Benyei11169dd2012-12-18 14:30:41 +00003330CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3331 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 // We use crash recovery to make some of our APIs more reliable, implicitly
3333 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003334 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3335 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003336
Chandler Carruth66660742014-06-27 16:37:27 +00003337 // Look through the managed static to trigger construction of the managed
3338 // static which registers our fatal error handler. This ensures it is only
3339 // registered once.
3340 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003341
Adrian Prantlbc068582015-07-08 01:00:30 +00003342 // Initialize targets for clang module support.
3343 llvm::InitializeAllTargets();
3344 llvm::InitializeAllTargetMCs();
3345 llvm::InitializeAllAsmPrinters();
3346 llvm::InitializeAllAsmParsers();
3347
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003348 CIndexer *CIdxr = new CIndexer();
3349
Guy Benyei11169dd2012-12-18 14:30:41 +00003350 if (excludeDeclarationsFromPCH)
3351 CIdxr->setOnlyLocalDecls();
3352 if (displayDiagnostics)
3353 CIdxr->setDisplayDiagnostics();
3354
3355 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3356 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3357 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3358 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3359 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3360 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3361
3362 return CIdxr;
3363}
3364
3365void clang_disposeIndex(CXIndex CIdx) {
3366 if (CIdx)
3367 delete static_cast<CIndexer *>(CIdx);
3368}
3369
3370void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3371 if (CIdx)
3372 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3373}
3374
3375unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3376 if (CIdx)
3377 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3378 return 0;
3379}
3380
Alex Lorenz08615792017-12-04 21:56:36 +00003381void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3382 const char *Path) {
3383 if (CIdx)
3384 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3385}
3386
Guy Benyei11169dd2012-12-18 14:30:41 +00003387void clang_toggleCrashRecovery(unsigned isEnabled) {
3388 if (isEnabled)
3389 llvm::CrashRecoveryContext::Enable();
3390 else
3391 llvm::CrashRecoveryContext::Disable();
3392}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003393
Guy Benyei11169dd2012-12-18 14:30:41 +00003394CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3395 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003396 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003397 enum CXErrorCode Result =
3398 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003399 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003400 assert((TU && Result == CXError_Success) ||
3401 (!TU && Result != CXError_Success));
3402 return TU;
3403}
3404
3405enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3406 const char *ast_filename,
3407 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003408 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003409 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003410
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003411 if (!CIdx || !ast_filename || !out_TU)
3412 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003413
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003414 LOG_FUNC_SECTION {
3415 *Log << ast_filename;
3416 }
3417
Guy Benyei11169dd2012-12-18 14:30:41 +00003418 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3419 FileSystemOptions FileSystemOpts;
3420
Justin Bognerd512c1e2014-10-15 00:33:06 +00003421 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3422 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003423 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003424 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3425 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003426 FileSystemOpts, /*UseDebugInfo=*/false,
3427 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003428 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003429 /*AllowPCHWithCompilerErrors=*/true,
3430 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003431 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003432 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003433}
3434
3435unsigned clang_defaultEditingTranslationUnitOptions() {
3436 return CXTranslationUnit_PrecompiledPreamble |
3437 CXTranslationUnit_CacheCompletionResults;
3438}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003439
Guy Benyei11169dd2012-12-18 14:30:41 +00003440CXTranslationUnit
3441clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3442 const char *source_filename,
3443 int num_command_line_args,
3444 const char * const *command_line_args,
3445 unsigned num_unsaved_files,
3446 struct CXUnsavedFile *unsaved_files) {
3447 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3448 return clang_parseTranslationUnit(CIdx, source_filename,
3449 command_line_args, num_command_line_args,
3450 unsaved_files, num_unsaved_files,
3451 Options);
3452}
3453
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003454static CXErrorCode
3455clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3456 const char *const *command_line_args,
3457 int num_command_line_args,
3458 ArrayRef<CXUnsavedFile> unsaved_files,
3459 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003460 // Set up the initial return values.
3461 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003462 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003463
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003464 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003465 if (!CIdx || !out_TU)
3466 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003467
Guy Benyei11169dd2012-12-18 14:30:41 +00003468 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3469
3470 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3471 setThreadBackgroundPriority();
3472
3473 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003474 bool CreatePreambleOnFirstParse =
3475 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003476 // FIXME: Add a flag for modules.
3477 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003478 = (options & (CXTranslationUnit_Incomplete |
3479 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003480 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003481 = options & CXTranslationUnit_CacheCompletionResults;
3482 bool IncludeBriefCommentsInCodeCompletion
3483 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003484 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3485 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003486 bool RetainExcludedCB = options &
3487 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003488 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3489 if (options & CXTranslationUnit_SkipFunctionBodies) {
3490 SkipFunctionBodies =
3491 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3492 ? SkipFunctionBodiesScope::Preamble
3493 : SkipFunctionBodiesScope::PreambleAndMainFile;
3494 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003495
3496 // Configure the diagnostics.
3497 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003498 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003499
Manuel Klimek016c0242016-03-01 10:56:19 +00003500 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003501 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003502
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003503 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3504 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3505 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3506
Guy Benyei11169dd2012-12-18 14:30:41 +00003507 // Recover resources if we crash before exiting this function.
3508 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3509 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003510 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003511
Ahmed Charlesb8984322014-03-07 20:03:18 +00003512 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3513 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003514
3515 // Recover resources if we crash before exiting this function.
3516 llvm::CrashRecoveryContextCleanupRegistrar<
3517 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3518
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003519 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003520 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003521 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003522 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 }
3524
Ahmed Charlesb8984322014-03-07 20:03:18 +00003525 std::unique_ptr<std::vector<const char *>> Args(
3526 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003527
3528 // Recover resources if we crash before exiting this method.
3529 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3530 ArgsCleanup(Args.get());
3531
3532 // Since the Clang C library is primarily used by batch tools dealing with
3533 // (often very broken) source code, where spell-checking can have a
3534 // significant negative impact on performance (particularly when
3535 // precompiled headers are involved), we disable it by default.
3536 // Only do this if we haven't found a spell-checking-related argument.
3537 bool FoundSpellCheckingArgument = false;
3538 for (int I = 0; I != num_command_line_args; ++I) {
3539 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3540 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3541 FoundSpellCheckingArgument = true;
3542 break;
3543 }
3544 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003545 Args->insert(Args->end(), command_line_args,
3546 command_line_args + num_command_line_args);
3547
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003548 if (!FoundSpellCheckingArgument)
3549 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3550
Guy Benyei11169dd2012-12-18 14:30:41 +00003551 // The 'source_filename' argument is optional. If the caller does not
3552 // specify it then it is assumed that the source file is specified
3553 // in the actual argument list.
3554 // Put the source file after command_line_args otherwise if '-x' flag is
3555 // present it will be unused.
3556 if (source_filename)
3557 Args->push_back(source_filename);
3558
3559 // Do we need the detailed preprocessing record?
3560 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3561 Args->push_back("-Xclang");
3562 Args->push_back("-detailed-preprocessing-record");
3563 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003564
3565 // Suppress any editor placeholder diagnostics.
3566 Args->push_back("-fallow-editor-placeholders");
3567
Guy Benyei11169dd2012-12-18 14:30:41 +00003568 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003569 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003570 // Unless the user specified that they want the preamble on the first parse
3571 // set it up to be created on the first reparse. This makes the first parse
3572 // faster, trading for a slower (first) reparse.
3573 unsigned PrecompilePreambleAfterNParses =
3574 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003575
Alex Lorenz08615792017-12-04 21:56:36 +00003576 LibclangInvocationReporter InvocationReporter(
3577 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003578 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3579 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003580 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003581 Args->data(), Args->data() + Args->size(),
3582 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003583 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003584 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003585 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3586 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003587 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003588 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003589 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3590 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003591
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003592 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003593 if (!Unit && !ErrUnit)
3594 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003595
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 if (NumErrors != Diags->getClient()->getNumErrors()) {
3597 // Make sure to check that 'Unit' is non-NULL.
3598 if (CXXIdx->getDisplayDiagnostics())
3599 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3600 }
3601
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003602 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3603 return CXError_ASTReadError;
3604
David Blaikieea4395e2017-01-06 19:49:01 +00003605 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003606 if (CXTranslationUnitImpl *TU = *out_TU) {
3607 TU->ParsingOptions = options;
3608 TU->Arguments.reserve(Args->size());
3609 for (const char *Arg : *Args)
3610 TU->Arguments.push_back(Arg);
3611 return CXError_Success;
3612 }
3613 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003614}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003615
3616CXTranslationUnit
3617clang_parseTranslationUnit(CXIndex CIdx,
3618 const char *source_filename,
3619 const char *const *command_line_args,
3620 int num_command_line_args,
3621 struct CXUnsavedFile *unsaved_files,
3622 unsigned num_unsaved_files,
3623 unsigned options) {
3624 CXTranslationUnit TU;
3625 enum CXErrorCode Result = clang_parseTranslationUnit2(
3626 CIdx, source_filename, command_line_args, num_command_line_args,
3627 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003628 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003629 assert((TU && Result == CXError_Success) ||
3630 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003631 return TU;
3632}
3633
3634enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003635 CXIndex CIdx, const char *source_filename,
3636 const char *const *command_line_args, int num_command_line_args,
3637 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3638 unsigned options, CXTranslationUnit *out_TU) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003639 noteBottomOfStack();
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003640 SmallVector<const char *, 4> Args;
3641 Args.push_back("clang");
3642 Args.append(command_line_args, command_line_args + num_command_line_args);
3643 return clang_parseTranslationUnit2FullArgv(
3644 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3645 num_unsaved_files, options, out_TU);
3646}
3647
3648enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3649 CXIndex CIdx, const char *source_filename,
3650 const char *const *command_line_args, int num_command_line_args,
3651 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3652 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003653 LOG_FUNC_SECTION {
3654 *Log << source_filename << ": ";
3655 for (int i = 0; i != num_command_line_args; ++i)
3656 *Log << command_line_args[i] << " ";
3657 }
3658
Alp Toker9d85b182014-07-07 01:23:14 +00003659 if (num_unsaved_files && !unsaved_files)
3660 return CXError_InvalidArguments;
3661
Alp Toker5c532982014-07-07 22:42:03 +00003662 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003663 auto ParseTranslationUnitImpl = [=, &result] {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003664 noteBottomOfStack();
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003665 result = clang_parseTranslationUnit_Impl(
3666 CIdx, source_filename, command_line_args, num_command_line_args,
3667 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3668 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003669
Guy Benyei11169dd2012-12-18 14:30:41 +00003670 llvm::CrashRecoveryContext CRC;
3671
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003672 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3674 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3675 fprintf(stderr, " 'command_line_args' : [");
3676 for (int i = 0; i != num_command_line_args; ++i) {
3677 if (i)
3678 fprintf(stderr, ", ");
3679 fprintf(stderr, "'%s'", command_line_args[i]);
3680 }
3681 fprintf(stderr, "],\n");
3682 fprintf(stderr, " 'unsaved_files' : [");
3683 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3684 if (i)
3685 fprintf(stderr, ", ");
3686 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3687 unsaved_files[i].Length);
3688 }
3689 fprintf(stderr, "],\n");
3690 fprintf(stderr, " 'options' : %d,\n", options);
3691 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003692
3693 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003694 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003695 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003696 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 }
Alp Toker5c532982014-07-07 22:42:03 +00003698
3699 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003700}
3701
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003702CXString clang_Type_getObjCEncoding(CXType CT) {
3703 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3704 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3705 std::string encoding;
3706 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3707 encoding);
3708
3709 return cxstring::createDup(encoding);
3710}
3711
3712static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3713 if (C.kind == CXCursor_MacroDefinition) {
3714 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3715 return MDR->getName();
3716 } else if (C.kind == CXCursor_MacroExpansion) {
3717 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3718 return ME.getName();
3719 }
3720 return nullptr;
3721}
3722
3723unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3724 const IdentifierInfo *II = getMacroIdentifier(C);
3725 if (!II) {
3726 return false;
3727 }
3728 ASTUnit *ASTU = getCursorASTUnit(C);
3729 Preprocessor &PP = ASTU->getPreprocessor();
3730 if (const MacroInfo *MI = PP.getMacroInfo(II))
3731 return MI->isFunctionLike();
3732 return false;
3733}
3734
3735unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3736 const IdentifierInfo *II = getMacroIdentifier(C);
3737 if (!II) {
3738 return false;
3739 }
3740 ASTUnit *ASTU = getCursorASTUnit(C);
3741 Preprocessor &PP = ASTU->getPreprocessor();
3742 if (const MacroInfo *MI = PP.getMacroInfo(II))
3743 return MI->isBuiltinMacro();
3744 return false;
3745}
3746
3747unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3748 const Decl *D = getCursorDecl(C);
3749 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3750 if (!FD) {
3751 return false;
3752 }
3753 return FD->isInlined();
3754}
3755
3756static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3757 if (callExpr->getNumArgs() != 1) {
3758 return nullptr;
3759 }
3760
3761 StringLiteral *S = nullptr;
3762 auto *arg = callExpr->getArg(0);
3763 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3764 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3765 auto *subExpr = I->getSubExprAsWritten();
3766
3767 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3768 return nullptr;
3769 }
3770
3771 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3772 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3773 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3774 } else {
3775 return nullptr;
3776 }
3777 return S;
3778}
3779
David Blaikie59272572016-04-13 18:23:33 +00003780struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003781 CXEvalResultKind EvalType;
3782 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003783 unsigned long long unsignedVal;
3784 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003785 double floatVal;
3786 char *stringVal;
3787 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003788 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003789 ~ExprEvalResult() {
3790 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3791 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003792 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003793 }
3794 }
3795};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003796
3797void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003798 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003799}
3800
3801CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3802 if (!E) {
3803 return CXEval_UnExposed;
3804 }
3805 return ((ExprEvalResult *)E)->EvalType;
3806}
3807
3808int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003809 return clang_EvalResult_getAsLongLong(E);
3810}
3811
3812long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003813 if (!E) {
3814 return 0;
3815 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003816 ExprEvalResult *Result = (ExprEvalResult*)E;
3817 if (Result->IsUnsignedInt)
3818 return Result->EvalData.unsignedVal;
3819 return Result->EvalData.intVal;
3820}
3821
3822unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3823 return ((ExprEvalResult *)E)->IsUnsignedInt;
3824}
3825
3826unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3827 if (!E) {
3828 return 0;
3829 }
3830
3831 ExprEvalResult *Result = (ExprEvalResult*)E;
3832 if (Result->IsUnsignedInt)
3833 return Result->EvalData.unsignedVal;
3834 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003835}
3836
3837double clang_EvalResult_getAsDouble(CXEvalResult E) {
3838 if (!E) {
3839 return 0;
3840 }
3841 return ((ExprEvalResult *)E)->EvalData.floatVal;
3842}
3843
3844const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3845 if (!E) {
3846 return nullptr;
3847 }
3848 return ((ExprEvalResult *)E)->EvalData.stringVal;
3849}
3850
3851static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3852 Expr::EvalResult ER;
3853 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003854 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003855 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003856
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003857 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003858 if (expr->isValueDependent())
3859 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003860 if (!expr->EvaluateAsRValue(ER, ctx))
3861 return nullptr;
3862
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003863 QualType rettype;
3864 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003865 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003866 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003867 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003868
David Blaikiebbc00882016-04-13 18:36:19 +00003869 if (ER.Val.isInt()) {
3870 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003871
3872 auto& val = ER.Val.getInt();
3873 if (val.isUnsigned()) {
3874 result->IsUnsignedInt = true;
3875 result->EvalData.unsignedVal = val.getZExtValue();
3876 } else {
3877 result->EvalData.intVal = val.getExtValue();
3878 }
3879
David Blaikiebbc00882016-04-13 18:36:19 +00003880 return result.release();
3881 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003882
David Blaikiebbc00882016-04-13 18:36:19 +00003883 if (ER.Val.isFloat()) {
3884 llvm::SmallVector<char, 100> Buffer;
3885 ER.Val.getFloat().toString(Buffer);
3886 std::string floatStr(Buffer.data(), Buffer.size());
3887 result->EvalType = CXEval_Float;
3888 bool ignored;
3889 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003890 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003891 llvm::APFloat::rmNearestTiesToEven, &ignored);
3892 result->EvalData.floatVal = apFloat.convertToDouble();
3893 return result.release();
3894 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003895
David Blaikiebbc00882016-04-13 18:36:19 +00003896 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3897 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3898 auto *subExpr = I->getSubExprAsWritten();
3899 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3900 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003901 const StringLiteral *StrE = nullptr;
3902 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003903 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003904
3905 if (ObjCExpr) {
3906 StrE = ObjCExpr->getString();
3907 result->EvalType = CXEval_ObjCStrLiteral;
3908 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003909 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003910 result->EvalType = CXEval_StrLiteral;
3911 }
3912
3913 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003914 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003915 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3916 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003917 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003918 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003919 }
3920 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3921 expr->getStmtClass() == Stmt::StringLiteralClass) {
3922 const StringLiteral *StrE = nullptr;
3923 const ObjCStringLiteral *ObjCExpr;
3924 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003925
David Blaikiebbc00882016-04-13 18:36:19 +00003926 if (ObjCExpr) {
3927 StrE = ObjCExpr->getString();
3928 result->EvalType = CXEval_ObjCStrLiteral;
3929 } else {
3930 StrE = cast<StringLiteral>(expr);
3931 result->EvalType = CXEval_StrLiteral;
3932 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003933
David Blaikiebbc00882016-04-13 18:36:19 +00003934 std::string strRef(StrE->getString().str());
3935 result->EvalData.stringVal = new char[strRef.size() + 1];
3936 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3937 result->EvalData.stringVal[strRef.size()] = '\0';
3938 return result.release();
3939 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003940
David Blaikiebbc00882016-04-13 18:36:19 +00003941 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3942 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003943
David Blaikiebbc00882016-04-13 18:36:19 +00003944 rettype = CC->getType();
3945 if (rettype.getAsString() == "CFStringRef" &&
3946 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003947
David Blaikiebbc00882016-04-13 18:36:19 +00003948 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3949 StringLiteral *S = getCFSTR_value(callExpr);
3950 if (S) {
3951 std::string strLiteral(S->getString().str());
3952 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003953
David Blaikiebbc00882016-04-13 18:36:19 +00003954 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3955 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3956 strLiteral.size());
3957 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003958 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003959 }
3960 }
3961
David Blaikiebbc00882016-04-13 18:36:19 +00003962 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3963 callExpr = static_cast<CallExpr *>(expr);
3964 rettype = callExpr->getCallReturnType(ctx);
3965
3966 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3967 return nullptr;
3968
3969 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3970 if (callExpr->getNumArgs() == 1 &&
3971 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3972 return nullptr;
3973 } else if (rettype.getAsString() == "CFStringRef") {
3974
3975 StringLiteral *S = getCFSTR_value(callExpr);
3976 if (S) {
3977 std::string strLiteral(S->getString().str());
3978 result->EvalType = CXEval_CFStr;
3979 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3980 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3981 strLiteral.size());
3982 result->EvalData.stringVal[strLiteral.size()] = '\0';
3983 return result.release();
3984 }
3985 }
3986 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3987 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3988 ValueDecl *V = D->getDecl();
3989 if (V->getKind() == Decl::Function) {
3990 std::string strName = V->getNameAsString();
3991 result->EvalType = CXEval_Other;
3992 result->EvalData.stringVal = new char[strName.size() + 1];
3993 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3994 result->EvalData.stringVal[strName.size()] = '\0';
3995 return result.release();
3996 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003997 }
3998
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003999 return nullptr;
4000}
4001
Alex Lorenz65317e12019-01-08 22:32:51 +00004002static const Expr *evaluateDeclExpr(const Decl *D) {
4003 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00004004 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00004005 if (auto *Var = dyn_cast<VarDecl>(D))
4006 return Var->getInit();
4007 else if (auto *Field = dyn_cast<FieldDecl>(D))
4008 return Field->getInClassInitializer();
4009 return nullptr;
4010}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00004011
Alex Lorenz65317e12019-01-08 22:32:51 +00004012static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
4013 assert(CS && "invalid compound statement");
4014 for (auto *bodyIterator : CS->body()) {
4015 if (const auto *E = dyn_cast<Expr>(bodyIterator))
4016 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00004017 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00004018 return nullptr;
4019}
4020
Alex Lorenz65317e12019-01-08 22:32:51 +00004021CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4022 if (const Expr *E =
4023 clang_getCursorKind(C) == CXCursor_CompoundStmt
4024 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
4025 : evaluateDeclExpr(getCursorDecl(C)))
4026 return const_cast<CXEvalResult>(
4027 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4028 return nullptr;
4029}
4030
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004031unsigned clang_Cursor_hasAttrs(CXCursor C) {
4032 const Decl *D = getCursorDecl(C);
4033 if (!D) {
4034 return 0;
4035 }
4036
4037 if (D->hasAttrs()) {
4038 return 1;
4039 }
4040
4041 return 0;
4042}
Guy Benyei11169dd2012-12-18 14:30:41 +00004043unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4044 return CXSaveTranslationUnit_None;
4045}
4046
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004047static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4048 const char *FileName,
4049 unsigned options) {
4050 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004051 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4052 setThreadBackgroundPriority();
4053
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004054 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4055 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004056}
4057
4058int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4059 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004060 LOG_FUNC_SECTION {
4061 *Log << TU << ' ' << FileName;
4062 }
4063
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004064 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004065 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004067 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004068
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004069 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4071 if (!CXXUnit->hasSema())
4072 return CXSaveError_InvalidTU;
4073
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004074 CXSaveError result;
4075 auto SaveTranslationUnitImpl = [=, &result]() {
4076 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4077 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004078
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004079 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004080 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004081
4082 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4083 PrintLibclangResourceUsage(TU);
4084
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004085 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004086 }
4087
4088 // We have an AST that has invalid nodes due to compiler errors.
4089 // Use a crash recovery thread for protection.
4090
4091 llvm::CrashRecoveryContext CRC;
4092
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004093 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4095 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4096 fprintf(stderr, " 'options' : %d,\n", options);
4097 fprintf(stderr, "}\n");
4098
4099 return CXSaveError_Unknown;
4100
4101 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4102 PrintLibclangResourceUsage(TU);
4103 }
4104
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004105 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004106}
4107
4108void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4109 if (CTUnit) {
4110 // If the translation unit has been marked as unsafe to free, just discard
4111 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004112 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4113 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 return;
4115
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004116 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004117 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4119 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004120 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 delete CTUnit;
4122 }
4123}
4124
Erik Verbruggen346066b2017-05-30 14:25:54 +00004125unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4126 if (CTUnit) {
4127 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4128
4129 if (Unit && Unit->isUnsafeToFree())
4130 return false;
4131
4132 Unit->ResetForParse();
4133 return true;
4134 }
4135
4136 return false;
4137}
4138
Guy Benyei11169dd2012-12-18 14:30:41 +00004139unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4140 return CXReparse_None;
4141}
4142
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004143static CXErrorCode
4144clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4145 ArrayRef<CXUnsavedFile> unsaved_files,
4146 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004147 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004148 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004149 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004150 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004151 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004152
4153 // Reset the associated diagnostics.
4154 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004155 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004156
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004157 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4159 setThreadBackgroundPriority();
4160
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004161 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004163
4164 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4165 new std::vector<ASTUnit::RemappedFile>());
4166
Guy Benyei11169dd2012-12-18 14:30:41 +00004167 // Recover resources if we crash before exiting this function.
4168 llvm::CrashRecoveryContextCleanupRegistrar<
4169 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004170
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004171 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004172 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004173 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004174 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004175 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004176
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004177 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4178 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004179 return CXError_Success;
4180 if (isASTReadError(CXXUnit))
4181 return CXError_ASTReadError;
4182 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004183}
4184
4185int clang_reparseTranslationUnit(CXTranslationUnit TU,
4186 unsigned num_unsaved_files,
4187 struct CXUnsavedFile *unsaved_files,
4188 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004189 LOG_FUNC_SECTION {
4190 *Log << TU;
4191 }
4192
Alp Toker9d85b182014-07-07 01:23:14 +00004193 if (num_unsaved_files && !unsaved_files)
4194 return CXError_InvalidArguments;
4195
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004196 CXErrorCode result;
4197 auto ReparseTranslationUnitImpl = [=, &result]() {
4198 result = clang_reparseTranslationUnit_Impl(
4199 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4200 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004201
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 llvm::CrashRecoveryContext CRC;
4203
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004204 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004206 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004207 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4209 PrintLibclangResourceUsage(TU);
4210
Alp Toker5c532982014-07-07 22:42:03 +00004211 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004212}
4213
4214
4215CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004216 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004217 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004218 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004219 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004220
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004221 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004222 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004223}
4224
4225CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004226 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004227 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004228 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004229 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004230
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004231 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4233}
4234
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004235CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4236 if (isNotUsableTU(CTUnit)) {
4237 LOG_BAD_TU(CTUnit);
4238 return nullptr;
4239 }
4240
4241 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4242 impl->TranslationUnit = CTUnit;
4243 return impl;
4244}
4245
4246CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4247 if (!TargetInfo)
4248 return cxstring::createEmpty();
4249
4250 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4251 assert(!isNotUsableTU(CTUnit) &&
4252 "Unexpected unusable translation unit in TargetInfo");
4253
4254 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4255 std::string Triple =
4256 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4257 return cxstring::createDup(Triple);
4258}
4259
4260int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4261 if (!TargetInfo)
4262 return -1;
4263
4264 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4265 assert(!isNotUsableTU(CTUnit) &&
4266 "Unexpected unusable translation unit in TargetInfo");
4267
4268 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4269 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4270}
4271
4272void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4273 if (!TargetInfo)
4274 return;
4275
4276 delete TargetInfo;
4277}
4278
Guy Benyei11169dd2012-12-18 14:30:41 +00004279//===----------------------------------------------------------------------===//
4280// CXFile Operations.
4281//===----------------------------------------------------------------------===//
4282
Guy Benyei11169dd2012-12-18 14:30:41 +00004283CXString clang_getFileName(CXFile SFile) {
4284 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004285 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004286
4287 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004288 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004289}
4290
4291time_t clang_getFileTime(CXFile SFile) {
4292 if (!SFile)
4293 return 0;
4294
4295 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4296 return FEnt->getModificationTime();
4297}
4298
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004299CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004300 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004301 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004302 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004303 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004304
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004305 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004306
4307 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004308 auto File = FMgr.getFile(file_name);
4309 if (!File)
4310 return nullptr;
4311 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004312}
4313
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004314const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4315 size_t *size) {
4316 if (isNotUsableTU(TU)) {
4317 LOG_BAD_TU(TU);
4318 return nullptr;
4319 }
4320
4321 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4322 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4323 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004324 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004325 if (Invalid) {
4326 if (size)
4327 *size = 0;
4328 return nullptr;
4329 }
4330 if (size)
4331 *size = buf->getBufferSize();
4332 return buf->getBufferStart();
4333}
4334
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004335unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4336 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004337 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004338 LOG_BAD_TU(TU);
4339 return 0;
4340 }
4341
4342 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 return 0;
4344
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004345 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 FileEntry *FEnt = static_cast<FileEntry *>(file);
4347 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4348 .isFileMultipleIncludeGuarded(FEnt);
4349}
4350
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004351int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4352 if (!file || !outID)
4353 return 1;
4354
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004355 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004356 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4357 outID->data[0] = ID.getDevice();
4358 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004359 outID->data[2] = FEnt->getModificationTime();
4360 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004361}
4362
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004363int clang_File_isEqual(CXFile file1, CXFile file2) {
4364 if (file1 == file2)
4365 return true;
4366
4367 if (!file1 || !file2)
4368 return false;
4369
4370 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4371 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4372 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4373}
4374
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004375CXString clang_File_tryGetRealPathName(CXFile SFile) {
4376 if (!SFile)
4377 return cxstring::createNull();
4378
4379 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4380 return cxstring::createRef(FEnt->tryGetRealPathName());
4381}
4382
Guy Benyei11169dd2012-12-18 14:30:41 +00004383//===----------------------------------------------------------------------===//
4384// CXCursor Operations.
4385//===----------------------------------------------------------------------===//
4386
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004387static const Decl *getDeclFromExpr(const Stmt *E) {
4388 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 return getDeclFromExpr(CE->getSubExpr());
4390
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004391 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004393 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004395 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004397 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 if (PRE->isExplicitProperty())
4399 return PRE->getExplicitProperty();
4400 // It could be messaging both getter and setter as in:
4401 // ++myobj.myprop;
4402 // in which case prefer to associate the setter since it is less obvious
4403 // from inspecting the source that the setter is going to get called.
4404 if (PRE->isMessagingSetter())
4405 return PRE->getImplicitPropertySetter();
4406 return PRE->getImplicitPropertyGetter();
4407 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004408 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004410 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 if (Expr *Src = OVE->getSourceExpr())
4412 return getDeclFromExpr(Src);
4413
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004414 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004416 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 if (!CE->isElidable())
4418 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004419 if (const CXXInheritedCtorInitExpr *CE =
4420 dyn_cast<CXXInheritedCtorInitExpr>(E))
4421 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004422 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 return OME->getMethodDecl();
4424
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004425 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004427 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4429 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004430 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4432 isa<ParmVarDecl>(SizeOfPack->getPack()))
4433 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004434
4435 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004436}
4437
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004438static SourceLocation getLocationFromExpr(const Expr *E) {
4439 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 return getLocationFromExpr(CE->getSubExpr());
4441
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004442 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004444 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004446 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004448 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004450 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004452 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004454
4455 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004456}
4457
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004458extern "C" {
4459
Guy Benyei11169dd2012-12-18 14:30:41 +00004460unsigned clang_visitChildren(CXCursor parent,
4461 CXCursorVisitor visitor,
4462 CXClientData client_data) {
4463 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4464 /*VisitPreprocessorLast=*/false);
4465 return CursorVis.VisitChildren(parent);
4466}
4467
4468#ifndef __has_feature
4469#define __has_feature(x) 0
4470#endif
4471#if __has_feature(blocks)
4472typedef enum CXChildVisitResult
4473 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4474
4475static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4476 CXClientData client_data) {
4477 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4478 return block(cursor, parent);
4479}
4480#else
4481// If we are compiled with a compiler that doesn't have native blocks support,
4482// define and call the block manually, so the
4483typedef struct _CXChildVisitResult
4484{
4485 void *isa;
4486 int flags;
4487 int reserved;
4488 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4489 CXCursor);
4490} *CXCursorVisitorBlock;
4491
4492static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4493 CXClientData client_data) {
4494 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4495 return block->invoke(block, cursor, parent);
4496}
4497#endif
4498
4499
4500unsigned clang_visitChildrenWithBlock(CXCursor parent,
4501 CXCursorVisitorBlock block) {
4502 return clang_visitChildren(parent, visitWithBlock, block);
4503}
4504
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004505static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004507 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004508
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004509 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004511 if (const ObjCPropertyImplDecl *PropImpl =
4512 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004514 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004515
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004516 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004518 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004519
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004520 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 }
4522
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004523 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004524 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004525
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004526 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4528 // and returns different names. NamedDecl returns the class name and
4529 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004530 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004531
4532 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004533 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004534
4535 SmallString<1024> S;
4536 llvm::raw_svector_ostream os(S);
4537 ND->printName(os);
4538
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004539 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004540}
4541
4542CXString clang_getCursorSpelling(CXCursor C) {
4543 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004544 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004545
4546 if (clang_isReference(C.kind)) {
4547 switch (C.kind) {
4548 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004549 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004550 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 }
4552 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004553 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004554 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 }
4556 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004557 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004559 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 }
4561 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004562 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004563 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 }
4565 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004566 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 assert(Type && "Missing type decl");
4568
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004569 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 getAsString());
4571 }
4572 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004573 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 assert(Template && "Missing template decl");
4575
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004576 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 }
4578
4579 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004580 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 assert(NS && "Missing namespace decl");
4582
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004583 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 }
4585
4586 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004587 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004588 assert(Field && "Missing member decl");
4589
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004590 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 }
4592
4593 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004594 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 assert(Label && "Missing label");
4596
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004597 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 }
4599
4600 case CXCursor_OverloadedDeclRef: {
4601 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004602 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4603 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004604 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004605 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004607 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004608 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 OverloadedTemplateStorage *Ovl
4610 = Storage.get<OverloadedTemplateStorage*>();
4611 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004612 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004613 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 }
4615
4616 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004617 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 assert(Var && "Missing variable decl");
4619
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004620 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 }
4622
4623 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004624 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 }
4626 }
4627
4628 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004629 const Expr *E = getCursorExpr(C);
4630
4631 if (C.kind == CXCursor_ObjCStringLiteral ||
4632 C.kind == CXCursor_StringLiteral) {
4633 const StringLiteral *SLit;
4634 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4635 SLit = OSL->getString();
4636 } else {
4637 SLit = cast<StringLiteral>(E);
4638 }
4639 SmallString<256> Buf;
4640 llvm::raw_svector_ostream OS(Buf);
4641 SLit->outputString(OS);
4642 return cxstring::createDup(OS.str());
4643 }
4644
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004645 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 if (D)
4647 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004648 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 }
4650
4651 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004652 const Stmt *S = getCursorStmt(C);
4653 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004654 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004655
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004656 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 }
4658
4659 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004660 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 ->getNameStart());
4662
4663 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004664 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 ->getNameStart());
4666
4667 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004668 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004669
4670 if (clang_isDeclaration(C.kind))
4671 return getDeclSpelling(getCursorDecl(C));
4672
4673 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004674 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004675 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004676 }
4677
4678 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004679 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004680 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 }
4682
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004683 if (C.kind == CXCursor_PackedAttr) {
4684 return cxstring::createRef("packed");
4685 }
4686
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004687 if (C.kind == CXCursor_VisibilityAttr) {
4688 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4689 switch (AA->getVisibility()) {
4690 case VisibilityAttr::VisibilityType::Default:
4691 return cxstring::createRef("default");
4692 case VisibilityAttr::VisibilityType::Hidden:
4693 return cxstring::createRef("hidden");
4694 case VisibilityAttr::VisibilityType::Protected:
4695 return cxstring::createRef("protected");
4696 }
4697 llvm_unreachable("unknown visibility type");
4698 }
4699
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004700 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004701}
4702
4703CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4704 unsigned pieceIndex,
4705 unsigned options) {
4706 if (clang_Cursor_isNull(C))
4707 return clang_getNullRange();
4708
4709 ASTContext &Ctx = getCursorContext(C);
4710
4711 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004712 const Stmt *S = getCursorStmt(C);
4713 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 if (pieceIndex > 0)
4715 return clang_getNullRange();
4716 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4717 }
4718
4719 return clang_getNullRange();
4720 }
4721
4722 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004723 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4725 if (pieceIndex >= ME->getNumSelectorLocs())
4726 return clang_getNullRange();
4727 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4728 }
4729 }
4730
4731 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4732 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004733 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4735 if (pieceIndex >= MD->getNumSelectorLocs())
4736 return clang_getNullRange();
4737 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4738 }
4739 }
4740
4741 if (C.kind == CXCursor_ObjCCategoryDecl ||
4742 C.kind == CXCursor_ObjCCategoryImplDecl) {
4743 if (pieceIndex > 0)
4744 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004745 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004746 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4747 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004748 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4750 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4751 }
4752
4753 if (C.kind == CXCursor_ModuleImportDecl) {
4754 if (pieceIndex > 0)
4755 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004756 if (const ImportDecl *ImportD =
4757 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4759 if (!Locs.empty())
4760 return cxloc::translateSourceRange(Ctx,
4761 SourceRange(Locs.front(), Locs.back()));
4762 }
4763 return clang_getNullRange();
4764 }
4765
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004766 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004767 C.kind == CXCursor_ConversionFunction ||
4768 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004769 if (pieceIndex > 0)
4770 return clang_getNullRange();
4771 if (const FunctionDecl *FD =
4772 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4773 DeclarationNameInfo FunctionName = FD->getNameInfo();
4774 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4775 }
4776 return clang_getNullRange();
4777 }
4778
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 // FIXME: A CXCursor_InclusionDirective should give the location of the
4780 // filename, but we don't keep track of this.
4781
4782 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4783 // but we don't keep track of this.
4784
4785 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4786 // but we don't keep track of this.
4787
4788 // Default handling, give the location of the cursor.
4789
4790 if (pieceIndex > 0)
4791 return clang_getNullRange();
4792
4793 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4794 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4795 return cxloc::translateSourceRange(Ctx, Loc);
4796}
4797
Eli Bendersky44a206f2014-07-31 18:04:56 +00004798CXString clang_Cursor_getMangling(CXCursor C) {
4799 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4800 return cxstring::createEmpty();
4801
Eli Bendersky44a206f2014-07-31 18:04:56 +00004802 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004803 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004804 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4805 return cxstring::createEmpty();
4806
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004807 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004808 ASTNameGenerator ASTNameGen(Ctx);
4809 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004810}
4811
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004812CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4813 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4814 return nullptr;
4815
4816 const Decl *D = getCursorDecl(C);
4817 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4818 return nullptr;
4819
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004820 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004821 ASTNameGenerator ASTNameGen(Ctx);
4822 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004823 return cxstring::createSet(Manglings);
4824}
4825
Dave Lee1a532c92017-09-22 16:58:57 +00004826CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4827 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4828 return nullptr;
4829
4830 const Decl *D = getCursorDecl(C);
4831 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4832 return nullptr;
4833
4834 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004835 ASTNameGenerator ASTNameGen(Ctx);
4836 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004837 return cxstring::createSet(Manglings);
4838}
4839
Jonathan Coe45ef5032018-01-16 10:19:56 +00004840CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4841 if (clang_Cursor_isNull(C))
4842 return 0;
4843 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4844}
4845
4846void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4847 if (Policy)
4848 delete static_cast<PrintingPolicy *>(Policy);
4849}
4850
4851unsigned
4852clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4853 enum CXPrintingPolicyProperty Property) {
4854 if (!Policy)
4855 return 0;
4856
4857 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4858 switch (Property) {
4859 case CXPrintingPolicy_Indentation:
4860 return P->Indentation;
4861 case CXPrintingPolicy_SuppressSpecifiers:
4862 return P->SuppressSpecifiers;
4863 case CXPrintingPolicy_SuppressTagKeyword:
4864 return P->SuppressTagKeyword;
4865 case CXPrintingPolicy_IncludeTagDefinition:
4866 return P->IncludeTagDefinition;
4867 case CXPrintingPolicy_SuppressScope:
4868 return P->SuppressScope;
4869 case CXPrintingPolicy_SuppressUnwrittenScope:
4870 return P->SuppressUnwrittenScope;
4871 case CXPrintingPolicy_SuppressInitializers:
4872 return P->SuppressInitializers;
4873 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4874 return P->ConstantArraySizeAsWritten;
4875 case CXPrintingPolicy_AnonymousTagLocations:
4876 return P->AnonymousTagLocations;
4877 case CXPrintingPolicy_SuppressStrongLifetime:
4878 return P->SuppressStrongLifetime;
4879 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4880 return P->SuppressLifetimeQualifiers;
4881 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4882 return P->SuppressTemplateArgsInCXXConstructors;
4883 case CXPrintingPolicy_Bool:
4884 return P->Bool;
4885 case CXPrintingPolicy_Restrict:
4886 return P->Restrict;
4887 case CXPrintingPolicy_Alignof:
4888 return P->Alignof;
4889 case CXPrintingPolicy_UnderscoreAlignof:
4890 return P->UnderscoreAlignof;
4891 case CXPrintingPolicy_UseVoidForZeroParams:
4892 return P->UseVoidForZeroParams;
4893 case CXPrintingPolicy_TerseOutput:
4894 return P->TerseOutput;
4895 case CXPrintingPolicy_PolishForDeclaration:
4896 return P->PolishForDeclaration;
4897 case CXPrintingPolicy_Half:
4898 return P->Half;
4899 case CXPrintingPolicy_MSWChar:
4900 return P->MSWChar;
4901 case CXPrintingPolicy_IncludeNewlines:
4902 return P->IncludeNewlines;
4903 case CXPrintingPolicy_MSVCFormatting:
4904 return P->MSVCFormatting;
4905 case CXPrintingPolicy_ConstantsAsWritten:
4906 return P->ConstantsAsWritten;
4907 case CXPrintingPolicy_SuppressImplicitBase:
4908 return P->SuppressImplicitBase;
4909 case CXPrintingPolicy_FullyQualifiedName:
4910 return P->FullyQualifiedName;
4911 }
4912
4913 assert(false && "Invalid CXPrintingPolicyProperty");
4914 return 0;
4915}
4916
4917void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4918 enum CXPrintingPolicyProperty Property,
4919 unsigned Value) {
4920 if (!Policy)
4921 return;
4922
4923 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4924 switch (Property) {
4925 case CXPrintingPolicy_Indentation:
4926 P->Indentation = Value;
4927 return;
4928 case CXPrintingPolicy_SuppressSpecifiers:
4929 P->SuppressSpecifiers = Value;
4930 return;
4931 case CXPrintingPolicy_SuppressTagKeyword:
4932 P->SuppressTagKeyword = Value;
4933 return;
4934 case CXPrintingPolicy_IncludeTagDefinition:
4935 P->IncludeTagDefinition = Value;
4936 return;
4937 case CXPrintingPolicy_SuppressScope:
4938 P->SuppressScope = Value;
4939 return;
4940 case CXPrintingPolicy_SuppressUnwrittenScope:
4941 P->SuppressUnwrittenScope = Value;
4942 return;
4943 case CXPrintingPolicy_SuppressInitializers:
4944 P->SuppressInitializers = Value;
4945 return;
4946 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4947 P->ConstantArraySizeAsWritten = Value;
4948 return;
4949 case CXPrintingPolicy_AnonymousTagLocations:
4950 P->AnonymousTagLocations = Value;
4951 return;
4952 case CXPrintingPolicy_SuppressStrongLifetime:
4953 P->SuppressStrongLifetime = Value;
4954 return;
4955 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4956 P->SuppressLifetimeQualifiers = Value;
4957 return;
4958 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4959 P->SuppressTemplateArgsInCXXConstructors = Value;
4960 return;
4961 case CXPrintingPolicy_Bool:
4962 P->Bool = Value;
4963 return;
4964 case CXPrintingPolicy_Restrict:
4965 P->Restrict = Value;
4966 return;
4967 case CXPrintingPolicy_Alignof:
4968 P->Alignof = Value;
4969 return;
4970 case CXPrintingPolicy_UnderscoreAlignof:
4971 P->UnderscoreAlignof = Value;
4972 return;
4973 case CXPrintingPolicy_UseVoidForZeroParams:
4974 P->UseVoidForZeroParams = Value;
4975 return;
4976 case CXPrintingPolicy_TerseOutput:
4977 P->TerseOutput = Value;
4978 return;
4979 case CXPrintingPolicy_PolishForDeclaration:
4980 P->PolishForDeclaration = Value;
4981 return;
4982 case CXPrintingPolicy_Half:
4983 P->Half = Value;
4984 return;
4985 case CXPrintingPolicy_MSWChar:
4986 P->MSWChar = Value;
4987 return;
4988 case CXPrintingPolicy_IncludeNewlines:
4989 P->IncludeNewlines = Value;
4990 return;
4991 case CXPrintingPolicy_MSVCFormatting:
4992 P->MSVCFormatting = Value;
4993 return;
4994 case CXPrintingPolicy_ConstantsAsWritten:
4995 P->ConstantsAsWritten = Value;
4996 return;
4997 case CXPrintingPolicy_SuppressImplicitBase:
4998 P->SuppressImplicitBase = Value;
4999 return;
5000 case CXPrintingPolicy_FullyQualifiedName:
5001 P->FullyQualifiedName = Value;
5002 return;
5003 }
5004
5005 assert(false && "Invalid CXPrintingPolicyProperty");
5006}
5007
5008CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
5009 if (clang_Cursor_isNull(C))
5010 return cxstring::createEmpty();
5011
5012 if (clang_isDeclaration(C.kind)) {
5013 const Decl *D = getCursorDecl(C);
5014 if (!D)
5015 return cxstring::createEmpty();
5016
5017 SmallString<128> Str;
5018 llvm::raw_svector_ostream OS(Str);
5019 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
5020 D->print(OS, UserPolicy ? *UserPolicy
5021 : getCursorContext(C).getPrintingPolicy());
5022
5023 return cxstring::createDup(OS.str());
5024 }
5025
5026 return cxstring::createEmpty();
5027}
5028
Guy Benyei11169dd2012-12-18 14:30:41 +00005029CXString clang_getCursorDisplayName(CXCursor C) {
5030 if (!clang_isDeclaration(C.kind))
5031 return clang_getCursorSpelling(C);
5032
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005033 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005035 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005036
5037 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005038 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 D = FunTmpl->getTemplatedDecl();
5040
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005041 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 SmallString<64> Str;
5043 llvm::raw_svector_ostream OS(Str);
5044 OS << *Function;
5045 if (Function->getPrimaryTemplate())
5046 OS << "<>";
5047 OS << "(";
5048 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5049 if (I)
5050 OS << ", ";
5051 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5052 }
5053
5054 if (Function->isVariadic()) {
5055 if (Function->getNumParams())
5056 OS << ", ";
5057 OS << "...";
5058 }
5059 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005060 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 }
5062
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005063 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 SmallString<64> Str;
5065 llvm::raw_svector_ostream OS(Str);
5066 OS << *ClassTemplate;
5067 OS << "<";
5068 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5069 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5070 if (I)
5071 OS << ", ";
5072
5073 NamedDecl *Param = Params->getParam(I);
5074 if (Param->getIdentifier()) {
5075 OS << Param->getIdentifier()->getName();
5076 continue;
5077 }
5078
5079 // There is no parameter name, which makes this tricky. Try to come up
5080 // with something useful that isn't too long.
5081 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Saar Razff1e0fc2020-01-15 02:48:42 +02005082 if (const auto *TC = TTP->getTypeConstraint()) {
5083 TC->getConceptNameInfo().printName(OS, Policy);
5084 if (TC->hasExplicitTemplateArgs())
5085 OS << "<...>";
5086 } else
5087 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 else if (NonTypeTemplateParmDecl *NTTP
5089 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5090 OS << NTTP->getType().getAsString(Policy);
5091 else
5092 OS << "template<...> class";
5093 }
5094
5095 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005096 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 }
5098
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005099 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5101 // If the type was explicitly written, use that.
5102 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005103 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005104
Benjamin Kramer9170e912013-02-22 15:46:01 +00005105 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 llvm::raw_svector_ostream OS(Str);
5107 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005108 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5109 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005110 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 }
5112
5113 return clang_getCursorSpelling(C);
5114}
5115
5116CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5117 switch (Kind) {
5118 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005182 case CXCursor_FixedPointLiteral:
5183 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005198 case CXCursor_OMPArraySectionExpr:
5199 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005250 case CXCursor_ObjCAvailabilityCheckExpr:
5251 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005252 case CXCursor_ObjCSelfExpr:
5253 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005257 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005265 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005277 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005280 case CXCursor_BuiltinBitCastExpr:
5281 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005297 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005307 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005309 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005311 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005313 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005315 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005317 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005319 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005321 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005323 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005325 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005327 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005328 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005329 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005330 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005331 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005333 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005335 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005337 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005338 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005339 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005340 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005341 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005343 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005344 case CXCursor_SEHLeaveStmt:
5345 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005347 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005349 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005350 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005351 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005352 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005353 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005355 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005357 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005359 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005360 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005361 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005362 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005363 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005365 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005367 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005369 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005370 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005371 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005372 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005373 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005374 case CXCursor_PackedAttr:
5375 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005376 case CXCursor_PureAttr:
5377 return cxstring::createRef("attribute(pure)");
5378 case CXCursor_ConstAttr:
5379 return cxstring::createRef("attribute(const)");
5380 case CXCursor_NoDuplicateAttr:
5381 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005382 case CXCursor_CUDAConstantAttr:
5383 return cxstring::createRef("attribute(constant)");
5384 case CXCursor_CUDADeviceAttr:
5385 return cxstring::createRef("attribute(device)");
5386 case CXCursor_CUDAGlobalAttr:
5387 return cxstring::createRef("attribute(global)");
5388 case CXCursor_CUDAHostAttr:
5389 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005390 case CXCursor_CUDASharedAttr:
5391 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005392 case CXCursor_VisibilityAttr:
5393 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005394 case CXCursor_DLLExport:
5395 return cxstring::createRef("attribute(dllexport)");
5396 case CXCursor_DLLImport:
5397 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005398 case CXCursor_NSReturnsRetained:
5399 return cxstring::createRef("attribute(ns_returns_retained)");
5400 case CXCursor_NSReturnsNotRetained:
5401 return cxstring::createRef("attribute(ns_returns_not_retained)");
5402 case CXCursor_NSReturnsAutoreleased:
5403 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5404 case CXCursor_NSConsumesSelf:
5405 return cxstring::createRef("attribute(ns_consumes_self)");
5406 case CXCursor_NSConsumed:
5407 return cxstring::createRef("attribute(ns_consumed)");
5408 case CXCursor_ObjCException:
5409 return cxstring::createRef("attribute(objc_exception)");
5410 case CXCursor_ObjCNSObject:
5411 return cxstring::createRef("attribute(NSObject)");
5412 case CXCursor_ObjCIndependentClass:
5413 return cxstring::createRef("attribute(objc_independent_class)");
5414 case CXCursor_ObjCPreciseLifetime:
5415 return cxstring::createRef("attribute(objc_precise_lifetime)");
5416 case CXCursor_ObjCReturnsInnerPointer:
5417 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5418 case CXCursor_ObjCRequiresSuper:
5419 return cxstring::createRef("attribute(objc_requires_super)");
5420 case CXCursor_ObjCRootClass:
5421 return cxstring::createRef("attribute(objc_root_class)");
5422 case CXCursor_ObjCSubclassingRestricted:
5423 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5424 case CXCursor_ObjCExplicitProtocolImpl:
5425 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5426 case CXCursor_ObjCDesignatedInitializer:
5427 return cxstring::createRef("attribute(objc_designated_initializer)");
5428 case CXCursor_ObjCRuntimeVisible:
5429 return cxstring::createRef("attribute(objc_runtime_visible)");
5430 case CXCursor_ObjCBoxable:
5431 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005432 case CXCursor_FlagEnum:
5433 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005434 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005435 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005436 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005437 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005438 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005439 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005441 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005442 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005443 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005444 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005445 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005446 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005447 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005448 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005449 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005451 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005453 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005454 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005455 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005457 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005458 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005459 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005460 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005461 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005462 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005463 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005464 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005465 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005466 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005467 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005468 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005469 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005470 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005471 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005472 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005473 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005474 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005475 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005476 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005477 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005478 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005479 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005480 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005481 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005482 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005483 return cxstring::createRef("OMPParallelDirective");
5484 case CXCursor_OMPSimdDirective:
5485 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005486 case CXCursor_OMPForDirective:
5487 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005488 case CXCursor_OMPForSimdDirective:
5489 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005490 case CXCursor_OMPSectionsDirective:
5491 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005492 case CXCursor_OMPSectionDirective:
5493 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005494 case CXCursor_OMPSingleDirective:
5495 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005496 case CXCursor_OMPMasterDirective:
5497 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005498 case CXCursor_OMPCriticalDirective:
5499 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005500 case CXCursor_OMPParallelForDirective:
5501 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005502 case CXCursor_OMPParallelForSimdDirective:
5503 return cxstring::createRef("OMPParallelForSimdDirective");
cchen47d60942019-12-05 13:43:48 -05005504 case CXCursor_OMPParallelMasterDirective:
5505 return cxstring::createRef("OMPParallelMasterDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005506 case CXCursor_OMPParallelSectionsDirective:
5507 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005508 case CXCursor_OMPTaskDirective:
5509 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005510 case CXCursor_OMPTaskyieldDirective:
5511 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005512 case CXCursor_OMPBarrierDirective:
5513 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005514 case CXCursor_OMPTaskwaitDirective:
5515 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005516 case CXCursor_OMPTaskgroupDirective:
5517 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005518 case CXCursor_OMPFlushDirective:
5519 return cxstring::createRef("OMPFlushDirective");
Alexey Bataevc112e942020-02-28 09:52:15 -05005520 case CXCursor_OMPDepobjDirective:
5521 return cxstring::createRef("OMPDepobjDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005522 case CXCursor_OMPOrderedDirective:
5523 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005524 case CXCursor_OMPAtomicDirective:
5525 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005526 case CXCursor_OMPTargetDirective:
5527 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005528 case CXCursor_OMPTargetDataDirective:
5529 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005530 case CXCursor_OMPTargetEnterDataDirective:
5531 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005532 case CXCursor_OMPTargetExitDataDirective:
5533 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005534 case CXCursor_OMPTargetParallelDirective:
5535 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005536 case CXCursor_OMPTargetParallelForDirective:
5537 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005538 case CXCursor_OMPTargetUpdateDirective:
5539 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005540 case CXCursor_OMPTeamsDirective:
5541 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005542 case CXCursor_OMPCancellationPointDirective:
5543 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005544 case CXCursor_OMPCancelDirective:
5545 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005546 case CXCursor_OMPTaskLoopDirective:
5547 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005548 case CXCursor_OMPTaskLoopSimdDirective:
5549 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005550 case CXCursor_OMPMasterTaskLoopDirective:
5551 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005552 case CXCursor_OMPMasterTaskLoopSimdDirective:
5553 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005554 case CXCursor_OMPParallelMasterTaskLoopDirective:
5555 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Alexey Bataev14a388f2019-10-25 10:27:13 -04005556 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5557 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005558 case CXCursor_OMPDistributeDirective:
5559 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005560 case CXCursor_OMPDistributeParallelForDirective:
5561 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005562 case CXCursor_OMPDistributeParallelForSimdDirective:
5563 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005564 case CXCursor_OMPDistributeSimdDirective:
5565 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005566 case CXCursor_OMPTargetParallelForSimdDirective:
5567 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005568 case CXCursor_OMPTargetSimdDirective:
5569 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005570 case CXCursor_OMPTeamsDistributeDirective:
5571 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005572 case CXCursor_OMPTeamsDistributeSimdDirective:
5573 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005574 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5575 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005576 case CXCursor_OMPTeamsDistributeParallelForDirective:
5577 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005578 case CXCursor_OMPTargetTeamsDirective:
5579 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005580 case CXCursor_OMPTargetTeamsDistributeDirective:
5581 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005582 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5583 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005584 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5585 return cxstring::createRef(
5586 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005587 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5588 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005589 case CXCursor_OverloadCandidate:
5590 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005591 case CXCursor_TypeAliasTemplateDecl:
5592 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005593 case CXCursor_StaticAssert:
5594 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005595 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005596 return cxstring::createRef("FriendDecl");
5597 case CXCursor_ConvergentAttr:
5598 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005599 case CXCursor_WarnUnusedAttr:
5600 return cxstring::createRef("attribute(warn_unused)");
5601 case CXCursor_WarnUnusedResultAttr:
5602 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005603 case CXCursor_AlignedAttr:
5604 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005605 }
5606
5607 llvm_unreachable("Unhandled CXCursorKind");
5608}
5609
5610struct GetCursorData {
5611 SourceLocation TokenBeginLoc;
5612 bool PointsAtMacroArgExpansion;
5613 bool VisitedObjCPropertyImplDecl;
5614 SourceLocation VisitedDeclaratorDeclStartLoc;
5615 CXCursor &BestCursor;
5616
5617 GetCursorData(SourceManager &SM,
5618 SourceLocation tokenBegin, CXCursor &outputCursor)
5619 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5620 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5621 VisitedObjCPropertyImplDecl = false;
5622 }
5623};
5624
5625static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5626 CXCursor parent,
5627 CXClientData client_data) {
5628 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5629 CXCursor *BestCursor = &Data->BestCursor;
5630
5631 // If we point inside a macro argument we should provide info of what the
5632 // token is so use the actual cursor, don't replace it with a macro expansion
5633 // cursor.
5634 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5635 return CXChildVisit_Recurse;
5636
5637 if (clang_isDeclaration(cursor.kind)) {
5638 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005639 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005640 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5641 if (MD->isImplicit())
5642 return CXChildVisit_Break;
5643
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005644 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005645 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5646 // Check that when we have multiple @class references in the same line,
5647 // that later ones do not override the previous ones.
5648 // If we have:
5649 // @class Foo, Bar;
5650 // source ranges for both start at '@', so 'Bar' will end up overriding
5651 // 'Foo' even though the cursor location was at 'Foo'.
5652 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5653 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005654 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5656 if (PrevID != ID &&
5657 !PrevID->isThisDeclarationADefinition() &&
5658 !ID->isThisDeclarationADefinition())
5659 return CXChildVisit_Break;
5660 }
5661
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005662 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005663 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5664 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5665 // Check that when we have multiple declarators in the same line,
5666 // that later ones do not override the previous ones.
5667 // If we have:
5668 // int Foo, Bar;
5669 // source ranges for both start at 'int', so 'Bar' will end up overriding
5670 // 'Foo' even though the cursor location was at 'Foo'.
5671 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5672 return CXChildVisit_Break;
5673 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5674
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005675 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005676 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5677 (void)PropImp;
5678 // Check that when we have multiple @synthesize in the same line,
5679 // that later ones do not override the previous ones.
5680 // If we have:
5681 // @synthesize Foo, Bar;
5682 // source ranges for both start at '@', so 'Bar' will end up overriding
5683 // 'Foo' even though the cursor location was at 'Foo'.
5684 if (Data->VisitedObjCPropertyImplDecl)
5685 return CXChildVisit_Break;
5686 Data->VisitedObjCPropertyImplDecl = true;
5687 }
5688 }
5689
5690 if (clang_isExpression(cursor.kind) &&
5691 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005692 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005693 // Avoid having the cursor of an expression replace the declaration cursor
5694 // when the expression source range overlaps the declaration range.
5695 // This can happen for C++ constructor expressions whose range generally
5696 // include the variable declaration, e.g.:
5697 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5698 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5699 D->getLocation() == Data->TokenBeginLoc)
5700 return CXChildVisit_Break;
5701 }
5702 }
5703
5704 // If our current best cursor is the construction of a temporary object,
5705 // don't replace that cursor with a type reference, because we want
5706 // clang_getCursor() to point at the constructor.
5707 if (clang_isExpression(BestCursor->kind) &&
5708 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5709 cursor.kind == CXCursor_TypeRef) {
5710 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5711 // as having the actual point on the type reference.
5712 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5713 return CXChildVisit_Recurse;
5714 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005715
5716 // If we already have an Objective-C superclass reference, don't
5717 // update it further.
5718 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5719 return CXChildVisit_Break;
5720
Guy Benyei11169dd2012-12-18 14:30:41 +00005721 *BestCursor = cursor;
5722 return CXChildVisit_Recurse;
5723}
5724
5725CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005726 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005727 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005728 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005729 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005730
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005731 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005732 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5733
5734 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5735 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5736
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005737 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005738 CXFile SearchFile;
5739 unsigned SearchLine, SearchColumn;
5740 CXFile ResultFile;
5741 unsigned ResultLine, ResultColumn;
5742 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5743 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5744 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005745
5746 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5747 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005748 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005749 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005750 SearchFileName = clang_getFileName(SearchFile);
5751 ResultFileName = clang_getFileName(ResultFile);
5752 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5753 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005754 *Log << llvm::format("(%s:%d:%d) = %s",
5755 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5756 clang_getCString(KindSpelling))
5757 << llvm::format("(%s:%d:%d):%s%s",
5758 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5759 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005760 clang_disposeString(SearchFileName);
5761 clang_disposeString(ResultFileName);
5762 clang_disposeString(KindSpelling);
5763 clang_disposeString(USR);
5764
5765 CXCursor Definition = clang_getCursorDefinition(Result);
5766 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5767 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5768 CXString DefinitionKindSpelling
5769 = clang_getCursorKindSpelling(Definition.kind);
5770 CXFile DefinitionFile;
5771 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005772 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005773 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005774 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005775 *Log << llvm::format(" -> %s(%s:%d:%d)",
5776 clang_getCString(DefinitionKindSpelling),
5777 clang_getCString(DefinitionFileName),
5778 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005779 clang_disposeString(DefinitionFileName);
5780 clang_disposeString(DefinitionKindSpelling);
5781 }
5782 }
5783
5784 return Result;
5785}
5786
5787CXCursor clang_getNullCursor(void) {
5788 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5789}
5790
5791unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005792 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5793 // can't set consistently. For example, when visiting a DeclStmt we will set
5794 // it but we don't set it on the result of clang_getCursorDefinition for
5795 // a reference of the same declaration.
5796 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5797 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5798 // to provide that kind of info.
5799 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005800 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005801 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005802 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005803
Guy Benyei11169dd2012-12-18 14:30:41 +00005804 return X == Y;
5805}
5806
5807unsigned clang_hashCursor(CXCursor C) {
5808 unsigned Index = 0;
5809 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5810 Index = 1;
5811
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005812 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005813 std::make_pair(C.kind, C.data[Index]));
5814}
5815
5816unsigned clang_isInvalid(enum CXCursorKind K) {
5817 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5818}
5819
5820unsigned clang_isDeclaration(enum CXCursorKind K) {
5821 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005822 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5823}
5824
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005825unsigned clang_isInvalidDeclaration(CXCursor C) {
5826 if (clang_isDeclaration(C.kind)) {
5827 if (const Decl *D = getCursorDecl(C))
5828 return D->isInvalidDecl();
5829 }
5830
5831 return 0;
5832}
5833
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005834unsigned clang_isReference(enum CXCursorKind K) {
5835 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5836}
Guy Benyei11169dd2012-12-18 14:30:41 +00005837
5838unsigned clang_isExpression(enum CXCursorKind K) {
5839 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5840}
5841
5842unsigned clang_isStatement(enum CXCursorKind K) {
5843 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5844}
5845
5846unsigned clang_isAttribute(enum CXCursorKind K) {
5847 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5848}
5849
5850unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5851 return K == CXCursor_TranslationUnit;
5852}
5853
5854unsigned clang_isPreprocessing(enum CXCursorKind K) {
5855 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5856}
5857
5858unsigned clang_isUnexposed(enum CXCursorKind K) {
5859 switch (K) {
5860 case CXCursor_UnexposedDecl:
5861 case CXCursor_UnexposedExpr:
5862 case CXCursor_UnexposedStmt:
5863 case CXCursor_UnexposedAttr:
5864 return true;
5865 default:
5866 return false;
5867 }
5868}
5869
5870CXCursorKind clang_getCursorKind(CXCursor C) {
5871 return C.kind;
5872}
5873
5874CXSourceLocation clang_getCursorLocation(CXCursor C) {
5875 if (clang_isReference(C.kind)) {
5876 switch (C.kind) {
5877 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005878 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005879 = getCursorObjCSuperClassRef(C);
5880 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5881 }
5882
5883 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005884 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005885 = getCursorObjCProtocolRef(C);
5886 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5887 }
5888
5889 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005890 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005891 = getCursorObjCClassRef(C);
5892 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5893 }
5894
5895 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005896 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005897 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5898 }
5899
5900 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005901 std::pair<const TemplateDecl *, SourceLocation> P =
5902 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005903 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5904 }
5905
5906 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005907 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005908 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5909 }
5910
5911 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005912 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005913 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5914 }
5915
5916 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005917 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005918 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5919 }
5920
5921 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005922 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005923 if (!BaseSpec)
5924 return clang_getNullLocation();
5925
5926 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5927 return cxloc::translateSourceLocation(getCursorContext(C),
5928 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005929
Guy Benyei11169dd2012-12-18 14:30:41 +00005930 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005931 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005932 }
5933
5934 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005935 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005936 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5937 }
5938
5939 case CXCursor_OverloadedDeclRef:
5940 return cxloc::translateSourceLocation(getCursorContext(C),
5941 getCursorOverloadedDeclRef(C).second);
5942
5943 default:
5944 // FIXME: Need a way to enumerate all non-reference cases.
5945 llvm_unreachable("Missed a reference kind");
5946 }
5947 }
5948
5949 if (clang_isExpression(C.kind))
5950 return cxloc::translateSourceLocation(getCursorContext(C),
5951 getLocationFromExpr(getCursorExpr(C)));
5952
5953 if (clang_isStatement(C.kind))
5954 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005955 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005956
5957 if (C.kind == CXCursor_PreprocessingDirective) {
5958 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5959 return cxloc::translateSourceLocation(getCursorContext(C), L);
5960 }
5961
5962 if (C.kind == CXCursor_MacroExpansion) {
5963 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005964 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005965 return cxloc::translateSourceLocation(getCursorContext(C), L);
5966 }
5967
5968 if (C.kind == CXCursor_MacroDefinition) {
5969 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5970 return cxloc::translateSourceLocation(getCursorContext(C), L);
5971 }
5972
5973 if (C.kind == CXCursor_InclusionDirective) {
5974 SourceLocation L
5975 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5976 return cxloc::translateSourceLocation(getCursorContext(C), L);
5977 }
5978
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005979 if (clang_isAttribute(C.kind)) {
5980 SourceLocation L
5981 = cxcursor::getCursorAttr(C)->getLocation();
5982 return cxloc::translateSourceLocation(getCursorContext(C), L);
5983 }
5984
Guy Benyei11169dd2012-12-18 14:30:41 +00005985 if (!clang_isDeclaration(C.kind))
5986 return clang_getNullLocation();
5987
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005988 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 if (!D)
5990 return clang_getNullLocation();
5991
5992 SourceLocation Loc = D->getLocation();
5993 // FIXME: Multiple variables declared in a single declaration
5994 // currently lack the information needed to correctly determine their
5995 // ranges when accounting for the type-specifier. We use context
5996 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5997 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005998 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005999 if (!cxcursor::isFirstInDeclGroup(C))
6000 Loc = VD->getLocation();
6001 }
6002
6003 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006004 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006005 Loc = MD->getSelectorStartLoc();
6006
6007 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
6008}
6009
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00006010} // end extern "C"
6011
Guy Benyei11169dd2012-12-18 14:30:41 +00006012CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
6013 assert(TU);
6014
6015 // Guard against an invalid SourceLocation, or we may assert in one
6016 // of the following calls.
6017 if (SLoc.isInvalid())
6018 return clang_getNullCursor();
6019
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006020 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006021
6022 // Translate the given source location to make it point at the beginning of
6023 // the token under the cursor.
6024 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
6025 CXXUnit->getASTContext().getLangOpts());
6026
6027 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
6028 if (SLoc.isValid()) {
6029 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
6030 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
6031 /*VisitPreprocessorLast=*/true,
6032 /*VisitIncludedEntities=*/false,
6033 SourceLocation(SLoc));
6034 CursorVis.visitFileRegion();
6035 }
6036
6037 return Result;
6038}
6039
6040static SourceRange getRawCursorExtent(CXCursor C) {
6041 if (clang_isReference(C.kind)) {
6042 switch (C.kind) {
6043 case CXCursor_ObjCSuperClassRef:
6044 return getCursorObjCSuperClassRef(C).second;
6045
6046 case CXCursor_ObjCProtocolRef:
6047 return getCursorObjCProtocolRef(C).second;
6048
6049 case CXCursor_ObjCClassRef:
6050 return getCursorObjCClassRef(C).second;
6051
6052 case CXCursor_TypeRef:
6053 return getCursorTypeRef(C).second;
6054
6055 case CXCursor_TemplateRef:
6056 return getCursorTemplateRef(C).second;
6057
6058 case CXCursor_NamespaceRef:
6059 return getCursorNamespaceRef(C).second;
6060
6061 case CXCursor_MemberRef:
6062 return getCursorMemberRef(C).second;
6063
6064 case CXCursor_CXXBaseSpecifier:
6065 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6066
6067 case CXCursor_LabelRef:
6068 return getCursorLabelRef(C).second;
6069
6070 case CXCursor_OverloadedDeclRef:
6071 return getCursorOverloadedDeclRef(C).second;
6072
6073 case CXCursor_VariableRef:
6074 return getCursorVariableRef(C).second;
6075
6076 default:
6077 // FIXME: Need a way to enumerate all non-reference cases.
6078 llvm_unreachable("Missed a reference kind");
6079 }
6080 }
6081
6082 if (clang_isExpression(C.kind))
6083 return getCursorExpr(C)->getSourceRange();
6084
6085 if (clang_isStatement(C.kind))
6086 return getCursorStmt(C)->getSourceRange();
6087
6088 if (clang_isAttribute(C.kind))
6089 return getCursorAttr(C)->getRange();
6090
6091 if (C.kind == CXCursor_PreprocessingDirective)
6092 return cxcursor::getCursorPreprocessingDirective(C);
6093
6094 if (C.kind == CXCursor_MacroExpansion) {
6095 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006096 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006097 return TU->mapRangeFromPreamble(Range);
6098 }
6099
6100 if (C.kind == CXCursor_MacroDefinition) {
6101 ASTUnit *TU = getCursorASTUnit(C);
6102 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6103 return TU->mapRangeFromPreamble(Range);
6104 }
6105
6106 if (C.kind == CXCursor_InclusionDirective) {
6107 ASTUnit *TU = getCursorASTUnit(C);
6108 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6109 return TU->mapRangeFromPreamble(Range);
6110 }
6111
6112 if (C.kind == CXCursor_TranslationUnit) {
6113 ASTUnit *TU = getCursorASTUnit(C);
6114 FileID MainID = TU->getSourceManager().getMainFileID();
6115 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6116 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6117 return SourceRange(Start, End);
6118 }
6119
6120 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006121 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 if (!D)
6123 return SourceRange();
6124
6125 SourceRange R = D->getSourceRange();
6126 // FIXME: Multiple variables declared in a single declaration
6127 // currently lack the information needed to correctly determine their
6128 // ranges when accounting for the type-specifier. We use context
6129 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6130 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006131 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006132 if (!cxcursor::isFirstInDeclGroup(C))
6133 R.setBegin(VD->getLocation());
6134 }
6135 return R;
6136 }
6137 return SourceRange();
6138}
6139
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006140/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006141/// the decl-specifier-seq for declarations.
6142static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6143 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006144 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 if (!D)
6146 return SourceRange();
6147
6148 SourceRange R = D->getSourceRange();
6149
6150 // Adjust the start of the location for declarations preceded by
6151 // declaration specifiers.
6152 SourceLocation StartLoc;
6153 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6154 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006155 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006156 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006158 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006159 }
6160
6161 if (StartLoc.isValid() && R.getBegin().isValid() &&
6162 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6163 R.setBegin(StartLoc);
6164
6165 // FIXME: Multiple variables declared in a single declaration
6166 // currently lack the information needed to correctly determine their
6167 // ranges when accounting for the type-specifier. We use context
6168 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6169 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006170 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 if (!cxcursor::isFirstInDeclGroup(C))
6172 R.setBegin(VD->getLocation());
6173 }
6174
6175 return R;
6176 }
6177
6178 return getRawCursorExtent(C);
6179}
6180
Guy Benyei11169dd2012-12-18 14:30:41 +00006181CXSourceRange clang_getCursorExtent(CXCursor C) {
6182 SourceRange R = getRawCursorExtent(C);
6183 if (R.isInvalid())
6184 return clang_getNullRange();
6185
6186 return cxloc::translateSourceRange(getCursorContext(C), R);
6187}
6188
6189CXCursor clang_getCursorReferenced(CXCursor C) {
6190 if (clang_isInvalid(C.kind))
6191 return clang_getNullCursor();
6192
6193 CXTranslationUnit tu = getCursorTU(C);
6194 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006195 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 if (!D)
6197 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006198 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006199 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006200 if (const ObjCPropertyImplDecl *PropImpl =
6201 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006202 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6203 return MakeCXCursor(Property, tu);
6204
6205 return C;
6206 }
6207
6208 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006209 const Expr *E = getCursorExpr(C);
6210 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006211 if (D) {
6212 CXCursor declCursor = MakeCXCursor(D, tu);
6213 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6214 declCursor);
6215 return declCursor;
6216 }
6217
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006218 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006219 return MakeCursorOverloadedDeclRef(Ovl, tu);
6220
6221 return clang_getNullCursor();
6222 }
6223
6224 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006225 const Stmt *S = getCursorStmt(C);
6226 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006227 if (LabelDecl *label = Goto->getLabel())
6228 if (LabelStmt *labelS = label->getStmt())
6229 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6230
6231 return clang_getNullCursor();
6232 }
Richard Smith66a81862015-05-04 02:25:31 +00006233
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006235 if (const MacroDefinitionRecord *Def =
6236 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006237 return MakeMacroDefinitionCursor(Def, tu);
6238 }
6239
6240 if (!clang_isReference(C.kind))
6241 return clang_getNullCursor();
6242
6243 switch (C.kind) {
6244 case CXCursor_ObjCSuperClassRef:
6245 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6246
6247 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006248 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6249 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006250 return MakeCXCursor(Def, tu);
6251
6252 return MakeCXCursor(Prot, tu);
6253 }
6254
6255 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006256 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6257 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006258 return MakeCXCursor(Def, tu);
6259
6260 return MakeCXCursor(Class, tu);
6261 }
6262
6263 case CXCursor_TypeRef:
6264 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6265
6266 case CXCursor_TemplateRef:
6267 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6268
6269 case CXCursor_NamespaceRef:
6270 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6271
6272 case CXCursor_MemberRef:
6273 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6274
6275 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006276 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6278 tu ));
6279 }
6280
6281 case CXCursor_LabelRef:
6282 // FIXME: We end up faking the "parent" declaration here because we
6283 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006284 return MakeCXCursor(getCursorLabelRef(C).first,
6285 cxtu::getASTUnit(tu)->getASTContext()
6286 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006287 tu);
6288
6289 case CXCursor_OverloadedDeclRef:
6290 return C;
6291
6292 case CXCursor_VariableRef:
6293 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6294
6295 default:
6296 // We would prefer to enumerate all non-reference cursor kinds here.
6297 llvm_unreachable("Unhandled reference cursor kind");
6298 }
6299}
6300
6301CXCursor clang_getCursorDefinition(CXCursor C) {
6302 if (clang_isInvalid(C.kind))
6303 return clang_getNullCursor();
6304
6305 CXTranslationUnit TU = getCursorTU(C);
6306
6307 bool WasReference = false;
6308 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6309 C = clang_getCursorReferenced(C);
6310 WasReference = true;
6311 }
6312
6313 if (C.kind == CXCursor_MacroExpansion)
6314 return clang_getCursorReferenced(C);
6315
6316 if (!clang_isDeclaration(C.kind))
6317 return clang_getNullCursor();
6318
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006319 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 if (!D)
6321 return clang_getNullCursor();
6322
6323 switch (D->getKind()) {
6324 // Declaration kinds that don't really separate the notions of
6325 // declaration and definition.
6326 case Decl::Namespace:
6327 case Decl::Typedef:
6328 case Decl::TypeAlias:
6329 case Decl::TypeAliasTemplate:
6330 case Decl::TemplateTypeParm:
6331 case Decl::EnumConstant:
6332 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006333 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006334 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006335 case Decl::IndirectField:
6336 case Decl::ObjCIvar:
6337 case Decl::ObjCAtDefsField:
6338 case Decl::ImplicitParam:
6339 case Decl::ParmVar:
6340 case Decl::NonTypeTemplateParm:
6341 case Decl::TemplateTemplateParm:
6342 case Decl::ObjCCategoryImpl:
6343 case Decl::ObjCImplementation:
6344 case Decl::AccessSpec:
6345 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006346 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 case Decl::ObjCPropertyImpl:
6348 case Decl::FileScopeAsm:
6349 case Decl::StaticAssert:
6350 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006351 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006352 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006353 case Decl::Label: // FIXME: Is this right??
6354 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006355 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006357 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006358 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006359 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006360 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006361 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006362 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006363 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006364 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006365 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006366 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006367 case Decl::Concept:
Tykerb0561b32019-11-17 11:41:55 +01006368 case Decl::LifetimeExtendedTemporary:
Saar Raza0f50d72020-01-18 09:11:43 +02006369 case Decl::RequiresExprBody:
Guy Benyei11169dd2012-12-18 14:30:41 +00006370 return C;
6371
6372 // Declaration kinds that don't make any sense here, but are
6373 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006374 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006376 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 break;
6378
6379 // Declaration kinds for which the definition is not resolvable.
6380 case Decl::UnresolvedUsingTypename:
6381 case Decl::UnresolvedUsingValue:
6382 break;
6383
6384 case Decl::UsingDirective:
6385 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6386 TU);
6387
6388 case Decl::NamespaceAlias:
6389 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6390
6391 case Decl::Enum:
6392 case Decl::Record:
6393 case Decl::CXXRecord:
6394 case Decl::ClassTemplateSpecialization:
6395 case Decl::ClassTemplatePartialSpecialization:
6396 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6397 return MakeCXCursor(Def, TU);
6398 return clang_getNullCursor();
6399
6400 case Decl::Function:
6401 case Decl::CXXMethod:
6402 case Decl::CXXConstructor:
6403 case Decl::CXXDestructor:
6404 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006405 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006407 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 return clang_getNullCursor();
6409 }
6410
Larisse Voufo39a1e502013-08-06 01:03:05 +00006411 case Decl::Var:
6412 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006413 case Decl::VarTemplatePartialSpecialization:
6414 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006415 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006416 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006417 return MakeCXCursor(Def, TU);
6418 return clang_getNullCursor();
6419 }
6420
6421 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006422 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006423 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6424 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6425 return clang_getNullCursor();
6426 }
6427
6428 case Decl::ClassTemplate: {
6429 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6430 ->getDefinition())
6431 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6432 TU);
6433 return clang_getNullCursor();
6434 }
6435
Larisse Voufo39a1e502013-08-06 01:03:05 +00006436 case Decl::VarTemplate: {
6437 if (VarDecl *Def =
6438 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6439 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6440 return clang_getNullCursor();
6441 }
6442
Guy Benyei11169dd2012-12-18 14:30:41 +00006443 case Decl::Using:
6444 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6445 D->getLocation(), TU);
6446
6447 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006448 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 return clang_getCursorDefinition(
6450 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6451 TU));
6452
6453 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006454 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006455 if (Method->isThisDeclarationADefinition())
6456 return C;
6457
6458 // Dig out the method definition in the associated
6459 // @implementation, if we have it.
6460 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006461 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006462 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6463 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6464 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6465 Method->isInstanceMethod()))
6466 if (Def->isThisDeclarationADefinition())
6467 return MakeCXCursor(Def, TU);
6468
6469 return clang_getNullCursor();
6470 }
6471
6472 case Decl::ObjCCategory:
6473 if (ObjCCategoryImplDecl *Impl
6474 = cast<ObjCCategoryDecl>(D)->getImplementation())
6475 return MakeCXCursor(Impl, TU);
6476 return clang_getNullCursor();
6477
6478 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006479 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 return MakeCXCursor(Def, TU);
6481 return clang_getNullCursor();
6482
6483 case Decl::ObjCInterface: {
6484 // There are two notions of a "definition" for an Objective-C
6485 // class: the interface and its implementation. When we resolved a
6486 // reference to an Objective-C class, produce the @interface as
6487 // the definition; when we were provided with the interface,
6488 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006489 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006490 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006491 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006492 return MakeCXCursor(Def, TU);
6493 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6494 return MakeCXCursor(Impl, TU);
6495 return clang_getNullCursor();
6496 }
6497
6498 case Decl::ObjCProperty:
6499 // FIXME: We don't really know where to find the
6500 // ObjCPropertyImplDecls that implement this property.
6501 return clang_getNullCursor();
6502
6503 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006504 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006505 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006506 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006507 return MakeCXCursor(Def, TU);
6508
6509 return clang_getNullCursor();
6510
6511 case Decl::Friend:
6512 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6513 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6514 return clang_getNullCursor();
6515
6516 case Decl::FriendTemplate:
6517 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6518 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6519 return clang_getNullCursor();
6520 }
6521
6522 return clang_getNullCursor();
6523}
6524
6525unsigned clang_isCursorDefinition(CXCursor C) {
6526 if (!clang_isDeclaration(C.kind))
6527 return 0;
6528
6529 return clang_getCursorDefinition(C) == C;
6530}
6531
6532CXCursor clang_getCanonicalCursor(CXCursor C) {
6533 if (!clang_isDeclaration(C.kind))
6534 return C;
6535
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006536 if (const Decl *D = getCursorDecl(C)) {
6537 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006538 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6539 return MakeCXCursor(CatD, getCursorTU(C));
6540
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006541 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6542 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006543 return MakeCXCursor(IFD, getCursorTU(C));
6544
6545 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6546 }
6547
6548 return C;
6549}
6550
6551int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6552 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6553}
6554
6555unsigned clang_getNumOverloadedDecls(CXCursor C) {
6556 if (C.kind != CXCursor_OverloadedDeclRef)
6557 return 0;
6558
6559 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006560 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006561 return E->getNumDecls();
6562
6563 if (OverloadedTemplateStorage *S
6564 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6565 return S->size();
6566
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006567 const Decl *D = Storage.get<const Decl *>();
6568 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006569 return Using->shadow_size();
6570
6571 return 0;
6572}
6573
6574CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6575 if (cursor.kind != CXCursor_OverloadedDeclRef)
6576 return clang_getNullCursor();
6577
6578 if (index >= clang_getNumOverloadedDecls(cursor))
6579 return clang_getNullCursor();
6580
6581 CXTranslationUnit TU = getCursorTU(cursor);
6582 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006583 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006584 return MakeCXCursor(E->decls_begin()[index], TU);
6585
6586 if (OverloadedTemplateStorage *S
6587 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6588 return MakeCXCursor(S->begin()[index], TU);
6589
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006590 const Decl *D = Storage.get<const Decl *>();
6591 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 // FIXME: This is, unfortunately, linear time.
6593 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6594 std::advance(Pos, index);
6595 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6596 }
6597
6598 return clang_getNullCursor();
6599}
6600
6601void clang_getDefinitionSpellingAndExtent(CXCursor C,
6602 const char **startBuf,
6603 const char **endBuf,
6604 unsigned *startLine,
6605 unsigned *startColumn,
6606 unsigned *endLine,
6607 unsigned *endColumn) {
6608 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006609 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006610 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6611
6612 SourceManager &SM = FD->getASTContext().getSourceManager();
6613 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6614 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6615 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6616 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6617 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6618 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6619}
6620
6621
6622CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6623 unsigned PieceIndex) {
6624 RefNamePieces Pieces;
6625
6626 switch (C.kind) {
6627 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006628 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006629 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6630 E->getQualifierLoc().getSourceRange());
6631 break;
6632
6633 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006634 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6635 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6636 Pieces =
6637 buildPieces(NameFlags, false, E->getNameInfo(),
6638 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6639 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 break;
6641
6642 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006643 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006644 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006645 const Expr *Callee = OCE->getCallee();
6646 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006647 Callee = ICE->getSubExpr();
6648
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006649 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006650 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6651 DRE->getQualifierLoc().getSourceRange());
6652 }
6653 break;
6654
6655 default:
6656 break;
6657 }
6658
6659 if (Pieces.empty()) {
6660 if (PieceIndex == 0)
6661 return clang_getCursorExtent(C);
6662 } else if (PieceIndex < Pieces.size()) {
6663 SourceRange R = Pieces[PieceIndex];
6664 if (R.isValid())
6665 return cxloc::translateSourceRange(getCursorContext(C), R);
6666 }
6667
6668 return clang_getNullRange();
6669}
6670
6671void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006672 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6673 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006674}
6675
6676void clang_executeOnThread(void (*fn)(void*), void *user_data,
6677 unsigned stack_size) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05006678 llvm::llvm_execute_on_thread(fn, user_data,
6679 stack_size == 0
6680 ? clang::DesiredStackSize
6681 : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006682}
6683
Guy Benyei11169dd2012-12-18 14:30:41 +00006684//===----------------------------------------------------------------------===//
6685// Token-based Operations.
6686//===----------------------------------------------------------------------===//
6687
6688/* CXToken layout:
6689 * int_data[0]: a CXTokenKind
6690 * int_data[1]: starting token location
6691 * int_data[2]: token length
6692 * int_data[3]: reserved
6693 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6694 * otherwise unused.
6695 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006696CXTokenKind clang_getTokenKind(CXToken CXTok) {
6697 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6698}
6699
6700CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6701 switch (clang_getTokenKind(CXTok)) {
6702 case CXToken_Identifier:
6703 case CXToken_Keyword:
6704 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006705 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 ->getNameStart());
6707
6708 case CXToken_Literal: {
6709 // We have stashed the starting pointer in the ptr_data field. Use it.
6710 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006711 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006712 }
6713
6714 case CXToken_Punctuation:
6715 case CXToken_Comment:
6716 break;
6717 }
6718
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006719 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006720 LOG_BAD_TU(TU);
6721 return cxstring::createEmpty();
6722 }
6723
Guy Benyei11169dd2012-12-18 14:30:41 +00006724 // We have to find the starting buffer pointer the hard way, by
6725 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006726 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006727 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006728 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006729
6730 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6731 std::pair<FileID, unsigned> LocInfo
6732 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6733 bool Invalid = false;
6734 StringRef Buffer
6735 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6736 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006737 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006738
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006739 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006740}
6741
6742CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006743 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006744 LOG_BAD_TU(TU);
6745 return clang_getNullLocation();
6746 }
6747
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006748 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006749 if (!CXXUnit)
6750 return clang_getNullLocation();
6751
6752 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6753 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6754}
6755
6756CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006757 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006758 LOG_BAD_TU(TU);
6759 return clang_getNullRange();
6760 }
6761
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006762 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006763 if (!CXXUnit)
6764 return clang_getNullRange();
6765
6766 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6767 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6768}
6769
6770static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6771 SmallVectorImpl<CXToken> &CXTokens) {
6772 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6773 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006774 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006775 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006776 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006777
6778 // Cannot tokenize across files.
6779 if (BeginLocInfo.first != EndLocInfo.first)
6780 return;
6781
6782 // Create a lexer
6783 bool Invalid = false;
6784 StringRef Buffer
6785 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6786 if (Invalid)
6787 return;
6788
6789 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6790 CXXUnit->getASTContext().getLangOpts(),
6791 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6792 Lex.SetCommentRetentionState(true);
6793
6794 // Lex tokens until we hit the end of the range.
6795 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6796 Token Tok;
6797 bool previousWasAt = false;
6798 do {
6799 // Lex the next token
6800 Lex.LexFromRawLexer(Tok);
6801 if (Tok.is(tok::eof))
6802 break;
6803
6804 // Initialize the CXToken.
6805 CXToken CXTok;
6806
6807 // - Common fields
6808 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6809 CXTok.int_data[2] = Tok.getLength();
6810 CXTok.int_data[3] = 0;
6811
6812 // - Kind-specific fields
6813 if (Tok.isLiteral()) {
6814 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006815 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006816 } else if (Tok.is(tok::raw_identifier)) {
6817 // Lookup the identifier to determine whether we have a keyword.
6818 IdentifierInfo *II
6819 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6820
6821 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6822 CXTok.int_data[0] = CXToken_Keyword;
6823 }
6824 else {
6825 CXTok.int_data[0] = Tok.is(tok::identifier)
6826 ? CXToken_Identifier
6827 : CXToken_Keyword;
6828 }
6829 CXTok.ptr_data = II;
6830 } else if (Tok.is(tok::comment)) {
6831 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006832 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006833 } else {
6834 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006835 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006836 }
6837 CXTokens.push_back(CXTok);
6838 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006839 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006840}
6841
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006842CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6843 LOG_FUNC_SECTION {
6844 *Log << TU << ' ' << Location;
6845 }
6846
6847 if (isNotUsableTU(TU)) {
6848 LOG_BAD_TU(TU);
6849 return NULL;
6850 }
6851
6852 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6853 if (!CXXUnit)
6854 return NULL;
6855
6856 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6857 if (Begin.isInvalid())
6858 return NULL;
6859 SourceManager &SM = CXXUnit->getSourceManager();
6860 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6861 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6862
6863 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6864
6865 SmallVector<CXToken, 32> CXTokens;
6866 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6867
6868 if (CXTokens.empty())
6869 return NULL;
6870
6871 CXTokens.resize(1);
6872 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6873
6874 memmove(Token, CXTokens.data(), sizeof(CXToken));
6875 return Token;
6876}
6877
Guy Benyei11169dd2012-12-18 14:30:41 +00006878void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6879 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006880 LOG_FUNC_SECTION {
6881 *Log << TU << ' ' << Range;
6882 }
6883
Guy Benyei11169dd2012-12-18 14:30:41 +00006884 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006885 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006886 if (NumTokens)
6887 *NumTokens = 0;
6888
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006889 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006890 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006891 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006892 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006893
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006894 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006895 if (!CXXUnit || !Tokens || !NumTokens)
6896 return;
6897
6898 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6899
6900 SourceRange R = cxloc::translateCXSourceRange(Range);
6901 if (R.isInvalid())
6902 return;
6903
6904 SmallVector<CXToken, 32> CXTokens;
6905 getTokens(CXXUnit, R, CXTokens);
6906
6907 if (CXTokens.empty())
6908 return;
6909
Serge Pavlov52525732018-02-21 02:02:39 +00006910 *Tokens = static_cast<CXToken *>(
6911 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006912 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6913 *NumTokens = CXTokens.size();
6914}
6915
6916void clang_disposeTokens(CXTranslationUnit TU,
6917 CXToken *Tokens, unsigned NumTokens) {
6918 free(Tokens);
6919}
6920
Guy Benyei11169dd2012-12-18 14:30:41 +00006921//===----------------------------------------------------------------------===//
6922// Token annotation APIs.
6923//===----------------------------------------------------------------------===//
6924
Guy Benyei11169dd2012-12-18 14:30:41 +00006925static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6926 CXCursor parent,
6927 CXClientData client_data);
6928static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6929 CXClientData client_data);
6930
6931namespace {
6932class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 CXToken *Tokens;
6934 CXCursor *Cursors;
6935 unsigned NumTokens;
6936 unsigned TokIdx;
6937 unsigned PreprocessingTokIdx;
6938 CursorVisitor AnnotateVis;
6939 SourceManager &SrcMgr;
6940 bool HasContextSensitiveKeywords;
6941
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006942 struct PostChildrenAction {
6943 CXCursor cursor;
6944 enum Action { Invalid, Ignore, Postpone } action;
6945 };
6946 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6947
Guy Benyei11169dd2012-12-18 14:30:41 +00006948 struct PostChildrenInfo {
6949 CXCursor Cursor;
6950 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006951 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006953 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006954 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006955 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006956
6957 CXToken &getTok(unsigned Idx) {
6958 assert(Idx < NumTokens);
6959 return Tokens[Idx];
6960 }
6961 const CXToken &getTok(unsigned Idx) const {
6962 assert(Idx < NumTokens);
6963 return Tokens[Idx];
6964 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006965 bool MoreTokens() const { return TokIdx < NumTokens; }
6966 unsigned NextToken() const { return TokIdx; }
6967 void AdvanceToken() { ++TokIdx; }
6968 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006969 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006970 }
6971 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006972 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006973 }
6974 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006975 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006976 }
6977
6978 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006979 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006980 SourceRange);
6981
6982public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006983 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006984 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006985 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006986 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006987 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006988 AnnotateTokensVisitor, this,
6989 /*VisitPreprocessorLast=*/true,
6990 /*VisitIncludedEntities=*/false,
6991 RegionOfInterest,
6992 /*VisitDeclsOnly=*/false,
6993 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006994 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006995 HasContextSensitiveKeywords(false) { }
6996
6997 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6998 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006999 bool IsIgnoredChildCursor(CXCursor cursor) const;
7000 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
7001
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007003 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
7004 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
7005
Guy Benyei11169dd2012-12-18 14:30:41 +00007006 void AnnotateTokens();
7007
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007008 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00007009 /// context-sensitive keywords.
7010 bool hasContextSensitiveKeywords() const {
7011 return HasContextSensitiveKeywords;
7012 }
7013
7014 ~AnnotateTokensWorker() {
7015 assert(PostChildrenInfos.empty());
7016 }
7017};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007018}
Guy Benyei11169dd2012-12-18 14:30:41 +00007019
7020void AnnotateTokensWorker::AnnotateTokens() {
7021 // Walk the AST within the region of interest, annotating tokens
7022 // along the way.
7023 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007024}
Guy Benyei11169dd2012-12-18 14:30:41 +00007025
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007026bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
7027 if (PostChildrenInfos.empty())
7028 return false;
7029
7030 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
7031 if (ChildAction.cursor == cursor &&
7032 ChildAction.action == PostChildrenAction::Ignore) {
7033 return true;
7034 }
7035 }
7036
7037 return false;
7038}
7039
7040const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
7041 if (!clang_isExpression(Cursor.kind))
7042 return nullptr;
7043
7044 const Expr *E = getCursorExpr(Cursor);
7045 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7046 const OverloadedOperatorKind Kind = OCE->getOperator();
7047 if (Kind == OO_Call || Kind == OO_Subscript)
7048 return OCE;
7049 }
7050
7051 return nullptr;
7052}
7053
7054AnnotateTokensWorker::PostChildrenActions
7055AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7056 PostChildrenActions actions;
7057
7058 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
7059 // visited before the arguments to the operator call. For the Call and
7060 // Subscript operator the range of this DeclRefExpr includes the whole call
7061 // expression, so that all tokens in that range would be mapped to the
7062 // operator function, including the tokens of the arguments. To avoid that,
7063 // ensure to visit this DeclRefExpr as last node.
7064 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7065 const Expr *Callee = OCE->getCallee();
7066 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7067 const Expr *SubExpr = ICE->getSubExpr();
7068 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007069 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007070 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7071
7072 // Visit the DeclRefExpr as last.
7073 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7074 actions.push_back({cxChild, PostChildrenAction::Postpone});
7075
7076 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7077 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7078 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7079 actions.push_back({cxChild, PostChildrenAction::Ignore});
7080 }
7081 }
7082 }
7083
7084 return actions;
7085}
7086
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007087static inline void updateCursorAnnotation(CXCursor &Cursor,
7088 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007089 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007090 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007091 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007092}
7093
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007094/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007095//// between the cursor location and the source range is the same as
7096/// \arg compResult.
7097///
7098/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7099/// Pass RangeOverlap to annotate tokens inside a range.
7100void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7101 RangeComparisonResult compResult,
7102 SourceRange range) {
7103 while (MoreTokens()) {
7104 const unsigned I = NextToken();
7105 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007106 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7107 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007108
7109 SourceLocation TokLoc = GetTokenLoc(I);
7110 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007111 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007112 AdvanceToken();
7113 continue;
7114 }
7115 break;
7116 }
7117}
7118
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007119/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007120/// \returns true if it advanced beyond all macro tokens, false otherwise.
7121bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007122 CXCursor updateC,
7123 RangeComparisonResult compResult,
7124 SourceRange range) {
7125 assert(MoreTokens());
7126 assert(isFunctionMacroToken(NextToken()) &&
7127 "Should be called only for macro arg tokens");
7128
7129 // This works differently than annotateAndAdvanceTokens; because expanded
7130 // macro arguments can have arbitrary translation-unit source order, we do not
7131 // advance the token index one by one until a token fails the range test.
7132 // We only advance once past all of the macro arg tokens if all of them
7133 // pass the range test. If one of them fails we keep the token index pointing
7134 // at the start of the macro arg tokens so that the failing token will be
7135 // annotated by a subsequent annotation try.
7136
7137 bool atLeastOneCompFail = false;
7138
7139 unsigned I = NextToken();
7140 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7141 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7142 if (TokLoc.isFileID())
7143 continue; // not macro arg token, it's parens or comma.
7144 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7145 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7146 Cursors[I] = updateC;
7147 } else
7148 atLeastOneCompFail = true;
7149 }
7150
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007151 if (atLeastOneCompFail)
7152 return false;
7153
7154 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7155 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007156}
7157
7158enum CXChildVisitResult
7159AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007160 SourceRange cursorRange = getRawCursorExtent(cursor);
7161 if (cursorRange.isInvalid())
7162 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007163
7164 if (IsIgnoredChildCursor(cursor))
7165 return CXChildVisit_Continue;
7166
Guy Benyei11169dd2012-12-18 14:30:41 +00007167 if (!HasContextSensitiveKeywords) {
7168 // Objective-C properties can have context-sensitive keywords.
7169 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007170 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007171 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7172 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7173 }
7174 // Objective-C methods can have context-sensitive keywords.
7175 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7176 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007177 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007178 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7179 if (Method->getObjCDeclQualifier())
7180 HasContextSensitiveKeywords = true;
7181 else {
David Majnemer59f77922016-06-24 04:05:48 +00007182 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007183 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007184 HasContextSensitiveKeywords = true;
7185 break;
7186 }
7187 }
7188 }
7189 }
7190 }
7191 // C++ methods can have context-sensitive keywords.
7192 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007193 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007194 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7195 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7196 HasContextSensitiveKeywords = true;
7197 }
7198 }
7199 // C++ classes can have context-sensitive keywords.
7200 else if (cursor.kind == CXCursor_StructDecl ||
7201 cursor.kind == CXCursor_ClassDecl ||
7202 cursor.kind == CXCursor_ClassTemplate ||
7203 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007204 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007205 if (D->hasAttr<FinalAttr>())
7206 HasContextSensitiveKeywords = true;
7207 }
7208 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007209
7210 // Don't override a property annotation with its getter/setter method.
7211 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7212 parent.kind == CXCursor_ObjCPropertyDecl)
7213 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007214
7215 if (clang_isPreprocessing(cursor.kind)) {
7216 // Items in the preprocessing record are kept separate from items in
7217 // declarations, so we keep a separate token index.
7218 unsigned SavedTokIdx = TokIdx;
7219 TokIdx = PreprocessingTokIdx;
7220
7221 // Skip tokens up until we catch up to the beginning of the preprocessing
7222 // entry.
7223 while (MoreTokens()) {
7224 const unsigned I = NextToken();
7225 SourceLocation TokLoc = GetTokenLoc(I);
7226 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7227 case RangeBefore:
7228 AdvanceToken();
7229 continue;
7230 case RangeAfter:
7231 case RangeOverlap:
7232 break;
7233 }
7234 break;
7235 }
7236
7237 // Look at all of the tokens within this range.
7238 while (MoreTokens()) {
7239 const unsigned I = NextToken();
7240 SourceLocation TokLoc = GetTokenLoc(I);
7241 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7242 case RangeBefore:
7243 llvm_unreachable("Infeasible");
7244 case RangeAfter:
7245 break;
7246 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007247 // For macro expansions, just note where the beginning of the macro
7248 // expansion occurs.
7249 if (cursor.kind == CXCursor_MacroExpansion) {
7250 if (TokLoc == cursorRange.getBegin())
7251 Cursors[I] = cursor;
7252 AdvanceToken();
7253 break;
7254 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007255 // We may have already annotated macro names inside macro definitions.
7256 if (Cursors[I].kind != CXCursor_MacroExpansion)
7257 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007259 continue;
7260 }
7261 break;
7262 }
7263
7264 // Save the preprocessing token index; restore the non-preprocessing
7265 // token index.
7266 PreprocessingTokIdx = TokIdx;
7267 TokIdx = SavedTokIdx;
7268 return CXChildVisit_Recurse;
7269 }
7270
7271 if (cursorRange.isInvalid())
7272 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007273
7274 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007275 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 const enum CXCursorKind K = clang_getCursorKind(parent);
7277 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007278 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7279 // Attributes are annotated out-of-order, skip tokens until we reach it.
7280 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007281 ? clang_getNullCursor() : parent;
7282
7283 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7284
7285 // Avoid having the cursor of an expression "overwrite" the annotation of the
7286 // variable declaration that it belongs to.
7287 // This can happen for C++ constructor expressions whose range generally
7288 // include the variable declaration, e.g.:
7289 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007290 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007291 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007292 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007293 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007294 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7295 E->getBeginLoc() == D->getLocation() &&
7296 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007297 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007298 AdvanceToken();
7299 }
7300 }
7301 }
7302
7303 // Before recursing into the children keep some state that we are going
7304 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7305 // extra work after the child nodes are visited.
7306 // Note that we don't call VisitChildren here to avoid traversing statements
7307 // code-recursively which can blow the stack.
7308
7309 PostChildrenInfo Info;
7310 Info.Cursor = cursor;
7311 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007312 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007313 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007314 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007315 PostChildrenInfos.push_back(Info);
7316
7317 return CXChildVisit_Recurse;
7318}
7319
7320bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7321 if (PostChildrenInfos.empty())
7322 return false;
7323 const PostChildrenInfo &Info = PostChildrenInfos.back();
7324 if (!clang_equalCursors(Info.Cursor, cursor))
7325 return false;
7326
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007327 HandlePostPonedChildCursors(Info);
7328
Guy Benyei11169dd2012-12-18 14:30:41 +00007329 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7330 const unsigned AfterChildren = NextToken();
7331 SourceRange cursorRange = Info.CursorRange;
7332
7333 // Scan the tokens that are at the end of the cursor, but are not captured
7334 // but the child cursors.
7335 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7336
7337 // Scan the tokens that are at the beginning of the cursor, but are not
7338 // capture by the child cursors.
7339 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7340 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7341 break;
7342
7343 Cursors[I] = cursor;
7344 }
7345
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007346 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7347 // encountered the attribute cursor.
7348 if (clang_isAttribute(cursor.kind))
7349 TokIdx = Info.BeforeReachingCursorIdx;
7350
Guy Benyei11169dd2012-12-18 14:30:41 +00007351 PostChildrenInfos.pop_back();
7352 return false;
7353}
7354
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007355void AnnotateTokensWorker::HandlePostPonedChildCursors(
7356 const PostChildrenInfo &Info) {
7357 for (const auto &ChildAction : Info.ChildActions) {
7358 if (ChildAction.action == PostChildrenAction::Postpone) {
7359 HandlePostPonedChildCursor(ChildAction.cursor,
7360 Info.BeforeChildrenTokenIdx);
7361 }
7362 }
7363}
7364
7365void AnnotateTokensWorker::HandlePostPonedChildCursor(
7366 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007367 unsigned I = StartTokenIndex;
7368
7369 // The bracket tokens of a Call or Subscript operator are mapped to
7370 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7371 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7372 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007373 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7374 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007375 if (clang_Range_isNull(CXRefNameRange))
7376 break; // All ranges handled.
7377
7378 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7379 while (I < NumTokens) {
7380 const SourceLocation TokenLocation = GetTokenLoc(I);
7381 if (!TokenLocation.isValid())
7382 break;
7383
7384 // Adapt the end range, because LocationCompare() reports
7385 // RangeOverlap even for the not-inclusive end location.
7386 const SourceLocation fixedEnd =
7387 RefNameRange.getEnd().getLocWithOffset(-1);
7388 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7389
7390 const RangeComparisonResult ComparisonResult =
7391 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7392
7393 if (ComparisonResult == RangeOverlap) {
7394 Cursors[I++] = Cursor;
7395 } else if (ComparisonResult == RangeBefore) {
7396 ++I; // Not relevant token, check next one.
7397 } else if (ComparisonResult == RangeAfter) {
7398 break; // All tokens updated for current range, check next.
7399 }
7400 }
7401 }
7402}
7403
Guy Benyei11169dd2012-12-18 14:30:41 +00007404static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7405 CXCursor parent,
7406 CXClientData client_data) {
7407 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7408}
7409
7410static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7411 CXClientData client_data) {
7412 return static_cast<AnnotateTokensWorker*>(client_data)->
7413 postVisitChildren(cursor);
7414}
7415
7416namespace {
7417
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007418/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007419/// and mark tokens that are macro arguments. This info is used by the
7420/// AnnotateTokensWorker.
7421class MarkMacroArgTokensVisitor {
7422 SourceManager &SM;
7423 CXToken *Tokens;
7424 unsigned NumTokens;
7425 unsigned CurIdx;
7426
7427public:
7428 MarkMacroArgTokensVisitor(SourceManager &SM,
7429 CXToken *tokens, unsigned numTokens)
7430 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7431
7432 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7433 if (cursor.kind != CXCursor_MacroExpansion)
7434 return CXChildVisit_Continue;
7435
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007436 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007437 if (macroRange.getBegin() == macroRange.getEnd())
7438 return CXChildVisit_Continue; // it's not a function macro.
7439
7440 for (; CurIdx < NumTokens; ++CurIdx) {
7441 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7442 macroRange.getBegin()))
7443 break;
7444 }
7445
7446 if (CurIdx == NumTokens)
7447 return CXChildVisit_Break;
7448
7449 for (; CurIdx < NumTokens; ++CurIdx) {
7450 SourceLocation tokLoc = getTokenLoc(CurIdx);
7451 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7452 break;
7453
7454 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7455 }
7456
7457 if (CurIdx == NumTokens)
7458 return CXChildVisit_Break;
7459
7460 return CXChildVisit_Continue;
7461 }
7462
7463private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007464 CXToken &getTok(unsigned Idx) {
7465 assert(Idx < NumTokens);
7466 return Tokens[Idx];
7467 }
7468 const CXToken &getTok(unsigned Idx) const {
7469 assert(Idx < NumTokens);
7470 return Tokens[Idx];
7471 }
7472
Guy Benyei11169dd2012-12-18 14:30:41 +00007473 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007474 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 }
7476
7477 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7478 // The third field is reserved and currently not used. Use it here
7479 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007480 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007481 }
7482};
7483
7484} // end anonymous namespace
7485
7486static CXChildVisitResult
7487MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7488 CXClientData client_data) {
7489 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7490 parent);
7491}
7492
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007493/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007494/// \returns true if lexing was finished, false otherwise.
7495static bool lexNext(Lexer &Lex, Token &Tok,
7496 unsigned &NextIdx, unsigned NumTokens) {
7497 if (NextIdx >= NumTokens)
7498 return true;
7499
7500 ++NextIdx;
7501 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007502 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007503}
7504
Guy Benyei11169dd2012-12-18 14:30:41 +00007505static void annotatePreprocessorTokens(CXTranslationUnit TU,
7506 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007507 CXCursor *Cursors,
7508 CXToken *Tokens,
7509 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007510 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007511
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007512 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007513 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7514 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007515 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007516 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007517 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007518
7519 if (BeginLocInfo.first != EndLocInfo.first)
7520 return;
7521
7522 StringRef Buffer;
7523 bool Invalid = false;
7524 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7525 if (Buffer.empty() || Invalid)
7526 return;
7527
7528 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7529 CXXUnit->getASTContext().getLangOpts(),
7530 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7531 Buffer.end());
7532 Lex.SetCommentRetentionState(true);
7533
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007534 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007535 // Lex tokens in raw mode until we hit the end of the range, to avoid
7536 // entering #includes or expanding macros.
7537 while (true) {
7538 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007539 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7540 break;
7541 unsigned TokIdx = NextIdx-1;
7542 assert(Tok.getLocation() ==
7543 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007544
7545 reprocess:
7546 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007547 // We have found a preprocessing directive. Annotate the tokens
7548 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007549 //
7550 // FIXME: Some simple tests here could identify macro definitions and
7551 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007552
7553 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007554 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7555 break;
7556
Craig Topper69186e72014-06-08 08:38:04 +00007557 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007558 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007559 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7560 break;
7561
7562 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007563 IdentifierInfo &II =
7564 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007565 SourceLocation MappedTokLoc =
7566 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7567 MI = getMacroInfo(II, MappedTokLoc, TU);
7568 }
7569 }
7570
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007571 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007572 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007573 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7574 finished = true;
7575 break;
7576 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007577 // If we are in a macro definition, check if the token was ever a
7578 // macro name and annotate it if that's the case.
7579 if (MI) {
7580 SourceLocation SaveLoc = Tok.getLocation();
7581 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007582 MacroDefinitionRecord *MacroDef =
7583 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007584 Tok.setLocation(SaveLoc);
7585 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007586 Cursors[NextIdx - 1] =
7587 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007588 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007589 } while (!Tok.isAtStartOfLine());
7590
7591 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7592 assert(TokIdx <= LastIdx);
7593 SourceLocation EndLoc =
7594 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7595 CXCursor Cursor =
7596 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7597
7598 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007599 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007600
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007601 if (finished)
7602 break;
7603 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007604 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007605 }
7606}
7607
7608// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007609static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7610 CXToken *Tokens, unsigned NumTokens,
7611 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007612 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007613 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7614 setThreadBackgroundPriority();
7615
7616 // Determine the region of interest, which contains all of the tokens.
7617 SourceRange RegionOfInterest;
7618 RegionOfInterest.setBegin(
7619 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7620 RegionOfInterest.setEnd(
7621 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7622 Tokens[NumTokens-1])));
7623
Guy Benyei11169dd2012-12-18 14:30:41 +00007624 // Relex the tokens within the source range to look for preprocessing
7625 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007626 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007627
7628 // If begin location points inside a macro argument, set it to the expansion
7629 // location so we can have the full context when annotating semantically.
7630 {
7631 SourceManager &SM = CXXUnit->getSourceManager();
7632 SourceLocation Loc =
7633 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7634 if (Loc.isMacroID())
7635 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7636 }
7637
Guy Benyei11169dd2012-12-18 14:30:41 +00007638 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7639 // Search and mark tokens that are macro argument expansions.
7640 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7641 Tokens, NumTokens);
7642 CursorVisitor MacroArgMarker(TU,
7643 MarkMacroArgTokensVisitorDelegate, &Visitor,
7644 /*VisitPreprocessorLast=*/true,
7645 /*VisitIncludedEntities=*/false,
7646 RegionOfInterest);
7647 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7648 }
7649
7650 // Annotate all of the source locations in the region of interest that map to
7651 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007652 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007653
7654 // FIXME: We use a ridiculous stack size here because the data-recursion
7655 // algorithm uses a large stack frame than the non-data recursive version,
7656 // and AnnotationTokensWorker currently transforms the data-recursion
7657 // algorithm back into a traditional recursion by explicitly calling
7658 // VisitChildren(). We will need to remove this explicit recursive call.
7659 W.AnnotateTokens();
7660
7661 // If we ran into any entities that involve context-sensitive keywords,
7662 // take another pass through the tokens to mark them as such.
7663 if (W.hasContextSensitiveKeywords()) {
7664 for (unsigned I = 0; I != NumTokens; ++I) {
7665 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7666 continue;
7667
7668 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7669 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007670 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007671 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7672 if (Property->getPropertyAttributesAsWritten() != 0 &&
7673 llvm::StringSwitch<bool>(II->getName())
7674 .Case("readonly", true)
7675 .Case("assign", true)
7676 .Case("unsafe_unretained", true)
7677 .Case("readwrite", true)
7678 .Case("retain", true)
7679 .Case("copy", true)
7680 .Case("nonatomic", true)
7681 .Case("atomic", true)
7682 .Case("getter", true)
7683 .Case("setter", true)
7684 .Case("strong", true)
7685 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007686 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007687 .Default(false))
7688 Tokens[I].int_data[0] = CXToken_Keyword;
7689 }
7690 continue;
7691 }
7692
7693 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7694 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7695 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7696 if (llvm::StringSwitch<bool>(II->getName())
7697 .Case("in", true)
7698 .Case("out", true)
7699 .Case("inout", true)
7700 .Case("oneway", true)
7701 .Case("bycopy", true)
7702 .Case("byref", true)
7703 .Default(false))
7704 Tokens[I].int_data[0] = CXToken_Keyword;
7705 continue;
7706 }
7707
7708 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7709 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7710 Tokens[I].int_data[0] = CXToken_Keyword;
7711 continue;
7712 }
7713 }
7714 }
7715}
7716
Guy Benyei11169dd2012-12-18 14:30:41 +00007717void clang_annotateTokens(CXTranslationUnit TU,
7718 CXToken *Tokens, unsigned NumTokens,
7719 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007720 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007721 LOG_BAD_TU(TU);
7722 return;
7723 }
7724 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007725 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007726 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007727 }
7728
7729 LOG_FUNC_SECTION {
7730 *Log << TU << ' ';
7731 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7732 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7733 *Log << clang_getRange(bloc, eloc);
7734 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007735
7736 // Any token we don't specifically annotate will have a NULL cursor.
7737 CXCursor C = clang_getNullCursor();
7738 for (unsigned I = 0; I != NumTokens; ++I)
7739 Cursors[I] = C;
7740
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007741 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007742 if (!CXXUnit)
7743 return;
7744
7745 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007746
7747 auto AnnotateTokensImpl = [=]() {
7748 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7749 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007750 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007751 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007752 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7753 }
7754}
7755
Guy Benyei11169dd2012-12-18 14:30:41 +00007756//===----------------------------------------------------------------------===//
7757// Operations for querying linkage of a cursor.
7758//===----------------------------------------------------------------------===//
7759
Guy Benyei11169dd2012-12-18 14:30:41 +00007760CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7761 if (!clang_isDeclaration(cursor.kind))
7762 return CXLinkage_Invalid;
7763
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007764 const Decl *D = cxcursor::getCursorDecl(cursor);
7765 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007766 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007767 case NoLinkage:
7768 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007769 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007770 case InternalLinkage: return CXLinkage_Internal;
7771 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007772 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007773 case ExternalLinkage: return CXLinkage_External;
7774 };
7775
7776 return CXLinkage_Invalid;
7777}
Guy Benyei11169dd2012-12-18 14:30:41 +00007778
7779//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007780// Operations for querying visibility of a cursor.
7781//===----------------------------------------------------------------------===//
7782
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007783CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7784 if (!clang_isDeclaration(cursor.kind))
7785 return CXVisibility_Invalid;
7786
7787 const Decl *D = cxcursor::getCursorDecl(cursor);
7788 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7789 switch (ND->getVisibility()) {
7790 case HiddenVisibility: return CXVisibility_Hidden;
7791 case ProtectedVisibility: return CXVisibility_Protected;
7792 case DefaultVisibility: return CXVisibility_Default;
7793 };
7794
7795 return CXVisibility_Invalid;
7796}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007797
7798//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007799// Operations for querying language of a cursor.
7800//===----------------------------------------------------------------------===//
7801
7802static CXLanguageKind getDeclLanguage(const Decl *D) {
7803 if (!D)
7804 return CXLanguage_C;
7805
7806 switch (D->getKind()) {
7807 default:
7808 break;
7809 case Decl::ImplicitParam:
7810 case Decl::ObjCAtDefsField:
7811 case Decl::ObjCCategory:
7812 case Decl::ObjCCategoryImpl:
7813 case Decl::ObjCCompatibleAlias:
7814 case Decl::ObjCImplementation:
7815 case Decl::ObjCInterface:
7816 case Decl::ObjCIvar:
7817 case Decl::ObjCMethod:
7818 case Decl::ObjCProperty:
7819 case Decl::ObjCPropertyImpl:
7820 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007821 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007822 return CXLanguage_ObjC;
7823 case Decl::CXXConstructor:
7824 case Decl::CXXConversion:
7825 case Decl::CXXDestructor:
7826 case Decl::CXXMethod:
7827 case Decl::CXXRecord:
7828 case Decl::ClassTemplate:
7829 case Decl::ClassTemplatePartialSpecialization:
7830 case Decl::ClassTemplateSpecialization:
7831 case Decl::Friend:
7832 case Decl::FriendTemplate:
7833 case Decl::FunctionTemplate:
7834 case Decl::LinkageSpec:
7835 case Decl::Namespace:
7836 case Decl::NamespaceAlias:
7837 case Decl::NonTypeTemplateParm:
7838 case Decl::StaticAssert:
7839 case Decl::TemplateTemplateParm:
7840 case Decl::TemplateTypeParm:
7841 case Decl::UnresolvedUsingTypename:
7842 case Decl::UnresolvedUsingValue:
7843 case Decl::Using:
7844 case Decl::UsingDirective:
7845 case Decl::UsingShadow:
7846 return CXLanguage_CPlusPlus;
7847 }
7848
7849 return CXLanguage_C;
7850}
7851
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007852static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7853 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007854 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007855
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007856 switch (D->getAvailability()) {
7857 case AR_Available:
7858 case AR_NotYetIntroduced:
7859 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007860 return getCursorAvailabilityForDecl(
7861 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007862 return CXAvailability_Available;
7863
7864 case AR_Deprecated:
7865 return CXAvailability_Deprecated;
7866
7867 case AR_Unavailable:
7868 return CXAvailability_NotAvailable;
7869 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007870
7871 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007872}
7873
Guy Benyei11169dd2012-12-18 14:30:41 +00007874enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7875 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007876 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7877 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007878
7879 return CXAvailability_Available;
7880}
7881
7882static CXVersion convertVersion(VersionTuple In) {
7883 CXVersion Out = { -1, -1, -1 };
7884 if (In.empty())
7885 return Out;
7886
7887 Out.Major = In.getMajor();
7888
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007889 Optional<unsigned> Minor = In.getMinor();
7890 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 Out.Minor = *Minor;
7892 else
7893 return Out;
7894
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007895 Optional<unsigned> Subminor = In.getSubminor();
7896 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007897 Out.Subminor = *Subminor;
7898
7899 return Out;
7900}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007901
Alex Lorenz1345ea22017-06-12 19:06:30 +00007902static void getCursorPlatformAvailabilityForDecl(
7903 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7904 int *always_unavailable, CXString *unavailable_message,
7905 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007906 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007907 for (auto A : D->attrs()) {
7908 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007909 HadAvailAttr = true;
7910 if (always_deprecated)
7911 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007912 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007913 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007914 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007915 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007916 continue;
7917 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007918
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007919 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007920 HadAvailAttr = true;
7921 if (always_unavailable)
7922 *always_unavailable = 1;
7923 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007924 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007925 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7926 }
7927 continue;
7928 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007929
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007930 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007931 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007932 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007933 }
7934 }
7935
7936 if (!HadAvailAttr)
7937 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7938 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007939 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7940 deprecated_message, always_unavailable, unavailable_message,
7941 AvailabilityAttrs);
7942
7943 if (AvailabilityAttrs.empty())
7944 return;
7945
Fangrui Song55fab262018-09-26 22:16:28 +00007946 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007947 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7948 return LHS->getPlatform()->getName() <
7949 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007950 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007951 ASTContext &Ctx = D->getASTContext();
7952 auto It = std::unique(
7953 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7954 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7955 if (LHS->getPlatform() != RHS->getPlatform())
7956 return false;
7957
7958 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7959 LHS->getDeprecated() == RHS->getDeprecated() &&
7960 LHS->getObsoleted() == RHS->getObsoleted() &&
7961 LHS->getMessage() == RHS->getMessage() &&
7962 LHS->getReplacement() == RHS->getReplacement())
7963 return true;
7964
7965 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7966 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7967 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7968 return false;
7969
7970 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7971 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7972
7973 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7974 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7975 if (LHS->getMessage().empty())
7976 LHS->setMessage(Ctx, RHS->getMessage());
7977 if (LHS->getReplacement().empty())
7978 LHS->setReplacement(Ctx, RHS->getReplacement());
7979 }
7980
7981 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7982 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7983 if (LHS->getMessage().empty())
7984 LHS->setMessage(Ctx, RHS->getMessage());
7985 if (LHS->getReplacement().empty())
7986 LHS->setReplacement(Ctx, RHS->getReplacement());
7987 }
7988
7989 return true;
7990 });
7991 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007992}
7993
Alex Lorenz1345ea22017-06-12 19:06:30 +00007994int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007995 CXString *deprecated_message,
7996 int *always_unavailable,
7997 CXString *unavailable_message,
7998 CXPlatformAvailability *availability,
7999 int availability_size) {
8000 if (always_deprecated)
8001 *always_deprecated = 0;
8002 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008003 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008004 if (always_unavailable)
8005 *always_unavailable = 0;
8006 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008007 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00008008
Guy Benyei11169dd2012-12-18 14:30:41 +00008009 if (!clang_isDeclaration(cursor.kind))
8010 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00008011
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008012 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 if (!D)
8014 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00008015
Alex Lorenz1345ea22017-06-12 19:06:30 +00008016 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
8017 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
8018 always_unavailable, unavailable_message,
8019 AvailabilityAttrs);
8020 for (const auto &Avail :
8021 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
8022 .take_front(availability_size))) {
8023 availability[Avail.index()].Platform =
8024 cxstring::createDup(Avail.value()->getPlatform()->getName());
8025 availability[Avail.index()].Introduced =
8026 convertVersion(Avail.value()->getIntroduced());
8027 availability[Avail.index()].Deprecated =
8028 convertVersion(Avail.value()->getDeprecated());
8029 availability[Avail.index()].Obsoleted =
8030 convertVersion(Avail.value()->getObsoleted());
8031 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
8032 availability[Avail.index()].Message =
8033 cxstring::createDup(Avail.value()->getMessage());
8034 }
8035
8036 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008037}
Alex Lorenz1345ea22017-06-12 19:06:30 +00008038
Guy Benyei11169dd2012-12-18 14:30:41 +00008039void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
8040 clang_disposeString(availability->Platform);
8041 clang_disposeString(availability->Message);
8042}
8043
8044CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
8045 if (clang_isDeclaration(cursor.kind))
8046 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
8047
8048 return CXLanguage_Invalid;
8049}
8050
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00008051CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
8052 const Decl *D = cxcursor::getCursorDecl(cursor);
8053 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8054 switch (VD->getTLSKind()) {
8055 case VarDecl::TLS_None:
8056 return CXTLS_None;
8057 case VarDecl::TLS_Dynamic:
8058 return CXTLS_Dynamic;
8059 case VarDecl::TLS_Static:
8060 return CXTLS_Static;
8061 }
8062 }
8063
8064 return CXTLS_None;
8065}
8066
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008067 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008068 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008069 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008070static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008072 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008073
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008074 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008075 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8076 return FunTmpl;
8077
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008078 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008079 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8080 return ClassTmpl;
8081
8082 return D;
8083}
8084
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008085
8086enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8087 StorageClass sc = SC_None;
8088 const Decl *D = getCursorDecl(C);
8089 if (D) {
8090 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8091 sc = FD->getStorageClass();
8092 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8093 sc = VD->getStorageClass();
8094 } else {
8095 return CX_SC_Invalid;
8096 }
8097 } else {
8098 return CX_SC_Invalid;
8099 }
8100 switch (sc) {
8101 case SC_None:
8102 return CX_SC_None;
8103 case SC_Extern:
8104 return CX_SC_Extern;
8105 case SC_Static:
8106 return CX_SC_Static;
8107 case SC_PrivateExtern:
8108 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008109 case SC_Auto:
8110 return CX_SC_Auto;
8111 case SC_Register:
8112 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008113 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008114 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008115}
8116
Guy Benyei11169dd2012-12-18 14:30:41 +00008117CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8118 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008119 if (const Decl *D = getCursorDecl(cursor)) {
8120 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 if (!DC)
8122 return clang_getNullCursor();
8123
8124 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8125 getCursorTU(cursor));
8126 }
8127 }
8128
8129 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008130 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008131 return MakeCXCursor(D, getCursorTU(cursor));
8132 }
8133
8134 return clang_getNullCursor();
8135}
8136
8137CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8138 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008139 if (const Decl *D = getCursorDecl(cursor)) {
8140 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008141 if (!DC)
8142 return clang_getNullCursor();
8143
8144 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8145 getCursorTU(cursor));
8146 }
8147 }
8148
8149 // FIXME: Note that we can't easily compute the lexical context of a
8150 // statement or expression, so we return nothing.
8151 return clang_getNullCursor();
8152}
8153
8154CXFile clang_getIncludedFile(CXCursor cursor) {
8155 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008156 return nullptr;
8157
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008158 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008159 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008160}
8161
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008162unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8163 if (C.kind != CXCursor_ObjCPropertyDecl)
8164 return CXObjCPropertyAttr_noattr;
8165
8166 unsigned Result = CXObjCPropertyAttr_noattr;
8167 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8168 ObjCPropertyDecl::PropertyAttributeKind Attr =
8169 PD->getPropertyAttributesAsWritten();
8170
8171#define SET_CXOBJCPROP_ATTR(A) \
8172 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8173 Result |= CXObjCPropertyAttr_##A
8174 SET_CXOBJCPROP_ATTR(readonly);
8175 SET_CXOBJCPROP_ATTR(getter);
8176 SET_CXOBJCPROP_ATTR(assign);
8177 SET_CXOBJCPROP_ATTR(readwrite);
8178 SET_CXOBJCPROP_ATTR(retain);
8179 SET_CXOBJCPROP_ATTR(copy);
8180 SET_CXOBJCPROP_ATTR(nonatomic);
8181 SET_CXOBJCPROP_ATTR(setter);
8182 SET_CXOBJCPROP_ATTR(atomic);
8183 SET_CXOBJCPROP_ATTR(weak);
8184 SET_CXOBJCPROP_ATTR(strong);
8185 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008186 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008187#undef SET_CXOBJCPROP_ATTR
8188
8189 return Result;
8190}
8191
Michael Wu6e88f532018-08-03 05:38:29 +00008192CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8193 if (C.kind != CXCursor_ObjCPropertyDecl)
8194 return cxstring::createNull();
8195
8196 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8197 Selector sel = PD->getGetterName();
8198 if (sel.isNull())
8199 return cxstring::createNull();
8200
8201 return cxstring::createDup(sel.getAsString());
8202}
8203
8204CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8205 if (C.kind != CXCursor_ObjCPropertyDecl)
8206 return cxstring::createNull();
8207
8208 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8209 Selector sel = PD->getSetterName();
8210 if (sel.isNull())
8211 return cxstring::createNull();
8212
8213 return cxstring::createDup(sel.getAsString());
8214}
8215
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008216unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8217 if (!clang_isDeclaration(C.kind))
8218 return CXObjCDeclQualifier_None;
8219
8220 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8221 const Decl *D = getCursorDecl(C);
8222 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8223 QT = MD->getObjCDeclQualifier();
8224 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8225 QT = PD->getObjCDeclQualifier();
8226 if (QT == Decl::OBJC_TQ_None)
8227 return CXObjCDeclQualifier_None;
8228
8229 unsigned Result = CXObjCDeclQualifier_None;
8230 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8231 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8232 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8233 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8234 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8235 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8236
8237 return Result;
8238}
8239
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008240unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8241 if (!clang_isDeclaration(C.kind))
8242 return 0;
8243
8244 const Decl *D = getCursorDecl(C);
8245 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8246 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8247 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8248 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8249
8250 return 0;
8251}
8252
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008253unsigned clang_Cursor_isVariadic(CXCursor C) {
8254 if (!clang_isDeclaration(C.kind))
8255 return 0;
8256
8257 const Decl *D = getCursorDecl(C);
8258 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8259 return FD->isVariadic();
8260 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8261 return MD->isVariadic();
8262
8263 return 0;
8264}
8265
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008266unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8267 CXString *language, CXString *definedIn,
8268 unsigned *isGenerated) {
8269 if (!clang_isDeclaration(C.kind))
8270 return 0;
8271
8272 const Decl *D = getCursorDecl(C);
8273
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008274 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008275 if (language)
8276 *language = cxstring::createDup(attr->getLanguage());
8277 if (definedIn)
8278 *definedIn = cxstring::createDup(attr->getDefinedIn());
8279 if (isGenerated)
8280 *isGenerated = attr->getGeneratedDeclaration();
8281 return 1;
8282 }
8283 return 0;
8284}
8285
Guy Benyei11169dd2012-12-18 14:30:41 +00008286CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8287 if (!clang_isDeclaration(C.kind))
8288 return clang_getNullRange();
8289
8290 const Decl *D = getCursorDecl(C);
8291 ASTContext &Context = getCursorContext(C);
8292 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8293 if (!RC)
8294 return clang_getNullRange();
8295
8296 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8297}
8298
8299CXString clang_Cursor_getRawCommentText(CXCursor C) {
8300 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008301 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008302
8303 const Decl *D = getCursorDecl(C);
8304 ASTContext &Context = getCursorContext(C);
8305 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8306 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8307 StringRef();
8308
8309 // Don't duplicate the string because RawText points directly into source
8310 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008311 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008312}
8313
8314CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8315 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008316 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008317
8318 const Decl *D = getCursorDecl(C);
8319 const ASTContext &Context = getCursorContext(C);
8320 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8321
8322 if (RC) {
8323 StringRef BriefText = RC->getBriefText(Context);
8324
8325 // Don't duplicate the string because RawComment ensures that this memory
8326 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008327 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008328 }
8329
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008330 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008331}
8332
Guy Benyei11169dd2012-12-18 14:30:41 +00008333CXModule clang_Cursor_getModule(CXCursor C) {
8334 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008335 if (const ImportDecl *ImportD =
8336 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008337 return ImportD->getImportedModule();
8338 }
8339
Craig Topper69186e72014-06-08 08:38:04 +00008340 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008341}
8342
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008343CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8344 if (isNotUsableTU(TU)) {
8345 LOG_BAD_TU(TU);
8346 return nullptr;
8347 }
8348 if (!File)
8349 return nullptr;
8350 FileEntry *FE = static_cast<FileEntry *>(File);
8351
8352 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8353 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8354 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8355
Richard Smithfeb54b62014-10-23 02:01:19 +00008356 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008357}
8358
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008359CXFile clang_Module_getASTFile(CXModule CXMod) {
8360 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008361 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008362 Module *Mod = static_cast<Module*>(CXMod);
8363 return const_cast<FileEntry *>(Mod->getASTFile());
8364}
8365
Guy Benyei11169dd2012-12-18 14:30:41 +00008366CXModule clang_Module_getParent(CXModule CXMod) {
8367 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008368 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008369 Module *Mod = static_cast<Module*>(CXMod);
8370 return Mod->Parent;
8371}
8372
8373CXString clang_Module_getName(CXModule CXMod) {
8374 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008375 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008376 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008377 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008378}
8379
8380CXString clang_Module_getFullName(CXModule CXMod) {
8381 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008382 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008383 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008384 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008385}
8386
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008387int clang_Module_isSystem(CXModule CXMod) {
8388 if (!CXMod)
8389 return 0;
8390 Module *Mod = static_cast<Module*>(CXMod);
8391 return Mod->IsSystem;
8392}
8393
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008394unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8395 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008396 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008397 LOG_BAD_TU(TU);
8398 return 0;
8399 }
8400 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008401 return 0;
8402 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008403 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8404 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8405 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008406}
8407
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008408CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8409 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008410 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008411 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008412 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008413 }
8414 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008415 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008416 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008417 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008418
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008419 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8420 if (Index < TopHeaders.size())
8421 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008422
Craig Topper69186e72014-06-08 08:38:04 +00008423 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008424}
8425
Guy Benyei11169dd2012-12-18 14:30:41 +00008426//===----------------------------------------------------------------------===//
8427// C++ AST instrospection.
8428//===----------------------------------------------------------------------===//
8429
Jonathan Coe29565352016-04-27 12:48:25 +00008430unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8431 if (!clang_isDeclaration(C.kind))
8432 return 0;
8433
8434 const Decl *D = cxcursor::getCursorDecl(C);
8435 const CXXConstructorDecl *Constructor =
8436 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8437 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8438}
8439
8440unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8441 if (!clang_isDeclaration(C.kind))
8442 return 0;
8443
8444 const Decl *D = cxcursor::getCursorDecl(C);
8445 const CXXConstructorDecl *Constructor =
8446 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8447 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8448}
8449
8450unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8451 if (!clang_isDeclaration(C.kind))
8452 return 0;
8453
8454 const Decl *D = cxcursor::getCursorDecl(C);
8455 const CXXConstructorDecl *Constructor =
8456 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8457 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8458}
8459
8460unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8461 if (!clang_isDeclaration(C.kind))
8462 return 0;
8463
8464 const Decl *D = cxcursor::getCursorDecl(C);
8465 const CXXConstructorDecl *Constructor =
8466 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8467 // Passing 'false' excludes constructors marked 'explicit'.
8468 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8469}
8470
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008471unsigned clang_CXXField_isMutable(CXCursor C) {
8472 if (!clang_isDeclaration(C.kind))
8473 return 0;
8474
8475 if (const auto D = cxcursor::getCursorDecl(C))
8476 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8477 return FD->isMutable() ? 1 : 0;
8478 return 0;
8479}
8480
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008481unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8482 if (!clang_isDeclaration(C.kind))
8483 return 0;
8484
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008485 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008486 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008487 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008488 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8489}
8490
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008491unsigned clang_CXXMethod_isConst(CXCursor C) {
8492 if (!clang_isDeclaration(C.kind))
8493 return 0;
8494
8495 const Decl *D = cxcursor::getCursorDecl(C);
8496 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008497 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008498 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008499}
8500
Jonathan Coe29565352016-04-27 12:48:25 +00008501unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8502 if (!clang_isDeclaration(C.kind))
8503 return 0;
8504
8505 const Decl *D = cxcursor::getCursorDecl(C);
8506 const CXXMethodDecl *Method =
8507 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8508 return (Method && Method->isDefaulted()) ? 1 : 0;
8509}
8510
Guy Benyei11169dd2012-12-18 14:30:41 +00008511unsigned clang_CXXMethod_isStatic(CXCursor C) {
8512 if (!clang_isDeclaration(C.kind))
8513 return 0;
8514
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008515 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008516 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008517 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008518 return (Method && Method->isStatic()) ? 1 : 0;
8519}
8520
8521unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8522 if (!clang_isDeclaration(C.kind))
8523 return 0;
8524
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008525 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008526 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008527 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008528 return (Method && Method->isVirtual()) ? 1 : 0;
8529}
Guy Benyei11169dd2012-12-18 14:30:41 +00008530
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008531unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8532 if (!clang_isDeclaration(C.kind))
8533 return 0;
8534
8535 const auto *D = cxcursor::getCursorDecl(C);
8536 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8537 if (RD)
8538 RD = RD->getDefinition();
8539 return (RD && RD->isAbstract()) ? 1 : 0;
8540}
8541
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008542unsigned clang_EnumDecl_isScoped(CXCursor C) {
8543 if (!clang_isDeclaration(C.kind))
8544 return 0;
8545
8546 const Decl *D = cxcursor::getCursorDecl(C);
8547 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8548 return (Enum && Enum->isScoped()) ? 1 : 0;
8549}
8550
Guy Benyei11169dd2012-12-18 14:30:41 +00008551//===----------------------------------------------------------------------===//
8552// Attribute introspection.
8553//===----------------------------------------------------------------------===//
8554
Guy Benyei11169dd2012-12-18 14:30:41 +00008555CXType clang_getIBOutletCollectionType(CXCursor C) {
8556 if (C.kind != CXCursor_IBOutletCollectionAttr)
8557 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8558
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008559 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008560 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8561
8562 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8563}
Guy Benyei11169dd2012-12-18 14:30:41 +00008564
8565//===----------------------------------------------------------------------===//
8566// Inspecting memory usage.
8567//===----------------------------------------------------------------------===//
8568
8569typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8570
8571static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8572 enum CXTUResourceUsageKind k,
8573 unsigned long amount) {
8574 CXTUResourceUsageEntry entry = { k, amount };
8575 entries.push_back(entry);
8576}
8577
Guy Benyei11169dd2012-12-18 14:30:41 +00008578const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8579 const char *str = "";
8580 switch (kind) {
8581 case CXTUResourceUsage_AST:
8582 str = "ASTContext: expressions, declarations, and types";
8583 break;
8584 case CXTUResourceUsage_Identifiers:
8585 str = "ASTContext: identifiers";
8586 break;
8587 case CXTUResourceUsage_Selectors:
8588 str = "ASTContext: selectors";
8589 break;
8590 case CXTUResourceUsage_GlobalCompletionResults:
8591 str = "Code completion: cached global results";
8592 break;
8593 case CXTUResourceUsage_SourceManagerContentCache:
8594 str = "SourceManager: content cache allocator";
8595 break;
8596 case CXTUResourceUsage_AST_SideTables:
8597 str = "ASTContext: side tables";
8598 break;
8599 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8600 str = "SourceManager: malloc'ed memory buffers";
8601 break;
8602 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8603 str = "SourceManager: mmap'ed memory buffers";
8604 break;
8605 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8606 str = "ExternalASTSource: malloc'ed memory buffers";
8607 break;
8608 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8609 str = "ExternalASTSource: mmap'ed memory buffers";
8610 break;
8611 case CXTUResourceUsage_Preprocessor:
8612 str = "Preprocessor: malloc'ed memory";
8613 break;
8614 case CXTUResourceUsage_PreprocessingRecord:
8615 str = "Preprocessor: PreprocessingRecord";
8616 break;
8617 case CXTUResourceUsage_SourceManager_DataStructures:
8618 str = "SourceManager: data structures and tables";
8619 break;
8620 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8621 str = "Preprocessor: header search tables";
8622 break;
8623 }
8624 return str;
8625}
8626
8627CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008628 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008629 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008630 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008631 return usage;
8632 }
8633
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008634 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008635 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008636 ASTContext &astContext = astUnit->getASTContext();
8637
8638 // How much memory is used by AST nodes and types?
8639 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8640 (unsigned long) astContext.getASTAllocatedMemory());
8641
8642 // How much memory is used by identifiers?
8643 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8644 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8645
8646 // How much memory is used for selectors?
8647 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8648 (unsigned long) astContext.Selectors.getTotalMemory());
8649
8650 // How much memory is used by ASTContext's side tables?
8651 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8652 (unsigned long) astContext.getSideTableAllocatedMemory());
8653
8654 // How much memory is used for caching global code completion results?
8655 unsigned long completionBytes = 0;
8656 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008657 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008658 completionBytes = completionAllocator->getTotalMemory();
8659 }
8660 createCXTUResourceUsageEntry(*entries,
8661 CXTUResourceUsage_GlobalCompletionResults,
8662 completionBytes);
8663
8664 // How much memory is being used by SourceManager's content cache?
8665 createCXTUResourceUsageEntry(*entries,
8666 CXTUResourceUsage_SourceManagerContentCache,
8667 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8668
8669 // How much memory is being used by the MemoryBuffer's in SourceManager?
8670 const SourceManager::MemoryBufferSizes &srcBufs =
8671 astUnit->getSourceManager().getMemoryBufferSizes();
8672
8673 createCXTUResourceUsageEntry(*entries,
8674 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8675 (unsigned long) srcBufs.malloc_bytes);
8676 createCXTUResourceUsageEntry(*entries,
8677 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8678 (unsigned long) srcBufs.mmap_bytes);
8679 createCXTUResourceUsageEntry(*entries,
8680 CXTUResourceUsage_SourceManager_DataStructures,
8681 (unsigned long) astContext.getSourceManager()
8682 .getDataStructureSizes());
8683
8684 // How much memory is being used by the ExternalASTSource?
8685 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8686 const ExternalASTSource::MemoryBufferSizes &sizes =
8687 esrc->getMemoryBufferSizes();
8688
8689 createCXTUResourceUsageEntry(*entries,
8690 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8691 (unsigned long) sizes.malloc_bytes);
8692 createCXTUResourceUsageEntry(*entries,
8693 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8694 (unsigned long) sizes.mmap_bytes);
8695 }
8696
8697 // How much memory is being used by the Preprocessor?
8698 Preprocessor &pp = astUnit->getPreprocessor();
8699 createCXTUResourceUsageEntry(*entries,
8700 CXTUResourceUsage_Preprocessor,
8701 pp.getTotalMemory());
8702
8703 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8704 createCXTUResourceUsageEntry(*entries,
8705 CXTUResourceUsage_PreprocessingRecord,
8706 pRec->getTotalMemory());
8707 }
8708
8709 createCXTUResourceUsageEntry(*entries,
8710 CXTUResourceUsage_Preprocessor_HeaderSearch,
8711 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008712
Guy Benyei11169dd2012-12-18 14:30:41 +00008713 CXTUResourceUsage usage = { (void*) entries.get(),
8714 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008715 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008716 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008717 return usage;
8718}
8719
8720void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8721 if (usage.data)
8722 delete (MemUsageEntries*) usage.data;
8723}
8724
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008725CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8726 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008727 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008728 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008729
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008730 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008731 LOG_BAD_TU(TU);
8732 return skipped;
8733 }
8734
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008735 if (!file)
8736 return skipped;
8737
8738 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8739 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8740 if (!ppRec)
8741 return skipped;
8742
8743 ASTContext &Ctx = astUnit->getASTContext();
8744 SourceManager &sm = Ctx.getSourceManager();
8745 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8746 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008747 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008748
8749 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8750 std::vector<SourceRange> wantedRanges;
8751 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8752 i != ei; ++i) {
8753 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8754 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008755 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8756 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008757 }
8758
8759 skipped->count = wantedRanges.size();
8760 skipped->ranges = new CXSourceRange[skipped->count];
8761 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8762 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8763
8764 return skipped;
8765}
8766
Cameron Desrochersd8091282016-08-18 15:43:55 +00008767CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8768 CXSourceRangeList *skipped = new CXSourceRangeList;
8769 skipped->count = 0;
8770 skipped->ranges = nullptr;
8771
8772 if (isNotUsableTU(TU)) {
8773 LOG_BAD_TU(TU);
8774 return skipped;
8775 }
8776
8777 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8778 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8779 if (!ppRec)
8780 return skipped;
8781
8782 ASTContext &Ctx = astUnit->getASTContext();
8783
8784 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8785
8786 skipped->count = SkippedRanges.size();
8787 skipped->ranges = new CXSourceRange[skipped->count];
8788 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8789 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8790
8791 return skipped;
8792}
8793
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008794void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8795 if (ranges) {
8796 delete[] ranges->ranges;
8797 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008798 }
8799}
8800
Guy Benyei11169dd2012-12-18 14:30:41 +00008801void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8802 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8803 for (unsigned I = 0; I != Usage.numEntries; ++I)
8804 fprintf(stderr, " %s: %lu\n",
8805 clang_getTUResourceUsageName(Usage.entries[I].kind),
8806 Usage.entries[I].amount);
8807
8808 clang_disposeCXTUResourceUsage(Usage);
8809}
8810
8811//===----------------------------------------------------------------------===//
8812// Misc. utility functions.
8813//===----------------------------------------------------------------------===//
8814
Richard Smith0a7b2972018-07-03 21:34:13 +00008815/// Default to using our desired 8 MB stack size on "safety" threads.
8816static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008817
8818namespace clang {
8819
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008820bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008821 unsigned Size) {
8822 if (!Size)
8823 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008824 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008825 return CRC.RunSafelyOnThread(Fn, Size);
8826 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008827}
8828
8829unsigned GetSafetyThreadStackSize() {
8830 return SafetyStackThreadSize;
8831}
8832
8833void SetSafetyThreadStackSize(unsigned Value) {
8834 SafetyStackThreadSize = Value;
8835}
8836
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008837}
Guy Benyei11169dd2012-12-18 14:30:41 +00008838
8839void clang::setThreadBackgroundPriority() {
8840 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8841 return;
8842
Nico Weber18cfd9f2019-04-21 19:18:41 +00008843#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008844 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008845#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008846}
8847
8848void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8849 if (!Unit)
8850 return;
8851
8852 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8853 DEnd = Unit->stored_diag_end();
8854 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008855 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008856 CXString Msg = clang_formatDiagnostic(&Diag,
8857 clang_defaultDiagnosticDisplayOptions());
8858 fprintf(stderr, "%s\n", clang_getCString(Msg));
8859 clang_disposeString(Msg);
8860 }
Nico Weber1865df42018-04-27 19:11:14 +00008861#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008862 // On Windows, force a flush, since there may be multiple copies of
8863 // stderr and stdout in the file system, all with different buffers
8864 // but writing to the same device.
8865 fflush(stderr);
8866#endif
8867}
8868
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008869MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8870 SourceLocation MacroDefLoc,
8871 CXTranslationUnit TU){
8872 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008873 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008874 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008875 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008876
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008877 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008878 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008879 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008880 if (MD) {
8881 for (MacroDirective::DefInfo
8882 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8883 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8884 return Def.getMacroInfo();
8885 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008886 }
8887
Craig Topper69186e72014-06-08 08:38:04 +00008888 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008889}
8890
Richard Smith66a81862015-05-04 02:25:31 +00008891const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008892 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008893 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008894 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008895 const IdentifierInfo *II = MacroDef->getName();
8896 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008897 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008898
8899 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8900}
8901
Richard Smith66a81862015-05-04 02:25:31 +00008902MacroDefinitionRecord *
8903cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8904 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008905 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008906 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008907 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008908 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008909
8910 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008911 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008912 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8913 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008914 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008915
8916 // Check that the token is inside the definition and not its argument list.
8917 SourceManager &SM = Unit->getSourceManager();
8918 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008919 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008920 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008921 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008922
8923 Preprocessor &PP = Unit->getPreprocessor();
8924 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8925 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008926 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008927
Alp Toker2d57cea2014-05-17 04:53:25 +00008928 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008929 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008930 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008931
8932 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008933 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008934 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008935
Richard Smith20e883e2015-04-29 23:20:19 +00008936 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008937 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008938 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008939
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008940 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008941}
8942
Richard Smith66a81862015-05-04 02:25:31 +00008943MacroDefinitionRecord *
8944cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8945 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008946 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008947 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008948
8949 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008950 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008951 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008952 Preprocessor &PP = Unit->getPreprocessor();
8953 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008954 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008955 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8956 Token Tok;
8957 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008958 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008959
8960 return checkForMacroInMacroDefinition(MI, Tok, TU);
8961}
8962
Guy Benyei11169dd2012-12-18 14:30:41 +00008963CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008964 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008965}
8966
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008967Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8968 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008969 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008970 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008971 if (Unit->isMainFileAST())
8972 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008973 return *this;
8974 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008975 } else {
8976 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008977 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008978 return *this;
8979}
8980
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008981Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8982 *this << FE->getName();
8983 return *this;
8984}
8985
8986Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8987 CXString cursorName = clang_getCursorDisplayName(cursor);
8988 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8989 clang_disposeString(cursorName);
8990 return *this;
8991}
8992
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008993Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8994 CXFile File;
8995 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008996 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008997 CXString FileName = clang_getFileName(File);
8998 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8999 clang_disposeString(FileName);
9000 return *this;
9001}
9002
9003Logger &cxindex::Logger::operator<<(CXSourceRange range) {
9004 CXSourceLocation BLoc = clang_getRangeStart(range);
9005 CXSourceLocation ELoc = clang_getRangeEnd(range);
9006
9007 CXFile BFile;
9008 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00009009 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009010
9011 CXFile EFile;
9012 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00009013 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009014
9015 CXString BFileName = clang_getFileName(BFile);
9016 if (BFile == EFile) {
9017 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
9018 BLine, BColumn, ELine, EColumn);
9019 } else {
9020 CXString EFileName = clang_getFileName(EFile);
9021 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
9022 BLine, BColumn)
9023 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
9024 ELine, EColumn);
9025 clang_disposeString(EFileName);
9026 }
9027 clang_disposeString(BFileName);
9028 return *this;
9029}
9030
9031Logger &cxindex::Logger::operator<<(CXString Str) {
9032 *this << clang_getCString(Str);
9033 return *this;
9034}
9035
9036Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
9037 LogOS << Fmt;
9038 return *this;
9039}
9040
Benjamin Kramer762bc332019-08-07 14:44:40 +00009041static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00009042
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009043cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00009044 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009045
9046 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
9047
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009048 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009049 OS << "[libclang:" << Name << ':';
9050
Alp Toker1a86ad22014-07-06 06:24:00 +00009051#ifdef USE_DARWIN_THREADS
9052 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009053 mach_port_t tid = pthread_mach_thread_np(pthread_self());
9054 OS << tid << ':';
9055#endif
9056
9057 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
9058 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00009059 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009060
9061 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00009062 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009063 OS << "--------------------------------------------------\n";
9064 }
9065}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00009066
9067#ifdef CLANG_TOOL_EXTRA_BUILD
9068// This anchor is used to force the linker to link the clang-tidy plugin.
9069extern volatile int ClangTidyPluginAnchorSource;
9070static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9071 ClangTidyPluginAnchorSource;
9072
9073// This anchor is used to force the linker to link the clang-include-fixer
9074// plugin.
9075extern volatile int ClangIncludeFixerPluginAnchorSource;
9076static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9077 ClangIncludeFixerPluginAnchorSource;
9078#endif