blob: 12479c7abb84e7bab1bb7e5195ee3339f3f77e87 [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 Bataev9fb6e642014-07-22 06:45:04 +00002050 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002051 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002052 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002053 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002054 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002055 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002056 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002057 void
2058 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002059 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002060 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002061 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Alexey Bataev60e51c42019-10-10 20:13:02 +00002062 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002063 void
2064 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002065 void VisitOMPParallelMasterTaskLoopDirective(
2066 const OMPParallelMasterTaskLoopDirective *D);
Alexey Bataev14a388f2019-10-25 10:27:13 -04002067 void VisitOMPParallelMasterTaskLoopSimdDirective(
2068 const OMPParallelMasterTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002069 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002070 void VisitOMPDistributeParallelForDirective(
2071 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002072 void VisitOMPDistributeParallelForSimdDirective(
2073 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002074 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002075 void VisitOMPTargetParallelForSimdDirective(
2076 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002077 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002078 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002079 void VisitOMPTeamsDistributeSimdDirective(
2080 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002081 void VisitOMPTeamsDistributeParallelForSimdDirective(
2082 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002083 void VisitOMPTeamsDistributeParallelForDirective(
2084 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002085 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002086 void VisitOMPTargetTeamsDistributeDirective(
2087 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002088 void VisitOMPTargetTeamsDistributeParallelForDirective(
2089 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002090 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2091 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002092 void VisitOMPTargetTeamsDistributeSimdDirective(
2093 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002094
Guy Benyei11169dd2012-12-18 14:30:41 +00002095private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002096 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002097 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002098 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2099 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002100 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2101 void AddStmt(const Stmt *S);
2102 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002103 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002104 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002105 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002106};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002107} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002108
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002109void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002110 // 'S' should always be non-null, since it comes from the
2111 // statement we are visiting.
2112 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2113}
2114
2115void
2116EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2117 if (Qualifier)
2118 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2119}
2120
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002121void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002122 if (S)
2123 WL.push_back(StmtVisit(S, Parent));
2124}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002125void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002126 if (D)
2127 WL.push_back(DeclVisit(D, Parent, isFirst));
2128}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002129void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2130 unsigned NumTemplateArgs) {
2131 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002132}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002133void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002134 if (D)
2135 WL.push_back(MemberRefVisit(D, L, Parent));
2136}
2137void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2138 if (TI)
2139 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2140 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002141void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002142 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002143 for (const Stmt *SubStmt : S->children()) {
2144 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002145 }
2146 if (size == WL.size())
2147 return;
2148 // Now reverse the entries we just added. This will match the DFS
2149 // ordering performed by the worklist.
2150 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2151 std::reverse(I, E);
2152}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002153namespace {
2154class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2155 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002156 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002157 template <typename T>
2158 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002159public:
2160 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2161#define OPENMP_CLAUSE(Name, Class) \
2162 void Visit##Class(const Class *C);
2163#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002164 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002165 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002166};
2167
Alexey Bataev3392d762016-02-16 11:18:12 +00002168void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2169 const OMPClauseWithPreInit *C) {
2170 Visitor->AddStmt(C->getPreInitStmt());
2171}
2172
Alexey Bataev005248a2016-02-25 05:25:57 +00002173void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2174 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002175 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002176 Visitor->AddStmt(C->getPostUpdateExpr());
2177}
2178
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002179void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002180 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002181 Visitor->AddStmt(C->getCondition());
2182}
2183
Alexey Bataev3778b602014-07-17 07:32:53 +00002184void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2185 Visitor->AddStmt(C->getCondition());
2186}
2187
Alexey Bataev568a8332014-03-06 06:15:19 +00002188void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002189 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002190 Visitor->AddStmt(C->getNumThreads());
2191}
2192
Alexey Bataev62c87d22014-03-21 04:51:18 +00002193void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2194 Visitor->AddStmt(C->getSafelen());
2195}
2196
Alexey Bataev66b15b52015-08-21 11:14:16 +00002197void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2198 Visitor->AddStmt(C->getSimdlen());
2199}
2200
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002201void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2202 Visitor->AddStmt(C->getAllocator());
2203}
2204
Alexander Musman8bd31e62014-05-27 15:12:19 +00002205void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2206 Visitor->AddStmt(C->getNumForLoops());
2207}
2208
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002209void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002210
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002211void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2212
Alexey Bataev56dafe82014-06-20 07:16:17 +00002213void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002214 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002215 Visitor->AddStmt(C->getChunkSize());
2216}
2217
Alexey Bataev10e775f2015-07-30 11:36:16 +00002218void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2219 Visitor->AddStmt(C->getNumForLoops());
2220}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002221
Alexey Bataev236070f2014-06-20 11:19:47 +00002222void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2223
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002224void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2225
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002226void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2227
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002228void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2229
Alexey Bataevdea47612014-07-23 07:46:59 +00002230void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2231
Alexey Bataev67a4f222014-07-23 10:25:33 +00002232void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2233
Alexey Bataev459dec02014-07-24 06:46:57 +00002234void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2235
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002236void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2237
Alexey Bataevea9166b2020-02-06 16:30:23 -05002238void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
2239
Alexey Bataev04a830f2020-02-10 14:30:39 -05002240void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
2241
Alexey Bataev95598342020-02-10 15:49:05 -05002242void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {}
2243
Alexey Bataev346265e2015-09-25 10:37:12 +00002244void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2245
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002246void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2247
Alexey Bataevb825de12015-12-07 10:51:44 +00002248void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2249
Kelvin Li1408f912018-09-26 04:28:39 +00002250void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2251 const OMPUnifiedAddressClause *) {}
2252
Patrick Lyster4a370b92018-10-01 13:47:43 +00002253void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2254 const OMPUnifiedSharedMemoryClause *) {}
2255
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002256void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2257 const OMPReverseOffloadClause *) {}
2258
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002259void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2260 const OMPDynamicAllocatorsClause *) {}
2261
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002262void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2263 const OMPAtomicDefaultMemOrderClause *) {}
2264
Michael Wonge710d542015-08-07 16:16:36 +00002265void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2266 Visitor->AddStmt(C->getDevice());
2267}
2268
Kelvin Li099bb8c2015-11-24 20:50:12 +00002269void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002270 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002271 Visitor->AddStmt(C->getNumTeams());
2272}
2273
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002274void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002275 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002276 Visitor->AddStmt(C->getThreadLimit());
2277}
2278
Alexey Bataeva0569352015-12-01 10:17:31 +00002279void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2280 Visitor->AddStmt(C->getPriority());
2281}
2282
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002283void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2284 Visitor->AddStmt(C->getGrainsize());
2285}
2286
Alexey Bataev382967a2015-12-08 12:06:20 +00002287void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2288 Visitor->AddStmt(C->getNumTasks());
2289}
2290
Alexey Bataev28c75412015-12-15 08:19:24 +00002291void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2292 Visitor->AddStmt(C->getHint());
2293}
2294
Alexey Bataev756c1962013-09-24 03:17:45 +00002295template<typename T>
2296void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002297 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002298 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002299 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002300}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002301
Alexey Bataeve04483e2019-03-27 14:14:31 +00002302void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2303 VisitOMPClauseList(C);
2304 Visitor->AddStmt(C->getAllocator());
2305}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002306void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002307 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002308 for (const auto *E : C->private_copies()) {
2309 Visitor->AddStmt(E);
2310 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002311}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002312void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2313 const OMPFirstprivateClause *C) {
2314 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002315 VisitOMPClauseWithPreInit(C);
2316 for (const auto *E : C->private_copies()) {
2317 Visitor->AddStmt(E);
2318 }
2319 for (const auto *E : C->inits()) {
2320 Visitor->AddStmt(E);
2321 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002322}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002323void OMPClauseEnqueue::VisitOMPLastprivateClause(
2324 const OMPLastprivateClause *C) {
2325 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002326 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002327 for (auto *E : C->private_copies()) {
2328 Visitor->AddStmt(E);
2329 }
2330 for (auto *E : C->source_exprs()) {
2331 Visitor->AddStmt(E);
2332 }
2333 for (auto *E : C->destination_exprs()) {
2334 Visitor->AddStmt(E);
2335 }
2336 for (auto *E : C->assignment_ops()) {
2337 Visitor->AddStmt(E);
2338 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002339}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002340void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002341 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002342}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002343void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2344 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002345 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002346 for (auto *E : C->privates()) {
2347 Visitor->AddStmt(E);
2348 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002349 for (auto *E : C->lhs_exprs()) {
2350 Visitor->AddStmt(E);
2351 }
2352 for (auto *E : C->rhs_exprs()) {
2353 Visitor->AddStmt(E);
2354 }
2355 for (auto *E : C->reduction_ops()) {
2356 Visitor->AddStmt(E);
2357 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002358}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002359void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2360 const OMPTaskReductionClause *C) {
2361 VisitOMPClauseList(C);
2362 VisitOMPClauseWithPostUpdate(C);
2363 for (auto *E : C->privates()) {
2364 Visitor->AddStmt(E);
2365 }
2366 for (auto *E : C->lhs_exprs()) {
2367 Visitor->AddStmt(E);
2368 }
2369 for (auto *E : C->rhs_exprs()) {
2370 Visitor->AddStmt(E);
2371 }
2372 for (auto *E : C->reduction_ops()) {
2373 Visitor->AddStmt(E);
2374 }
2375}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002376void OMPClauseEnqueue::VisitOMPInReductionClause(
2377 const OMPInReductionClause *C) {
2378 VisitOMPClauseList(C);
2379 VisitOMPClauseWithPostUpdate(C);
2380 for (auto *E : C->privates()) {
2381 Visitor->AddStmt(E);
2382 }
2383 for (auto *E : C->lhs_exprs()) {
2384 Visitor->AddStmt(E);
2385 }
2386 for (auto *E : C->rhs_exprs()) {
2387 Visitor->AddStmt(E);
2388 }
2389 for (auto *E : C->reduction_ops()) {
2390 Visitor->AddStmt(E);
2391 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002392 for (auto *E : C->taskgroup_descriptors())
2393 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002394}
Alexander Musman8dba6642014-04-22 13:09:42 +00002395void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2396 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002397 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002398 for (const auto *E : C->privates()) {
2399 Visitor->AddStmt(E);
2400 }
Alexander Musman3276a272015-03-21 10:12:56 +00002401 for (const auto *E : C->inits()) {
2402 Visitor->AddStmt(E);
2403 }
2404 for (const auto *E : C->updates()) {
2405 Visitor->AddStmt(E);
2406 }
2407 for (const auto *E : C->finals()) {
2408 Visitor->AddStmt(E);
2409 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002410 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002411 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002412}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002413void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2414 VisitOMPClauseList(C);
2415 Visitor->AddStmt(C->getAlignment());
2416}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002417void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2418 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002419 for (auto *E : C->source_exprs()) {
2420 Visitor->AddStmt(E);
2421 }
2422 for (auto *E : C->destination_exprs()) {
2423 Visitor->AddStmt(E);
2424 }
2425 for (auto *E : C->assignment_ops()) {
2426 Visitor->AddStmt(E);
2427 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002428}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002429void
2430OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2431 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002432 for (auto *E : C->source_exprs()) {
2433 Visitor->AddStmt(E);
2434 }
2435 for (auto *E : C->destination_exprs()) {
2436 Visitor->AddStmt(E);
2437 }
2438 for (auto *E : C->assignment_ops()) {
2439 Visitor->AddStmt(E);
2440 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002441}
Alexey Bataev6125da92014-07-21 11:26:11 +00002442void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2443 VisitOMPClauseList(C);
2444}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002445void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2446 VisitOMPClauseList(C);
2447}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002448void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2449 VisitOMPClauseList(C);
2450}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002451void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2452 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002453 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002454 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002455}
Alexey Bataev3392d762016-02-16 11:18:12 +00002456void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2457 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002458void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2459 VisitOMPClauseList(C);
2460}
Samuel Antaoec172c62016-05-26 17:49:04 +00002461void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2462 VisitOMPClauseList(C);
2463}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002464void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2465 VisitOMPClauseList(C);
2466}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002467void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2468 VisitOMPClauseList(C);
2469}
Alexey Bataevb6e70842019-12-16 15:54:17 -05002470void OMPClauseEnqueue::VisitOMPNontemporalClause(
2471 const OMPNontemporalClause *C) {
2472 VisitOMPClauseList(C);
Alexey Bataev0860db92019-12-19 10:01:10 -05002473 for (const auto *E : C->private_refs())
2474 Visitor->AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05002475}
Alexey Bataevcb8e6912020-01-31 16:09:26 -05002476void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002477}
Alexey Bataev756c1962013-09-24 03:17:45 +00002478
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002479void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2480 unsigned size = WL.size();
2481 OMPClauseEnqueue Visitor(this);
2482 Visitor.Visit(S);
2483 if (size == WL.size())
2484 return;
2485 // Now reverse the entries we just added. This will match the DFS
2486 // ordering performed by the worklist.
2487 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2488 std::reverse(I, E);
2489}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002490void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2492}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002493void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 AddDecl(B->getBlockDecl());
2495}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002496void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 EnqueueChildren(E);
2498 AddTypeLoc(E->getTypeSourceInfo());
2499}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002500void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002501 for (auto &I : llvm::reverse(S->body()))
2502 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002503}
2504void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002505VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 AddStmt(S->getSubStmt());
2507 AddDeclarationNameInfo(S);
2508 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2509 AddNestedNameSpecifierLoc(QualifierLoc);
2510}
2511
2512void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002513VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002514 if (E->hasExplicitTemplateArgs())
2515 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 AddDeclarationNameInfo(E);
2517 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2518 AddNestedNameSpecifierLoc(QualifierLoc);
2519 if (!E->isImplicitAccess())
2520 AddStmt(E->getBase());
2521}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002522void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 // Enqueue the initializer , if any.
2524 AddStmt(E->getInitializer());
2525 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002526 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 // Enqueue the allocated type.
2528 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2529 // Enqueue the placement arguments.
2530 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2531 AddStmt(E->getPlacementArg(I-1));
2532}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002533void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2535 AddStmt(CE->getArg(I-1));
2536 AddStmt(CE->getCallee());
2537 AddStmt(CE->getArg(0));
2538}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002539void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2540 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 // Visit the name of the type being destroyed.
2542 AddTypeLoc(E->getDestroyedTypeInfo());
2543 // Visit the scope type that looks disturbingly like the nested-name-specifier
2544 // but isn't.
2545 AddTypeLoc(E->getScopeTypeInfo());
2546 // Visit the nested-name-specifier.
2547 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2548 AddNestedNameSpecifierLoc(QualifierLoc);
2549 // Visit base expression.
2550 AddStmt(E->getBase());
2551}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002552void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2553 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 AddTypeLoc(E->getTypeSourceInfo());
2555}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002556void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2557 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 EnqueueChildren(E);
2559 AddTypeLoc(E->getTypeSourceInfo());
2560}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002561void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 EnqueueChildren(E);
2563 if (E->isTypeOperand())
2564 AddTypeLoc(E->getTypeOperandSourceInfo());
2565}
2566
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002567void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2568 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 EnqueueChildren(E);
2570 AddTypeLoc(E->getTypeSourceInfo());
2571}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002572void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 EnqueueChildren(E);
2574 if (E->isTypeOperand())
2575 AddTypeLoc(E->getTypeOperandSourceInfo());
2576}
2577
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002578void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 EnqueueChildren(S);
2580 AddDecl(S->getExceptionDecl());
2581}
2582
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002583void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002584 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002585 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002586 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002587}
2588
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002589void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002590 if (DR->hasExplicitTemplateArgs())
2591 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 WL.push_back(DeclRefExprParts(DR, Parent));
2593}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002594void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2595 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002596 if (E->hasExplicitTemplateArgs())
2597 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 AddDeclarationNameInfo(E);
2599 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2600}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002601void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 unsigned size = WL.size();
2603 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002604 for (const auto *D : S->decls()) {
2605 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 isFirst = false;
2607 }
2608 if (size == WL.size())
2609 return;
2610 // Now reverse the entries we just added. This will match the DFS
2611 // ordering performed by the worklist.
2612 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2613 std::reverse(I, E);
2614}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002615void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002617 for (const DesignatedInitExpr::Designator &D :
2618 llvm::reverse(E->designators())) {
2619 if (D.isFieldDesignator()) {
2620 if (FieldDecl *Field = D.getField())
2621 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 continue;
2623 }
David Majnemerf7e36092016-06-23 00:15:04 +00002624 if (D.isArrayDesignator()) {
2625 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 continue;
2627 }
David Majnemerf7e36092016-06-23 00:15:04 +00002628 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2629 AddStmt(E->getArrayRangeEnd(D));
2630 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 }
2632}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002633void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 EnqueueChildren(E);
2635 AddTypeLoc(E->getTypeInfoAsWritten());
2636}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002637void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 AddStmt(FS->getBody());
2639 AddStmt(FS->getInc());
2640 AddStmt(FS->getCond());
2641 AddDecl(FS->getConditionVariable());
2642 AddStmt(FS->getInit());
2643}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002644void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2646}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002647void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 AddStmt(If->getElse());
2649 AddStmt(If->getThen());
2650 AddStmt(If->getCond());
2651 AddDecl(If->getConditionVariable());
2652}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002653void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 // We care about the syntactic form of the initializer list, only.
2655 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2656 IE = Syntactic;
2657 EnqueueChildren(IE);
2658}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002659void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 WL.push_back(MemberExprParts(M, Parent));
2661
2662 // If the base of the member access expression is an implicit 'this', don't
2663 // visit it.
2664 // FIXME: If we ever want to show these implicit accesses, this will be
2665 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002666 if (M->isImplicitAccess())
2667 return;
2668
2669 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002670 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002671 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2672 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2673 if (FD->isAnonymousStructOrUnion()) {
2674 AddStmt(SubME->getBase());
2675 return;
2676 }
2677 }
2678 }
2679
2680 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002681}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002682void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 AddTypeLoc(E->getEncodedTypeSourceInfo());
2684}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002685void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 EnqueueChildren(M);
2687 AddTypeLoc(M->getClassReceiverTypeInfo());
2688}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002689void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 // Visit the components of the offsetof expression.
2691 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 const OffsetOfNode &Node = E->getComponent(I-1);
2693 switch (Node.getKind()) {
2694 case OffsetOfNode::Array:
2695 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2696 break;
2697 case OffsetOfNode::Field:
2698 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2699 break;
2700 case OffsetOfNode::Identifier:
2701 case OffsetOfNode::Base:
2702 continue;
2703 }
2704 }
2705 // Visit the type into which we're computing the offset.
2706 AddTypeLoc(E->getTypeSourceInfo());
2707}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002708void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002709 if (E->hasExplicitTemplateArgs())
2710 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 WL.push_back(OverloadExprParts(E, Parent));
2712}
2713void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002714 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 EnqueueChildren(E);
2716 if (E->isArgumentType())
2717 AddTypeLoc(E->getArgumentTypeInfo());
2718}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002719void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 EnqueueChildren(S);
2721}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002722void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 AddStmt(S->getBody());
2724 AddStmt(S->getCond());
2725 AddDecl(S->getConditionVariable());
2726}
2727
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002728void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 AddStmt(W->getBody());
2730 AddStmt(W->getCond());
2731 AddDecl(W->getConditionVariable());
2732}
2733
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002734void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 for (unsigned I = E->getNumArgs(); I > 0; --I)
2736 AddTypeLoc(E->getArg(I-1));
2737}
2738
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002739void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 AddTypeLoc(E->getQueriedTypeSourceInfo());
2741}
2742
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002743void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 EnqueueChildren(E);
2745}
2746
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002747void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 VisitOverloadExpr(U);
2749 if (!U->isImplicitAccess())
2750 AddStmt(U->getBase());
2751}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002752void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 AddStmt(E->getSubExpr());
2754 AddTypeLoc(E->getWrittenTypeInfo());
2755}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002756void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002757 WL.push_back(SizeOfPackExprParts(E, Parent));
2758}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002759void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 // If the opaque value has a source expression, just transparently
2761 // visit that. This is useful for (e.g.) pseudo-object expressions.
2762 if (Expr *SourceExpr = E->getSourceExpr())
2763 return Visit(SourceExpr);
2764}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002765void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 AddStmt(E->getBody());
2767 WL.push_back(LambdaExprParts(E, Parent));
2768}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002769void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 // Treat the expression like its syntactic form.
2771 Visit(E->getSyntacticForm());
2772}
2773
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002774void EnqueueVisitor::VisitOMPExecutableDirective(
2775 const OMPExecutableDirective *D) {
2776 EnqueueChildren(D);
2777 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2778 E = D->clauses().end();
2779 I != E; ++I)
2780 EnqueueChildren(*I);
2781}
2782
Alexander Musman3aaab662014-08-19 11:27:13 +00002783void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2784 VisitOMPExecutableDirective(D);
2785}
2786
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002787void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2788 VisitOMPExecutableDirective(D);
2789}
2790
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002791void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002792 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002793}
2794
Alexey Bataevf29276e2014-06-18 04:14:57 +00002795void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002796 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002797}
2798
Alexander Musmanf82886e2014-09-18 05:12:34 +00002799void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2800 VisitOMPLoopDirective(D);
2801}
2802
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002803void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2804 VisitOMPExecutableDirective(D);
2805}
2806
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002807void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2808 VisitOMPExecutableDirective(D);
2809}
2810
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002811void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2812 VisitOMPExecutableDirective(D);
2813}
2814
Alexander Musman80c22892014-07-17 08:54:58 +00002815void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2816 VisitOMPExecutableDirective(D);
2817}
2818
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002819void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2820 VisitOMPExecutableDirective(D);
2821 AddDeclarationNameInfo(D);
2822}
2823
Alexey Bataev4acb8592014-07-07 13:01:15 +00002824void
2825EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002826 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002827}
2828
Alexander Musmane4e893b2014-09-23 09:33:00 +00002829void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2830 const OMPParallelForSimdDirective *D) {
2831 VisitOMPLoopDirective(D);
2832}
2833
cchen47d60942019-12-05 13:43:48 -05002834void EnqueueVisitor::VisitOMPParallelMasterDirective(
2835 const OMPParallelMasterDirective *D) {
2836 VisitOMPExecutableDirective(D);
2837}
2838
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002839void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2840 const OMPParallelSectionsDirective *D) {
2841 VisitOMPExecutableDirective(D);
2842}
2843
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002844void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2845 VisitOMPExecutableDirective(D);
2846}
2847
Alexey Bataev68446b72014-07-18 07:47:19 +00002848void
2849EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2850 VisitOMPExecutableDirective(D);
2851}
2852
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002853void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2854 VisitOMPExecutableDirective(D);
2855}
2856
Alexey Bataev2df347a2014-07-18 10:17:07 +00002857void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2858 VisitOMPExecutableDirective(D);
2859}
2860
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002861void EnqueueVisitor::VisitOMPTaskgroupDirective(
2862 const OMPTaskgroupDirective *D) {
2863 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002864 if (const Expr *E = D->getReductionRef())
2865 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002866}
2867
Alexey Bataev6125da92014-07-21 11:26:11 +00002868void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2869 VisitOMPExecutableDirective(D);
2870}
2871
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002872void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2873 VisitOMPExecutableDirective(D);
2874}
2875
Alexey Bataev0162e452014-07-22 10:10:35 +00002876void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2877 VisitOMPExecutableDirective(D);
2878}
2879
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002880void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2881 VisitOMPExecutableDirective(D);
2882}
2883
Michael Wong65f367f2015-07-21 13:44:28 +00002884void EnqueueVisitor::VisitOMPTargetDataDirective(const
2885 OMPTargetDataDirective *D) {
2886 VisitOMPExecutableDirective(D);
2887}
2888
Samuel Antaodf67fc42016-01-19 19:15:56 +00002889void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2890 const OMPTargetEnterDataDirective *D) {
2891 VisitOMPExecutableDirective(D);
2892}
2893
Samuel Antao72590762016-01-19 20:04:50 +00002894void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2895 const OMPTargetExitDataDirective *D) {
2896 VisitOMPExecutableDirective(D);
2897}
2898
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002899void EnqueueVisitor::VisitOMPTargetParallelDirective(
2900 const OMPTargetParallelDirective *D) {
2901 VisitOMPExecutableDirective(D);
2902}
2903
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002904void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2905 const OMPTargetParallelForDirective *D) {
2906 VisitOMPLoopDirective(D);
2907}
2908
Alexey Bataev13314bf2014-10-09 04:18:56 +00002909void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2910 VisitOMPExecutableDirective(D);
2911}
2912
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002913void EnqueueVisitor::VisitOMPCancellationPointDirective(
2914 const OMPCancellationPointDirective *D) {
2915 VisitOMPExecutableDirective(D);
2916}
2917
Alexey Bataev80909872015-07-02 11:25:17 +00002918void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2919 VisitOMPExecutableDirective(D);
2920}
2921
Alexey Bataev49f6e782015-12-01 04:18:41 +00002922void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2923 VisitOMPLoopDirective(D);
2924}
2925
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002926void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2927 const OMPTaskLoopSimdDirective *D) {
2928 VisitOMPLoopDirective(D);
2929}
2930
Alexey Bataev60e51c42019-10-10 20:13:02 +00002931void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2932 const OMPMasterTaskLoopDirective *D) {
2933 VisitOMPLoopDirective(D);
2934}
2935
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002936void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2937 const OMPMasterTaskLoopSimdDirective *D) {
2938 VisitOMPLoopDirective(D);
2939}
2940
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002941void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2942 const OMPParallelMasterTaskLoopDirective *D) {
2943 VisitOMPLoopDirective(D);
2944}
2945
Alexey Bataev14a388f2019-10-25 10:27:13 -04002946void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
2947 const OMPParallelMasterTaskLoopSimdDirective *D) {
2948 VisitOMPLoopDirective(D);
2949}
2950
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002951void EnqueueVisitor::VisitOMPDistributeDirective(
2952 const OMPDistributeDirective *D) {
2953 VisitOMPLoopDirective(D);
2954}
2955
Carlo Bertolli9925f152016-06-27 14:55:37 +00002956void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2957 const OMPDistributeParallelForDirective *D) {
2958 VisitOMPLoopDirective(D);
2959}
2960
Kelvin Li4a39add2016-07-05 05:00:15 +00002961void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2962 const OMPDistributeParallelForSimdDirective *D) {
2963 VisitOMPLoopDirective(D);
2964}
2965
Kelvin Li787f3fc2016-07-06 04:45:38 +00002966void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2967 const OMPDistributeSimdDirective *D) {
2968 VisitOMPLoopDirective(D);
2969}
2970
Kelvin Lia579b912016-07-14 02:54:56 +00002971void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2972 const OMPTargetParallelForSimdDirective *D) {
2973 VisitOMPLoopDirective(D);
2974}
2975
Kelvin Li986330c2016-07-20 22:57:10 +00002976void EnqueueVisitor::VisitOMPTargetSimdDirective(
2977 const OMPTargetSimdDirective *D) {
2978 VisitOMPLoopDirective(D);
2979}
2980
Kelvin Li02532872016-08-05 14:37:37 +00002981void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2982 const OMPTeamsDistributeDirective *D) {
2983 VisitOMPLoopDirective(D);
2984}
2985
Kelvin Li4e325f72016-10-25 12:50:55 +00002986void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2987 const OMPTeamsDistributeSimdDirective *D) {
2988 VisitOMPLoopDirective(D);
2989}
2990
Kelvin Li579e41c2016-11-30 23:51:03 +00002991void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2992 const OMPTeamsDistributeParallelForSimdDirective *D) {
2993 VisitOMPLoopDirective(D);
2994}
2995
Kelvin Li7ade93f2016-12-09 03:24:30 +00002996void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2997 const OMPTeamsDistributeParallelForDirective *D) {
2998 VisitOMPLoopDirective(D);
2999}
3000
Kelvin Libf594a52016-12-17 05:48:59 +00003001void EnqueueVisitor::VisitOMPTargetTeamsDirective(
3002 const OMPTargetTeamsDirective *D) {
3003 VisitOMPExecutableDirective(D);
3004}
3005
Kelvin Li83c451e2016-12-25 04:52:54 +00003006void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3007 const OMPTargetTeamsDistributeDirective *D) {
3008 VisitOMPLoopDirective(D);
3009}
3010
Kelvin Li80e8f562016-12-29 22:16:30 +00003011void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3012 const OMPTargetTeamsDistributeParallelForDirective *D) {
3013 VisitOMPLoopDirective(D);
3014}
3015
Kelvin Li1851df52017-01-03 05:23:48 +00003016void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3017 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3018 VisitOMPLoopDirective(D);
3019}
3020
Kelvin Lida681182017-01-10 18:08:18 +00003021void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3022 const OMPTargetTeamsDistributeSimdDirective *D) {
3023 VisitOMPLoopDirective(D);
3024}
3025
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003026void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
3028}
3029
3030bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3031 if (RegionOfInterest.isValid()) {
3032 SourceRange Range = getRawCursorExtent(C);
3033 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3034 return false;
3035 }
3036 return true;
3037}
3038
3039bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3040 while (!WL.empty()) {
3041 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003042 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003043
3044 // Set the Parent field, then back to its old value once we're done.
3045 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3046
3047 switch (LI.getKind()) {
3048 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003049 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 if (!D)
3051 continue;
3052
3053 // For now, perform default visitation for Decls.
3054 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3055 cast<DeclVisit>(&LI)->isFirst())))
3056 return true;
3057
3058 continue;
3059 }
3060 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003061 for (const TemplateArgumentLoc &Arg :
3062 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3063 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 return true;
3065 }
3066 continue;
3067 }
3068 case VisitorJob::TypeLocVisitKind: {
3069 // Perform default visitation for TypeLocs.
3070 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3071 return true;
3072 continue;
3073 }
3074 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003075 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 if (LabelStmt *stmt = LS->getStmt()) {
3077 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3078 TU))) {
3079 return true;
3080 }
3081 }
3082 continue;
3083 }
3084
3085 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3086 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3087 if (VisitNestedNameSpecifierLoc(V->get()))
3088 return true;
3089 continue;
3090 }
3091
3092 case VisitorJob::DeclarationNameInfoVisitKind: {
3093 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3094 ->get()))
3095 return true;
3096 continue;
3097 }
3098 case VisitorJob::MemberRefVisitKind: {
3099 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3100 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3101 return true;
3102 continue;
3103 }
3104 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003105 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 if (!S)
3107 continue;
3108
3109 // Update the current cursor.
3110 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3111 if (!IsInRegionOfInterest(Cursor))
3112 continue;
3113 switch (Visitor(Cursor, Parent, ClientData)) {
3114 case CXChildVisit_Break: return true;
3115 case CXChildVisit_Continue: break;
3116 case CXChildVisit_Recurse:
3117 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003118 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 EnqueueWorkList(WL, S);
3120 break;
3121 }
3122 continue;
3123 }
3124 case VisitorJob::MemberExprPartsKind: {
3125 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003126 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003127
3128 // Visit the nested-name-specifier
3129 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3130 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3131 return true;
3132
3133 // Visit the declaration name.
3134 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3135 return true;
3136
3137 // Visit the explicitly-specified template arguments, if any.
3138 if (M->hasExplicitTemplateArgs()) {
3139 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3140 *ArgEnd = Arg + M->getNumTemplateArgs();
3141 Arg != ArgEnd; ++Arg) {
3142 if (VisitTemplateArgumentLoc(*Arg))
3143 return true;
3144 }
3145 }
3146 continue;
3147 }
3148 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003149 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 // Visit nested-name-specifier, if present.
3151 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3152 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3153 return true;
3154 // Visit declaration name.
3155 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3156 return true;
3157 continue;
3158 }
3159 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003160 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 // Visit the nested-name-specifier.
3162 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3163 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3164 return true;
3165 // Visit the declaration name.
3166 if (VisitDeclarationNameInfo(O->getNameInfo()))
3167 return true;
3168 // Visit the overloaded declaration reference.
3169 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3170 return true;
3171 continue;
3172 }
3173 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003174 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003175 NamedDecl *Pack = E->getPack();
3176 if (isa<TemplateTypeParmDecl>(Pack)) {
3177 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3178 E->getPackLoc(), TU)))
3179 return true;
3180
3181 continue;
3182 }
3183
3184 if (isa<TemplateTemplateParmDecl>(Pack)) {
3185 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3186 E->getPackLoc(), TU)))
3187 return true;
3188
3189 continue;
3190 }
3191
3192 // Non-type template parameter packs and function parameter packs are
3193 // treated like DeclRefExpr cursors.
3194 continue;
3195 }
3196
3197 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003198 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003199 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003200 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3201 CEnd = E->explicit_capture_end();
3202 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003203 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003205
Guy Benyei11169dd2012-12-18 14:30:41 +00003206 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3207 C->getLocation(),
3208 TU)))
3209 return true;
3210 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003211 // Visit init captures
3212 for (auto InitExpr : E->capture_inits()) {
3213 if (Visit(InitExpr))
3214 return true;
3215 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003216
Haojian Wuef87c262018-12-18 15:29:12 +00003217 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003219 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3220 if (E->hasExplicitParameters()) {
3221 // Visit parameters.
3222 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3223 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003224 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003225 }
3226 if (E->hasExplicitResultType()) {
3227 // Visit result type.
3228 if (Visit(Proto.getReturnLoc()))
3229 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003230 }
3231 }
3232 break;
3233 }
3234
3235 case VisitorJob::PostChildrenVisitKind:
3236 if (PostChildrenVisitor(Parent, ClientData))
3237 return true;
3238 break;
3239 }
3240 }
3241 return false;
3242}
3243
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003244bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003245 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003246 if (!WorkListFreeList.empty()) {
3247 WL = WorkListFreeList.back();
3248 WL->clear();
3249 WorkListFreeList.pop_back();
3250 }
3251 else {
3252 WL = new VisitorWorkList();
3253 WorkListCache.push_back(WL);
3254 }
3255 EnqueueWorkList(*WL, S);
3256 bool result = RunVisitorWorkList(*WL);
3257 WorkListFreeList.push_back(WL);
3258 return result;
3259}
3260
3261namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003262typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003263RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3264 const DeclarationNameInfo &NI, SourceRange QLoc,
3265 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003266 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3267 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3268 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3269
3270 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3271
3272 RefNamePieces Pieces;
3273
3274 if (WantQualifier && QLoc.isValid())
3275 Pieces.push_back(QLoc);
3276
3277 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3278 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003279
3280 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3281 Pieces.push_back(*TemplateArgsLoc);
3282
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 if (Kind == DeclarationName::CXXOperatorName) {
3284 Pieces.push_back(SourceLocation::getFromRawEncoding(
3285 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3286 Pieces.push_back(SourceLocation::getFromRawEncoding(
3287 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3288 }
3289
3290 if (WantSinglePiece) {
3291 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3292 Pieces.clear();
3293 Pieces.push_back(R);
3294 }
3295
3296 return Pieces;
3297}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003298}
Guy Benyei11169dd2012-12-18 14:30:41 +00003299
3300//===----------------------------------------------------------------------===//
3301// Misc. API hooks.
3302//===----------------------------------------------------------------------===//
3303
Chandler Carruth66660742014-06-27 16:37:27 +00003304namespace {
3305struct RegisterFatalErrorHandler {
3306 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003307 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003308 }
3309};
3310}
3311
3312static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3313
Guy Benyei11169dd2012-12-18 14:30:41 +00003314CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3315 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 // We use crash recovery to make some of our APIs more reliable, implicitly
3317 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003318 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3319 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003320
Chandler Carruth66660742014-06-27 16:37:27 +00003321 // Look through the managed static to trigger construction of the managed
3322 // static which registers our fatal error handler. This ensures it is only
3323 // registered once.
3324 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003325
Adrian Prantlbc068582015-07-08 01:00:30 +00003326 // Initialize targets for clang module support.
3327 llvm::InitializeAllTargets();
3328 llvm::InitializeAllTargetMCs();
3329 llvm::InitializeAllAsmPrinters();
3330 llvm::InitializeAllAsmParsers();
3331
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003332 CIndexer *CIdxr = new CIndexer();
3333
Guy Benyei11169dd2012-12-18 14:30:41 +00003334 if (excludeDeclarationsFromPCH)
3335 CIdxr->setOnlyLocalDecls();
3336 if (displayDiagnostics)
3337 CIdxr->setDisplayDiagnostics();
3338
3339 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3340 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3341 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3342 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3343 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3344 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3345
3346 return CIdxr;
3347}
3348
3349void clang_disposeIndex(CXIndex CIdx) {
3350 if (CIdx)
3351 delete static_cast<CIndexer *>(CIdx);
3352}
3353
3354void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3355 if (CIdx)
3356 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3357}
3358
3359unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3360 if (CIdx)
3361 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3362 return 0;
3363}
3364
Alex Lorenz08615792017-12-04 21:56:36 +00003365void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3366 const char *Path) {
3367 if (CIdx)
3368 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3369}
3370
Guy Benyei11169dd2012-12-18 14:30:41 +00003371void clang_toggleCrashRecovery(unsigned isEnabled) {
3372 if (isEnabled)
3373 llvm::CrashRecoveryContext::Enable();
3374 else
3375 llvm::CrashRecoveryContext::Disable();
3376}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003377
Guy Benyei11169dd2012-12-18 14:30:41 +00003378CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3379 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003380 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003381 enum CXErrorCode Result =
3382 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003383 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003384 assert((TU && Result == CXError_Success) ||
3385 (!TU && Result != CXError_Success));
3386 return TU;
3387}
3388
3389enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3390 const char *ast_filename,
3391 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003392 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003393 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003394
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003395 if (!CIdx || !ast_filename || !out_TU)
3396 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003397
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003398 LOG_FUNC_SECTION {
3399 *Log << ast_filename;
3400 }
3401
Guy Benyei11169dd2012-12-18 14:30:41 +00003402 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3403 FileSystemOptions FileSystemOpts;
3404
Justin Bognerd512c1e2014-10-15 00:33:06 +00003405 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3406 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003407 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003408 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3409 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003410 FileSystemOpts, /*UseDebugInfo=*/false,
3411 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003412 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003413 /*AllowPCHWithCompilerErrors=*/true,
3414 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003415 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003416 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003417}
3418
3419unsigned clang_defaultEditingTranslationUnitOptions() {
3420 return CXTranslationUnit_PrecompiledPreamble |
3421 CXTranslationUnit_CacheCompletionResults;
3422}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003423
Guy Benyei11169dd2012-12-18 14:30:41 +00003424CXTranslationUnit
3425clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3426 const char *source_filename,
3427 int num_command_line_args,
3428 const char * const *command_line_args,
3429 unsigned num_unsaved_files,
3430 struct CXUnsavedFile *unsaved_files) {
3431 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3432 return clang_parseTranslationUnit(CIdx, source_filename,
3433 command_line_args, num_command_line_args,
3434 unsaved_files, num_unsaved_files,
3435 Options);
3436}
3437
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003438static CXErrorCode
3439clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3440 const char *const *command_line_args,
3441 int num_command_line_args,
3442 ArrayRef<CXUnsavedFile> unsaved_files,
3443 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003444 // Set up the initial return values.
3445 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003446 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003447
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003448 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003449 if (!CIdx || !out_TU)
3450 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003451
Guy Benyei11169dd2012-12-18 14:30:41 +00003452 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3453
3454 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3455 setThreadBackgroundPriority();
3456
3457 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003458 bool CreatePreambleOnFirstParse =
3459 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 // FIXME: Add a flag for modules.
3461 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003462 = (options & (CXTranslationUnit_Incomplete |
3463 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003464 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003465 = options & CXTranslationUnit_CacheCompletionResults;
3466 bool IncludeBriefCommentsInCodeCompletion
3467 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003468 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3469 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003470 bool RetainExcludedCB = options &
3471 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003472 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3473 if (options & CXTranslationUnit_SkipFunctionBodies) {
3474 SkipFunctionBodies =
3475 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3476 ? SkipFunctionBodiesScope::Preamble
3477 : SkipFunctionBodiesScope::PreambleAndMainFile;
3478 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003479
3480 // Configure the diagnostics.
3481 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003482 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003483
Manuel Klimek016c0242016-03-01 10:56:19 +00003484 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003485 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003486
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003487 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3488 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3489 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3490
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 // Recover resources if we crash before exiting this function.
3492 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3493 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003494 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003495
Ahmed Charlesb8984322014-03-07 20:03:18 +00003496 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3497 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003498
3499 // Recover resources if we crash before exiting this function.
3500 llvm::CrashRecoveryContextCleanupRegistrar<
3501 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3502
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003503 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003504 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003505 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003506 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003507 }
3508
Ahmed Charlesb8984322014-03-07 20:03:18 +00003509 std::unique_ptr<std::vector<const char *>> Args(
3510 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003511
3512 // Recover resources if we crash before exiting this method.
3513 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3514 ArgsCleanup(Args.get());
3515
3516 // Since the Clang C library is primarily used by batch tools dealing with
3517 // (often very broken) source code, where spell-checking can have a
3518 // significant negative impact on performance (particularly when
3519 // precompiled headers are involved), we disable it by default.
3520 // Only do this if we haven't found a spell-checking-related argument.
3521 bool FoundSpellCheckingArgument = false;
3522 for (int I = 0; I != num_command_line_args; ++I) {
3523 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3524 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3525 FoundSpellCheckingArgument = true;
3526 break;
3527 }
3528 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003529 Args->insert(Args->end(), command_line_args,
3530 command_line_args + num_command_line_args);
3531
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003532 if (!FoundSpellCheckingArgument)
3533 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3534
Guy Benyei11169dd2012-12-18 14:30:41 +00003535 // The 'source_filename' argument is optional. If the caller does not
3536 // specify it then it is assumed that the source file is specified
3537 // in the actual argument list.
3538 // Put the source file after command_line_args otherwise if '-x' flag is
3539 // present it will be unused.
3540 if (source_filename)
3541 Args->push_back(source_filename);
3542
3543 // Do we need the detailed preprocessing record?
3544 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3545 Args->push_back("-Xclang");
3546 Args->push_back("-detailed-preprocessing-record");
3547 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003548
3549 // Suppress any editor placeholder diagnostics.
3550 Args->push_back("-fallow-editor-placeholders");
3551
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003553 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003554 // Unless the user specified that they want the preamble on the first parse
3555 // set it up to be created on the first reparse. This makes the first parse
3556 // faster, trading for a slower (first) reparse.
3557 unsigned PrecompilePreambleAfterNParses =
3558 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003559
Alex Lorenz08615792017-12-04 21:56:36 +00003560 LibclangInvocationReporter InvocationReporter(
3561 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003562 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3563 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003564 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003565 Args->data(), Args->data() + Args->size(),
3566 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003567 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003568 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003569 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3570 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003571 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003572 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003573 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3574 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003575
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003576 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003577 if (!Unit && !ErrUnit)
3578 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003579
Guy Benyei11169dd2012-12-18 14:30:41 +00003580 if (NumErrors != Diags->getClient()->getNumErrors()) {
3581 // Make sure to check that 'Unit' is non-NULL.
3582 if (CXXIdx->getDisplayDiagnostics())
3583 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3584 }
3585
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003586 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3587 return CXError_ASTReadError;
3588
David Blaikieea4395e2017-01-06 19:49:01 +00003589 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003590 if (CXTranslationUnitImpl *TU = *out_TU) {
3591 TU->ParsingOptions = options;
3592 TU->Arguments.reserve(Args->size());
3593 for (const char *Arg : *Args)
3594 TU->Arguments.push_back(Arg);
3595 return CXError_Success;
3596 }
3597 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003598}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003599
3600CXTranslationUnit
3601clang_parseTranslationUnit(CXIndex CIdx,
3602 const char *source_filename,
3603 const char *const *command_line_args,
3604 int num_command_line_args,
3605 struct CXUnsavedFile *unsaved_files,
3606 unsigned num_unsaved_files,
3607 unsigned options) {
3608 CXTranslationUnit TU;
3609 enum CXErrorCode Result = clang_parseTranslationUnit2(
3610 CIdx, source_filename, command_line_args, num_command_line_args,
3611 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003612 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003613 assert((TU && Result == CXError_Success) ||
3614 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003615 return TU;
3616}
3617
3618enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003619 CXIndex CIdx, const char *source_filename,
3620 const char *const *command_line_args, int num_command_line_args,
3621 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3622 unsigned options, CXTranslationUnit *out_TU) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003623 noteBottomOfStack();
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003624 SmallVector<const char *, 4> Args;
3625 Args.push_back("clang");
3626 Args.append(command_line_args, command_line_args + num_command_line_args);
3627 return clang_parseTranslationUnit2FullArgv(
3628 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3629 num_unsaved_files, options, out_TU);
3630}
3631
3632enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3633 CXIndex CIdx, const char *source_filename,
3634 const char *const *command_line_args, int num_command_line_args,
3635 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3636 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003637 LOG_FUNC_SECTION {
3638 *Log << source_filename << ": ";
3639 for (int i = 0; i != num_command_line_args; ++i)
3640 *Log << command_line_args[i] << " ";
3641 }
3642
Alp Toker9d85b182014-07-07 01:23:14 +00003643 if (num_unsaved_files && !unsaved_files)
3644 return CXError_InvalidArguments;
3645
Alp Toker5c532982014-07-07 22:42:03 +00003646 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003647 auto ParseTranslationUnitImpl = [=, &result] {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003648 noteBottomOfStack();
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003649 result = clang_parseTranslationUnit_Impl(
3650 CIdx, source_filename, command_line_args, num_command_line_args,
3651 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3652 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003653
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 llvm::CrashRecoveryContext CRC;
3655
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003656 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003657 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3658 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3659 fprintf(stderr, " 'command_line_args' : [");
3660 for (int i = 0; i != num_command_line_args; ++i) {
3661 if (i)
3662 fprintf(stderr, ", ");
3663 fprintf(stderr, "'%s'", command_line_args[i]);
3664 }
3665 fprintf(stderr, "],\n");
3666 fprintf(stderr, " 'unsaved_files' : [");
3667 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3668 if (i)
3669 fprintf(stderr, ", ");
3670 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3671 unsaved_files[i].Length);
3672 }
3673 fprintf(stderr, "],\n");
3674 fprintf(stderr, " 'options' : %d,\n", options);
3675 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003676
3677 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003678 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003679 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003680 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003681 }
Alp Toker5c532982014-07-07 22:42:03 +00003682
3683 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003684}
3685
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003686CXString clang_Type_getObjCEncoding(CXType CT) {
3687 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3688 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3689 std::string encoding;
3690 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3691 encoding);
3692
3693 return cxstring::createDup(encoding);
3694}
3695
3696static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3697 if (C.kind == CXCursor_MacroDefinition) {
3698 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3699 return MDR->getName();
3700 } else if (C.kind == CXCursor_MacroExpansion) {
3701 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3702 return ME.getName();
3703 }
3704 return nullptr;
3705}
3706
3707unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3708 const IdentifierInfo *II = getMacroIdentifier(C);
3709 if (!II) {
3710 return false;
3711 }
3712 ASTUnit *ASTU = getCursorASTUnit(C);
3713 Preprocessor &PP = ASTU->getPreprocessor();
3714 if (const MacroInfo *MI = PP.getMacroInfo(II))
3715 return MI->isFunctionLike();
3716 return false;
3717}
3718
3719unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3720 const IdentifierInfo *II = getMacroIdentifier(C);
3721 if (!II) {
3722 return false;
3723 }
3724 ASTUnit *ASTU = getCursorASTUnit(C);
3725 Preprocessor &PP = ASTU->getPreprocessor();
3726 if (const MacroInfo *MI = PP.getMacroInfo(II))
3727 return MI->isBuiltinMacro();
3728 return false;
3729}
3730
3731unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3732 const Decl *D = getCursorDecl(C);
3733 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3734 if (!FD) {
3735 return false;
3736 }
3737 return FD->isInlined();
3738}
3739
3740static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3741 if (callExpr->getNumArgs() != 1) {
3742 return nullptr;
3743 }
3744
3745 StringLiteral *S = nullptr;
3746 auto *arg = callExpr->getArg(0);
3747 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3748 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3749 auto *subExpr = I->getSubExprAsWritten();
3750
3751 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3752 return nullptr;
3753 }
3754
3755 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3756 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3757 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3758 } else {
3759 return nullptr;
3760 }
3761 return S;
3762}
3763
David Blaikie59272572016-04-13 18:23:33 +00003764struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003765 CXEvalResultKind EvalType;
3766 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003767 unsigned long long unsignedVal;
3768 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003769 double floatVal;
3770 char *stringVal;
3771 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003772 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003773 ~ExprEvalResult() {
3774 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3775 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003776 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003777 }
3778 }
3779};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003780
3781void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003782 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003783}
3784
3785CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3786 if (!E) {
3787 return CXEval_UnExposed;
3788 }
3789 return ((ExprEvalResult *)E)->EvalType;
3790}
3791
3792int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003793 return clang_EvalResult_getAsLongLong(E);
3794}
3795
3796long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003797 if (!E) {
3798 return 0;
3799 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003800 ExprEvalResult *Result = (ExprEvalResult*)E;
3801 if (Result->IsUnsignedInt)
3802 return Result->EvalData.unsignedVal;
3803 return Result->EvalData.intVal;
3804}
3805
3806unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3807 return ((ExprEvalResult *)E)->IsUnsignedInt;
3808}
3809
3810unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3811 if (!E) {
3812 return 0;
3813 }
3814
3815 ExprEvalResult *Result = (ExprEvalResult*)E;
3816 if (Result->IsUnsignedInt)
3817 return Result->EvalData.unsignedVal;
3818 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003819}
3820
3821double clang_EvalResult_getAsDouble(CXEvalResult E) {
3822 if (!E) {
3823 return 0;
3824 }
3825 return ((ExprEvalResult *)E)->EvalData.floatVal;
3826}
3827
3828const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3829 if (!E) {
3830 return nullptr;
3831 }
3832 return ((ExprEvalResult *)E)->EvalData.stringVal;
3833}
3834
3835static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3836 Expr::EvalResult ER;
3837 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003838 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003839 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003840
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003841 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003842 if (expr->isValueDependent())
3843 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003844 if (!expr->EvaluateAsRValue(ER, ctx))
3845 return nullptr;
3846
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003847 QualType rettype;
3848 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003849 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003850 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003851 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003852
David Blaikiebbc00882016-04-13 18:36:19 +00003853 if (ER.Val.isInt()) {
3854 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003855
3856 auto& val = ER.Val.getInt();
3857 if (val.isUnsigned()) {
3858 result->IsUnsignedInt = true;
3859 result->EvalData.unsignedVal = val.getZExtValue();
3860 } else {
3861 result->EvalData.intVal = val.getExtValue();
3862 }
3863
David Blaikiebbc00882016-04-13 18:36:19 +00003864 return result.release();
3865 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003866
David Blaikiebbc00882016-04-13 18:36:19 +00003867 if (ER.Val.isFloat()) {
3868 llvm::SmallVector<char, 100> Buffer;
3869 ER.Val.getFloat().toString(Buffer);
3870 std::string floatStr(Buffer.data(), Buffer.size());
3871 result->EvalType = CXEval_Float;
3872 bool ignored;
3873 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003874 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003875 llvm::APFloat::rmNearestTiesToEven, &ignored);
3876 result->EvalData.floatVal = apFloat.convertToDouble();
3877 return result.release();
3878 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003879
David Blaikiebbc00882016-04-13 18:36:19 +00003880 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3881 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3882 auto *subExpr = I->getSubExprAsWritten();
3883 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3884 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003885 const StringLiteral *StrE = nullptr;
3886 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003887 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003888
3889 if (ObjCExpr) {
3890 StrE = ObjCExpr->getString();
3891 result->EvalType = CXEval_ObjCStrLiteral;
3892 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003893 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003894 result->EvalType = CXEval_StrLiteral;
3895 }
3896
3897 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003898 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003899 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3900 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003901 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003902 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003903 }
3904 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3905 expr->getStmtClass() == Stmt::StringLiteralClass) {
3906 const StringLiteral *StrE = nullptr;
3907 const ObjCStringLiteral *ObjCExpr;
3908 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003909
David Blaikiebbc00882016-04-13 18:36:19 +00003910 if (ObjCExpr) {
3911 StrE = ObjCExpr->getString();
3912 result->EvalType = CXEval_ObjCStrLiteral;
3913 } else {
3914 StrE = cast<StringLiteral>(expr);
3915 result->EvalType = CXEval_StrLiteral;
3916 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003917
David Blaikiebbc00882016-04-13 18:36:19 +00003918 std::string strRef(StrE->getString().str());
3919 result->EvalData.stringVal = new char[strRef.size() + 1];
3920 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3921 result->EvalData.stringVal[strRef.size()] = '\0';
3922 return result.release();
3923 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003924
David Blaikiebbc00882016-04-13 18:36:19 +00003925 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3926 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003927
David Blaikiebbc00882016-04-13 18:36:19 +00003928 rettype = CC->getType();
3929 if (rettype.getAsString() == "CFStringRef" &&
3930 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003931
David Blaikiebbc00882016-04-13 18:36:19 +00003932 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3933 StringLiteral *S = getCFSTR_value(callExpr);
3934 if (S) {
3935 std::string strLiteral(S->getString().str());
3936 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003937
David Blaikiebbc00882016-04-13 18:36:19 +00003938 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3939 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3940 strLiteral.size());
3941 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003942 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003943 }
3944 }
3945
David Blaikiebbc00882016-04-13 18:36:19 +00003946 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3947 callExpr = static_cast<CallExpr *>(expr);
3948 rettype = callExpr->getCallReturnType(ctx);
3949
3950 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3951 return nullptr;
3952
3953 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3954 if (callExpr->getNumArgs() == 1 &&
3955 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3956 return nullptr;
3957 } else if (rettype.getAsString() == "CFStringRef") {
3958
3959 StringLiteral *S = getCFSTR_value(callExpr);
3960 if (S) {
3961 std::string strLiteral(S->getString().str());
3962 result->EvalType = CXEval_CFStr;
3963 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3964 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3965 strLiteral.size());
3966 result->EvalData.stringVal[strLiteral.size()] = '\0';
3967 return result.release();
3968 }
3969 }
3970 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3971 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3972 ValueDecl *V = D->getDecl();
3973 if (V->getKind() == Decl::Function) {
3974 std::string strName = V->getNameAsString();
3975 result->EvalType = CXEval_Other;
3976 result->EvalData.stringVal = new char[strName.size() + 1];
3977 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3978 result->EvalData.stringVal[strName.size()] = '\0';
3979 return result.release();
3980 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003981 }
3982
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003983 return nullptr;
3984}
3985
Alex Lorenz65317e12019-01-08 22:32:51 +00003986static const Expr *evaluateDeclExpr(const Decl *D) {
3987 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003988 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003989 if (auto *Var = dyn_cast<VarDecl>(D))
3990 return Var->getInit();
3991 else if (auto *Field = dyn_cast<FieldDecl>(D))
3992 return Field->getInClassInitializer();
3993 return nullptr;
3994}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003995
Alex Lorenz65317e12019-01-08 22:32:51 +00003996static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3997 assert(CS && "invalid compound statement");
3998 for (auto *bodyIterator : CS->body()) {
3999 if (const auto *E = dyn_cast<Expr>(bodyIterator))
4000 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00004001 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00004002 return nullptr;
4003}
4004
Alex Lorenz65317e12019-01-08 22:32:51 +00004005CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4006 if (const Expr *E =
4007 clang_getCursorKind(C) == CXCursor_CompoundStmt
4008 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
4009 : evaluateDeclExpr(getCursorDecl(C)))
4010 return const_cast<CXEvalResult>(
4011 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4012 return nullptr;
4013}
4014
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004015unsigned clang_Cursor_hasAttrs(CXCursor C) {
4016 const Decl *D = getCursorDecl(C);
4017 if (!D) {
4018 return 0;
4019 }
4020
4021 if (D->hasAttrs()) {
4022 return 1;
4023 }
4024
4025 return 0;
4026}
Guy Benyei11169dd2012-12-18 14:30:41 +00004027unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4028 return CXSaveTranslationUnit_None;
4029}
4030
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004031static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4032 const char *FileName,
4033 unsigned options) {
4034 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004035 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4036 setThreadBackgroundPriority();
4037
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004038 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4039 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004040}
4041
4042int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4043 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004044 LOG_FUNC_SECTION {
4045 *Log << TU << ' ' << FileName;
4046 }
4047
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004048 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004049 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004051 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004052
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004053 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004054 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4055 if (!CXXUnit->hasSema())
4056 return CXSaveError_InvalidTU;
4057
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004058 CXSaveError result;
4059 auto SaveTranslationUnitImpl = [=, &result]() {
4060 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4061 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004062
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004063 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004064 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004065
4066 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4067 PrintLibclangResourceUsage(TU);
4068
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004069 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 }
4071
4072 // We have an AST that has invalid nodes due to compiler errors.
4073 // Use a crash recovery thread for protection.
4074
4075 llvm::CrashRecoveryContext CRC;
4076
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004077 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4079 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4080 fprintf(stderr, " 'options' : %d,\n", options);
4081 fprintf(stderr, "}\n");
4082
4083 return CXSaveError_Unknown;
4084
4085 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4086 PrintLibclangResourceUsage(TU);
4087 }
4088
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004089 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004090}
4091
4092void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4093 if (CTUnit) {
4094 // If the translation unit has been marked as unsafe to free, just discard
4095 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004096 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4097 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 return;
4099
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004100 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004101 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004102 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4103 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004104 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 delete CTUnit;
4106 }
4107}
4108
Erik Verbruggen346066b2017-05-30 14:25:54 +00004109unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4110 if (CTUnit) {
4111 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4112
4113 if (Unit && Unit->isUnsafeToFree())
4114 return false;
4115
4116 Unit->ResetForParse();
4117 return true;
4118 }
4119
4120 return false;
4121}
4122
Guy Benyei11169dd2012-12-18 14:30:41 +00004123unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4124 return CXReparse_None;
4125}
4126
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004127static CXErrorCode
4128clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4129 ArrayRef<CXUnsavedFile> unsaved_files,
4130 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004131 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004132 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004133 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004134 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004135 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004136
4137 // Reset the associated diagnostics.
4138 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004139 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004140
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004141 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004142 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4143 setThreadBackgroundPriority();
4144
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004145 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004147
4148 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4149 new std::vector<ASTUnit::RemappedFile>());
4150
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 // Recover resources if we crash before exiting this function.
4152 llvm::CrashRecoveryContextCleanupRegistrar<
4153 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004154
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004155 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004156 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004157 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004158 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004159 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004160
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004161 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4162 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004163 return CXError_Success;
4164 if (isASTReadError(CXXUnit))
4165 return CXError_ASTReadError;
4166 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004167}
4168
4169int clang_reparseTranslationUnit(CXTranslationUnit TU,
4170 unsigned num_unsaved_files,
4171 struct CXUnsavedFile *unsaved_files,
4172 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004173 LOG_FUNC_SECTION {
4174 *Log << TU;
4175 }
4176
Alp Toker9d85b182014-07-07 01:23:14 +00004177 if (num_unsaved_files && !unsaved_files)
4178 return CXError_InvalidArguments;
4179
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004180 CXErrorCode result;
4181 auto ReparseTranslationUnitImpl = [=, &result]() {
4182 result = clang_reparseTranslationUnit_Impl(
4183 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4184 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004185
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 llvm::CrashRecoveryContext CRC;
4187
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004188 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004189 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004190 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004191 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4193 PrintLibclangResourceUsage(TU);
4194
Alp Toker5c532982014-07-07 22:42:03 +00004195 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004196}
4197
4198
4199CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004200 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004201 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004202 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004203 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004204
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004205 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004206 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004207}
4208
4209CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004210 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004211 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004212 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004213 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004214
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004215 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4217}
4218
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004219CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4220 if (isNotUsableTU(CTUnit)) {
4221 LOG_BAD_TU(CTUnit);
4222 return nullptr;
4223 }
4224
4225 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4226 impl->TranslationUnit = CTUnit;
4227 return impl;
4228}
4229
4230CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4231 if (!TargetInfo)
4232 return cxstring::createEmpty();
4233
4234 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4235 assert(!isNotUsableTU(CTUnit) &&
4236 "Unexpected unusable translation unit in TargetInfo");
4237
4238 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4239 std::string Triple =
4240 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4241 return cxstring::createDup(Triple);
4242}
4243
4244int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4245 if (!TargetInfo)
4246 return -1;
4247
4248 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4249 assert(!isNotUsableTU(CTUnit) &&
4250 "Unexpected unusable translation unit in TargetInfo");
4251
4252 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4253 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4254}
4255
4256void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4257 if (!TargetInfo)
4258 return;
4259
4260 delete TargetInfo;
4261}
4262
Guy Benyei11169dd2012-12-18 14:30:41 +00004263//===----------------------------------------------------------------------===//
4264// CXFile Operations.
4265//===----------------------------------------------------------------------===//
4266
Guy Benyei11169dd2012-12-18 14:30:41 +00004267CXString clang_getFileName(CXFile SFile) {
4268 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004269 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004270
4271 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004272 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004273}
4274
4275time_t clang_getFileTime(CXFile SFile) {
4276 if (!SFile)
4277 return 0;
4278
4279 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4280 return FEnt->getModificationTime();
4281}
4282
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004283CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004284 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004285 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004286 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004287 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004288
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004289 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004290
4291 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004292 auto File = FMgr.getFile(file_name);
4293 if (!File)
4294 return nullptr;
4295 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004296}
4297
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004298const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4299 size_t *size) {
4300 if (isNotUsableTU(TU)) {
4301 LOG_BAD_TU(TU);
4302 return nullptr;
4303 }
4304
4305 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4306 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4307 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004308 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004309 if (Invalid) {
4310 if (size)
4311 *size = 0;
4312 return nullptr;
4313 }
4314 if (size)
4315 *size = buf->getBufferSize();
4316 return buf->getBufferStart();
4317}
4318
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004319unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4320 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004321 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004322 LOG_BAD_TU(TU);
4323 return 0;
4324 }
4325
4326 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 return 0;
4328
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004329 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 FileEntry *FEnt = static_cast<FileEntry *>(file);
4331 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4332 .isFileMultipleIncludeGuarded(FEnt);
4333}
4334
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004335int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4336 if (!file || !outID)
4337 return 1;
4338
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004339 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004340 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4341 outID->data[0] = ID.getDevice();
4342 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004343 outID->data[2] = FEnt->getModificationTime();
4344 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004345}
4346
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004347int clang_File_isEqual(CXFile file1, CXFile file2) {
4348 if (file1 == file2)
4349 return true;
4350
4351 if (!file1 || !file2)
4352 return false;
4353
4354 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4355 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4356 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4357}
4358
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004359CXString clang_File_tryGetRealPathName(CXFile SFile) {
4360 if (!SFile)
4361 return cxstring::createNull();
4362
4363 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4364 return cxstring::createRef(FEnt->tryGetRealPathName());
4365}
4366
Guy Benyei11169dd2012-12-18 14:30:41 +00004367//===----------------------------------------------------------------------===//
4368// CXCursor Operations.
4369//===----------------------------------------------------------------------===//
4370
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004371static const Decl *getDeclFromExpr(const Stmt *E) {
4372 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 return getDeclFromExpr(CE->getSubExpr());
4374
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004375 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004377 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004378 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004379 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004381 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 if (PRE->isExplicitProperty())
4383 return PRE->getExplicitProperty();
4384 // It could be messaging both getter and setter as in:
4385 // ++myobj.myprop;
4386 // in which case prefer to associate the setter since it is less obvious
4387 // from inspecting the source that the setter is going to get called.
4388 if (PRE->isMessagingSetter())
4389 return PRE->getImplicitPropertySetter();
4390 return PRE->getImplicitPropertyGetter();
4391 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004392 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004393 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004394 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004395 if (Expr *Src = OVE->getSourceExpr())
4396 return getDeclFromExpr(Src);
4397
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004398 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004400 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 if (!CE->isElidable())
4402 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004403 if (const CXXInheritedCtorInitExpr *CE =
4404 dyn_cast<CXXInheritedCtorInitExpr>(E))
4405 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004406 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 return OME->getMethodDecl();
4408
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004409 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004411 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4413 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004414 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4416 isa<ParmVarDecl>(SizeOfPack->getPack()))
4417 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004418
4419 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004420}
4421
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004422static SourceLocation getLocationFromExpr(const Expr *E) {
4423 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 return getLocationFromExpr(CE->getSubExpr());
4425
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004426 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004428 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004430 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004432 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004434 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004436 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004438
4439 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004440}
4441
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004442extern "C" {
4443
Guy Benyei11169dd2012-12-18 14:30:41 +00004444unsigned clang_visitChildren(CXCursor parent,
4445 CXCursorVisitor visitor,
4446 CXClientData client_data) {
4447 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4448 /*VisitPreprocessorLast=*/false);
4449 return CursorVis.VisitChildren(parent);
4450}
4451
4452#ifndef __has_feature
4453#define __has_feature(x) 0
4454#endif
4455#if __has_feature(blocks)
4456typedef enum CXChildVisitResult
4457 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4458
4459static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4460 CXClientData client_data) {
4461 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4462 return block(cursor, parent);
4463}
4464#else
4465// If we are compiled with a compiler that doesn't have native blocks support,
4466// define and call the block manually, so the
4467typedef struct _CXChildVisitResult
4468{
4469 void *isa;
4470 int flags;
4471 int reserved;
4472 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4473 CXCursor);
4474} *CXCursorVisitorBlock;
4475
4476static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4477 CXClientData client_data) {
4478 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4479 return block->invoke(block, cursor, parent);
4480}
4481#endif
4482
4483
4484unsigned clang_visitChildrenWithBlock(CXCursor parent,
4485 CXCursorVisitorBlock block) {
4486 return clang_visitChildren(parent, visitWithBlock, block);
4487}
4488
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004489static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004491 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004492
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004493 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004495 if (const ObjCPropertyImplDecl *PropImpl =
4496 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004498 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004499
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004500 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004502 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004503
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004504 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 }
4506
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004507 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004508 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004509
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004510 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4512 // and returns different names. NamedDecl returns the class name and
4513 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004514 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004515
4516 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004517 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004518
4519 SmallString<1024> S;
4520 llvm::raw_svector_ostream os(S);
4521 ND->printName(os);
4522
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004523 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004524}
4525
4526CXString clang_getCursorSpelling(CXCursor C) {
4527 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004528 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004529
4530 if (clang_isReference(C.kind)) {
4531 switch (C.kind) {
4532 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004533 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004534 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 }
4536 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004537 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004538 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 }
4540 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004541 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004543 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 }
4545 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004546 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004547 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 }
4549 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004550 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 assert(Type && "Missing type decl");
4552
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004553 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 getAsString());
4555 }
4556 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004557 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 assert(Template && "Missing template decl");
4559
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004560 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 }
4562
4563 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004564 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 assert(NS && "Missing namespace decl");
4566
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004567 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 }
4569
4570 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004571 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 assert(Field && "Missing member decl");
4573
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004574 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 }
4576
4577 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004578 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 assert(Label && "Missing label");
4580
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004581 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 }
4583
4584 case CXCursor_OverloadedDeclRef: {
4585 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004586 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4587 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004588 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004589 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004591 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004592 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 OverloadedTemplateStorage *Ovl
4594 = Storage.get<OverloadedTemplateStorage*>();
4595 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004596 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004597 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 }
4599
4600 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004601 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 assert(Var && "Missing variable decl");
4603
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004604 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 }
4606
4607 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004608 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 }
4610 }
4611
4612 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004613 const Expr *E = getCursorExpr(C);
4614
4615 if (C.kind == CXCursor_ObjCStringLiteral ||
4616 C.kind == CXCursor_StringLiteral) {
4617 const StringLiteral *SLit;
4618 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4619 SLit = OSL->getString();
4620 } else {
4621 SLit = cast<StringLiteral>(E);
4622 }
4623 SmallString<256> Buf;
4624 llvm::raw_svector_ostream OS(Buf);
4625 SLit->outputString(OS);
4626 return cxstring::createDup(OS.str());
4627 }
4628
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004629 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 if (D)
4631 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004632 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 }
4634
4635 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004636 const Stmt *S = getCursorStmt(C);
4637 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004638 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004639
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004640 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 }
4642
4643 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004644 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 ->getNameStart());
4646
4647 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004648 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 ->getNameStart());
4650
4651 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004652 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004653
4654 if (clang_isDeclaration(C.kind))
4655 return getDeclSpelling(getCursorDecl(C));
4656
4657 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004658 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004659 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 }
4661
4662 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004663 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004664 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 }
4666
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004667 if (C.kind == CXCursor_PackedAttr) {
4668 return cxstring::createRef("packed");
4669 }
4670
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004671 if (C.kind == CXCursor_VisibilityAttr) {
4672 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4673 switch (AA->getVisibility()) {
4674 case VisibilityAttr::VisibilityType::Default:
4675 return cxstring::createRef("default");
4676 case VisibilityAttr::VisibilityType::Hidden:
4677 return cxstring::createRef("hidden");
4678 case VisibilityAttr::VisibilityType::Protected:
4679 return cxstring::createRef("protected");
4680 }
4681 llvm_unreachable("unknown visibility type");
4682 }
4683
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004684 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004685}
4686
4687CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4688 unsigned pieceIndex,
4689 unsigned options) {
4690 if (clang_Cursor_isNull(C))
4691 return clang_getNullRange();
4692
4693 ASTContext &Ctx = getCursorContext(C);
4694
4695 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004696 const Stmt *S = getCursorStmt(C);
4697 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 if (pieceIndex > 0)
4699 return clang_getNullRange();
4700 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4701 }
4702
4703 return clang_getNullRange();
4704 }
4705
4706 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004707 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004708 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4709 if (pieceIndex >= ME->getNumSelectorLocs())
4710 return clang_getNullRange();
4711 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4712 }
4713 }
4714
4715 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4716 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004717 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4719 if (pieceIndex >= MD->getNumSelectorLocs())
4720 return clang_getNullRange();
4721 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4722 }
4723 }
4724
4725 if (C.kind == CXCursor_ObjCCategoryDecl ||
4726 C.kind == CXCursor_ObjCCategoryImplDecl) {
4727 if (pieceIndex > 0)
4728 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004729 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4731 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004732 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4734 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4735 }
4736
4737 if (C.kind == CXCursor_ModuleImportDecl) {
4738 if (pieceIndex > 0)
4739 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004740 if (const ImportDecl *ImportD =
4741 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4743 if (!Locs.empty())
4744 return cxloc::translateSourceRange(Ctx,
4745 SourceRange(Locs.front(), Locs.back()));
4746 }
4747 return clang_getNullRange();
4748 }
4749
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004750 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004751 C.kind == CXCursor_ConversionFunction ||
4752 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004753 if (pieceIndex > 0)
4754 return clang_getNullRange();
4755 if (const FunctionDecl *FD =
4756 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4757 DeclarationNameInfo FunctionName = FD->getNameInfo();
4758 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4759 }
4760 return clang_getNullRange();
4761 }
4762
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 // FIXME: A CXCursor_InclusionDirective should give the location of the
4764 // filename, but we don't keep track of this.
4765
4766 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4767 // but we don't keep track of this.
4768
4769 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4770 // but we don't keep track of this.
4771
4772 // Default handling, give the location of the cursor.
4773
4774 if (pieceIndex > 0)
4775 return clang_getNullRange();
4776
4777 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4778 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4779 return cxloc::translateSourceRange(Ctx, Loc);
4780}
4781
Eli Bendersky44a206f2014-07-31 18:04:56 +00004782CXString clang_Cursor_getMangling(CXCursor C) {
4783 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4784 return cxstring::createEmpty();
4785
Eli Bendersky44a206f2014-07-31 18:04:56 +00004786 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004787 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004788 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4789 return cxstring::createEmpty();
4790
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004791 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004792 ASTNameGenerator ASTNameGen(Ctx);
4793 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004794}
4795
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004796CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4797 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4798 return nullptr;
4799
4800 const Decl *D = getCursorDecl(C);
4801 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4802 return nullptr;
4803
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004804 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004805 ASTNameGenerator ASTNameGen(Ctx);
4806 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004807 return cxstring::createSet(Manglings);
4808}
4809
Dave Lee1a532c92017-09-22 16:58:57 +00004810CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4811 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4812 return nullptr;
4813
4814 const Decl *D = getCursorDecl(C);
4815 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4816 return nullptr;
4817
4818 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004819 ASTNameGenerator ASTNameGen(Ctx);
4820 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004821 return cxstring::createSet(Manglings);
4822}
4823
Jonathan Coe45ef5032018-01-16 10:19:56 +00004824CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4825 if (clang_Cursor_isNull(C))
4826 return 0;
4827 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4828}
4829
4830void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4831 if (Policy)
4832 delete static_cast<PrintingPolicy *>(Policy);
4833}
4834
4835unsigned
4836clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4837 enum CXPrintingPolicyProperty Property) {
4838 if (!Policy)
4839 return 0;
4840
4841 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4842 switch (Property) {
4843 case CXPrintingPolicy_Indentation:
4844 return P->Indentation;
4845 case CXPrintingPolicy_SuppressSpecifiers:
4846 return P->SuppressSpecifiers;
4847 case CXPrintingPolicy_SuppressTagKeyword:
4848 return P->SuppressTagKeyword;
4849 case CXPrintingPolicy_IncludeTagDefinition:
4850 return P->IncludeTagDefinition;
4851 case CXPrintingPolicy_SuppressScope:
4852 return P->SuppressScope;
4853 case CXPrintingPolicy_SuppressUnwrittenScope:
4854 return P->SuppressUnwrittenScope;
4855 case CXPrintingPolicy_SuppressInitializers:
4856 return P->SuppressInitializers;
4857 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4858 return P->ConstantArraySizeAsWritten;
4859 case CXPrintingPolicy_AnonymousTagLocations:
4860 return P->AnonymousTagLocations;
4861 case CXPrintingPolicy_SuppressStrongLifetime:
4862 return P->SuppressStrongLifetime;
4863 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4864 return P->SuppressLifetimeQualifiers;
4865 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4866 return P->SuppressTemplateArgsInCXXConstructors;
4867 case CXPrintingPolicy_Bool:
4868 return P->Bool;
4869 case CXPrintingPolicy_Restrict:
4870 return P->Restrict;
4871 case CXPrintingPolicy_Alignof:
4872 return P->Alignof;
4873 case CXPrintingPolicy_UnderscoreAlignof:
4874 return P->UnderscoreAlignof;
4875 case CXPrintingPolicy_UseVoidForZeroParams:
4876 return P->UseVoidForZeroParams;
4877 case CXPrintingPolicy_TerseOutput:
4878 return P->TerseOutput;
4879 case CXPrintingPolicy_PolishForDeclaration:
4880 return P->PolishForDeclaration;
4881 case CXPrintingPolicy_Half:
4882 return P->Half;
4883 case CXPrintingPolicy_MSWChar:
4884 return P->MSWChar;
4885 case CXPrintingPolicy_IncludeNewlines:
4886 return P->IncludeNewlines;
4887 case CXPrintingPolicy_MSVCFormatting:
4888 return P->MSVCFormatting;
4889 case CXPrintingPolicy_ConstantsAsWritten:
4890 return P->ConstantsAsWritten;
4891 case CXPrintingPolicy_SuppressImplicitBase:
4892 return P->SuppressImplicitBase;
4893 case CXPrintingPolicy_FullyQualifiedName:
4894 return P->FullyQualifiedName;
4895 }
4896
4897 assert(false && "Invalid CXPrintingPolicyProperty");
4898 return 0;
4899}
4900
4901void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4902 enum CXPrintingPolicyProperty Property,
4903 unsigned Value) {
4904 if (!Policy)
4905 return;
4906
4907 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4908 switch (Property) {
4909 case CXPrintingPolicy_Indentation:
4910 P->Indentation = Value;
4911 return;
4912 case CXPrintingPolicy_SuppressSpecifiers:
4913 P->SuppressSpecifiers = Value;
4914 return;
4915 case CXPrintingPolicy_SuppressTagKeyword:
4916 P->SuppressTagKeyword = Value;
4917 return;
4918 case CXPrintingPolicy_IncludeTagDefinition:
4919 P->IncludeTagDefinition = Value;
4920 return;
4921 case CXPrintingPolicy_SuppressScope:
4922 P->SuppressScope = Value;
4923 return;
4924 case CXPrintingPolicy_SuppressUnwrittenScope:
4925 P->SuppressUnwrittenScope = Value;
4926 return;
4927 case CXPrintingPolicy_SuppressInitializers:
4928 P->SuppressInitializers = Value;
4929 return;
4930 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4931 P->ConstantArraySizeAsWritten = Value;
4932 return;
4933 case CXPrintingPolicy_AnonymousTagLocations:
4934 P->AnonymousTagLocations = Value;
4935 return;
4936 case CXPrintingPolicy_SuppressStrongLifetime:
4937 P->SuppressStrongLifetime = Value;
4938 return;
4939 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4940 P->SuppressLifetimeQualifiers = Value;
4941 return;
4942 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4943 P->SuppressTemplateArgsInCXXConstructors = Value;
4944 return;
4945 case CXPrintingPolicy_Bool:
4946 P->Bool = Value;
4947 return;
4948 case CXPrintingPolicy_Restrict:
4949 P->Restrict = Value;
4950 return;
4951 case CXPrintingPolicy_Alignof:
4952 P->Alignof = Value;
4953 return;
4954 case CXPrintingPolicy_UnderscoreAlignof:
4955 P->UnderscoreAlignof = Value;
4956 return;
4957 case CXPrintingPolicy_UseVoidForZeroParams:
4958 P->UseVoidForZeroParams = Value;
4959 return;
4960 case CXPrintingPolicy_TerseOutput:
4961 P->TerseOutput = Value;
4962 return;
4963 case CXPrintingPolicy_PolishForDeclaration:
4964 P->PolishForDeclaration = Value;
4965 return;
4966 case CXPrintingPolicy_Half:
4967 P->Half = Value;
4968 return;
4969 case CXPrintingPolicy_MSWChar:
4970 P->MSWChar = Value;
4971 return;
4972 case CXPrintingPolicy_IncludeNewlines:
4973 P->IncludeNewlines = Value;
4974 return;
4975 case CXPrintingPolicy_MSVCFormatting:
4976 P->MSVCFormatting = Value;
4977 return;
4978 case CXPrintingPolicy_ConstantsAsWritten:
4979 P->ConstantsAsWritten = Value;
4980 return;
4981 case CXPrintingPolicy_SuppressImplicitBase:
4982 P->SuppressImplicitBase = Value;
4983 return;
4984 case CXPrintingPolicy_FullyQualifiedName:
4985 P->FullyQualifiedName = Value;
4986 return;
4987 }
4988
4989 assert(false && "Invalid CXPrintingPolicyProperty");
4990}
4991
4992CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4993 if (clang_Cursor_isNull(C))
4994 return cxstring::createEmpty();
4995
4996 if (clang_isDeclaration(C.kind)) {
4997 const Decl *D = getCursorDecl(C);
4998 if (!D)
4999 return cxstring::createEmpty();
5000
5001 SmallString<128> Str;
5002 llvm::raw_svector_ostream OS(Str);
5003 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
5004 D->print(OS, UserPolicy ? *UserPolicy
5005 : getCursorContext(C).getPrintingPolicy());
5006
5007 return cxstring::createDup(OS.str());
5008 }
5009
5010 return cxstring::createEmpty();
5011}
5012
Guy Benyei11169dd2012-12-18 14:30:41 +00005013CXString clang_getCursorDisplayName(CXCursor C) {
5014 if (!clang_isDeclaration(C.kind))
5015 return clang_getCursorSpelling(C);
5016
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005017 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005019 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005020
5021 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005022 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 D = FunTmpl->getTemplatedDecl();
5024
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005025 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 SmallString<64> Str;
5027 llvm::raw_svector_ostream OS(Str);
5028 OS << *Function;
5029 if (Function->getPrimaryTemplate())
5030 OS << "<>";
5031 OS << "(";
5032 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5033 if (I)
5034 OS << ", ";
5035 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5036 }
5037
5038 if (Function->isVariadic()) {
5039 if (Function->getNumParams())
5040 OS << ", ";
5041 OS << "...";
5042 }
5043 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005044 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 }
5046
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005047 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 SmallString<64> Str;
5049 llvm::raw_svector_ostream OS(Str);
5050 OS << *ClassTemplate;
5051 OS << "<";
5052 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5053 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5054 if (I)
5055 OS << ", ";
5056
5057 NamedDecl *Param = Params->getParam(I);
5058 if (Param->getIdentifier()) {
5059 OS << Param->getIdentifier()->getName();
5060 continue;
5061 }
5062
5063 // There is no parameter name, which makes this tricky. Try to come up
5064 // with something useful that isn't too long.
5065 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Saar Razff1e0fc2020-01-15 02:48:42 +02005066 if (const auto *TC = TTP->getTypeConstraint()) {
5067 TC->getConceptNameInfo().printName(OS, Policy);
5068 if (TC->hasExplicitTemplateArgs())
5069 OS << "<...>";
5070 } else
5071 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 else if (NonTypeTemplateParmDecl *NTTP
5073 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5074 OS << NTTP->getType().getAsString(Policy);
5075 else
5076 OS << "template<...> class";
5077 }
5078
5079 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005080 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 }
5082
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005083 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5085 // If the type was explicitly written, use that.
5086 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005087 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005088
Benjamin Kramer9170e912013-02-22 15:46:01 +00005089 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 llvm::raw_svector_ostream OS(Str);
5091 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005092 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5093 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005094 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 }
5096
5097 return clang_getCursorSpelling(C);
5098}
5099
5100CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5101 switch (Kind) {
5102 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005166 case CXCursor_FixedPointLiteral:
5167 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005182 case CXCursor_OMPArraySectionExpr:
5183 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005234 case CXCursor_ObjCAvailabilityCheckExpr:
5235 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005236 case CXCursor_ObjCSelfExpr:
5237 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005257 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005264 case CXCursor_BuiltinBitCastExpr:
5265 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005277 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005297 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005307 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005309 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005311 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005313 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005315 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005317 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005319 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005321 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005323 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005325 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005327 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005328 case CXCursor_SEHLeaveStmt:
5329 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005330 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005331 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005333 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005335 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005337 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005338 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005339 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005340 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005341 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005343 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005345 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005347 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005349 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005350 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005351 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005352 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005353 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005355 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005357 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005358 case CXCursor_PackedAttr:
5359 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005360 case CXCursor_PureAttr:
5361 return cxstring::createRef("attribute(pure)");
5362 case CXCursor_ConstAttr:
5363 return cxstring::createRef("attribute(const)");
5364 case CXCursor_NoDuplicateAttr:
5365 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005366 case CXCursor_CUDAConstantAttr:
5367 return cxstring::createRef("attribute(constant)");
5368 case CXCursor_CUDADeviceAttr:
5369 return cxstring::createRef("attribute(device)");
5370 case CXCursor_CUDAGlobalAttr:
5371 return cxstring::createRef("attribute(global)");
5372 case CXCursor_CUDAHostAttr:
5373 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005374 case CXCursor_CUDASharedAttr:
5375 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005376 case CXCursor_VisibilityAttr:
5377 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005378 case CXCursor_DLLExport:
5379 return cxstring::createRef("attribute(dllexport)");
5380 case CXCursor_DLLImport:
5381 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005382 case CXCursor_NSReturnsRetained:
5383 return cxstring::createRef("attribute(ns_returns_retained)");
5384 case CXCursor_NSReturnsNotRetained:
5385 return cxstring::createRef("attribute(ns_returns_not_retained)");
5386 case CXCursor_NSReturnsAutoreleased:
5387 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5388 case CXCursor_NSConsumesSelf:
5389 return cxstring::createRef("attribute(ns_consumes_self)");
5390 case CXCursor_NSConsumed:
5391 return cxstring::createRef("attribute(ns_consumed)");
5392 case CXCursor_ObjCException:
5393 return cxstring::createRef("attribute(objc_exception)");
5394 case CXCursor_ObjCNSObject:
5395 return cxstring::createRef("attribute(NSObject)");
5396 case CXCursor_ObjCIndependentClass:
5397 return cxstring::createRef("attribute(objc_independent_class)");
5398 case CXCursor_ObjCPreciseLifetime:
5399 return cxstring::createRef("attribute(objc_precise_lifetime)");
5400 case CXCursor_ObjCReturnsInnerPointer:
5401 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5402 case CXCursor_ObjCRequiresSuper:
5403 return cxstring::createRef("attribute(objc_requires_super)");
5404 case CXCursor_ObjCRootClass:
5405 return cxstring::createRef("attribute(objc_root_class)");
5406 case CXCursor_ObjCSubclassingRestricted:
5407 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5408 case CXCursor_ObjCExplicitProtocolImpl:
5409 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5410 case CXCursor_ObjCDesignatedInitializer:
5411 return cxstring::createRef("attribute(objc_designated_initializer)");
5412 case CXCursor_ObjCRuntimeVisible:
5413 return cxstring::createRef("attribute(objc_runtime_visible)");
5414 case CXCursor_ObjCBoxable:
5415 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005416 case CXCursor_FlagEnum:
5417 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005418 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005419 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005420 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005421 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005422 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005423 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005425 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005426 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005427 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005428 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005429 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005431 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005432 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005433 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005434 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005435 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005436 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005437 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005438 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005439 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005441 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005442 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005443 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005444 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005445 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005446 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005447 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005448 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005449 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005451 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005453 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005454 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005455 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005457 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005458 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005459 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005460 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005461 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005462 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005463 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005464 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005465 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005466 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005467 return cxstring::createRef("OMPParallelDirective");
5468 case CXCursor_OMPSimdDirective:
5469 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005470 case CXCursor_OMPForDirective:
5471 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005472 case CXCursor_OMPForSimdDirective:
5473 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005474 case CXCursor_OMPSectionsDirective:
5475 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005476 case CXCursor_OMPSectionDirective:
5477 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005478 case CXCursor_OMPSingleDirective:
5479 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005480 case CXCursor_OMPMasterDirective:
5481 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005482 case CXCursor_OMPCriticalDirective:
5483 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005484 case CXCursor_OMPParallelForDirective:
5485 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005486 case CXCursor_OMPParallelForSimdDirective:
5487 return cxstring::createRef("OMPParallelForSimdDirective");
cchen47d60942019-12-05 13:43:48 -05005488 case CXCursor_OMPParallelMasterDirective:
5489 return cxstring::createRef("OMPParallelMasterDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005490 case CXCursor_OMPParallelSectionsDirective:
5491 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005492 case CXCursor_OMPTaskDirective:
5493 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005494 case CXCursor_OMPTaskyieldDirective:
5495 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005496 case CXCursor_OMPBarrierDirective:
5497 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005498 case CXCursor_OMPTaskwaitDirective:
5499 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005500 case CXCursor_OMPTaskgroupDirective:
5501 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005502 case CXCursor_OMPFlushDirective:
5503 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005504 case CXCursor_OMPOrderedDirective:
5505 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005506 case CXCursor_OMPAtomicDirective:
5507 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005508 case CXCursor_OMPTargetDirective:
5509 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005510 case CXCursor_OMPTargetDataDirective:
5511 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005512 case CXCursor_OMPTargetEnterDataDirective:
5513 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005514 case CXCursor_OMPTargetExitDataDirective:
5515 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005516 case CXCursor_OMPTargetParallelDirective:
5517 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005518 case CXCursor_OMPTargetParallelForDirective:
5519 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005520 case CXCursor_OMPTargetUpdateDirective:
5521 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005522 case CXCursor_OMPTeamsDirective:
5523 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005524 case CXCursor_OMPCancellationPointDirective:
5525 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005526 case CXCursor_OMPCancelDirective:
5527 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005528 case CXCursor_OMPTaskLoopDirective:
5529 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005530 case CXCursor_OMPTaskLoopSimdDirective:
5531 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005532 case CXCursor_OMPMasterTaskLoopDirective:
5533 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005534 case CXCursor_OMPMasterTaskLoopSimdDirective:
5535 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005536 case CXCursor_OMPParallelMasterTaskLoopDirective:
5537 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Alexey Bataev14a388f2019-10-25 10:27:13 -04005538 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5539 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005540 case CXCursor_OMPDistributeDirective:
5541 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005542 case CXCursor_OMPDistributeParallelForDirective:
5543 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005544 case CXCursor_OMPDistributeParallelForSimdDirective:
5545 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005546 case CXCursor_OMPDistributeSimdDirective:
5547 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005548 case CXCursor_OMPTargetParallelForSimdDirective:
5549 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005550 case CXCursor_OMPTargetSimdDirective:
5551 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005552 case CXCursor_OMPTeamsDistributeDirective:
5553 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005554 case CXCursor_OMPTeamsDistributeSimdDirective:
5555 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005556 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5557 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005558 case CXCursor_OMPTeamsDistributeParallelForDirective:
5559 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005560 case CXCursor_OMPTargetTeamsDirective:
5561 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005562 case CXCursor_OMPTargetTeamsDistributeDirective:
5563 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005564 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5565 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005566 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5567 return cxstring::createRef(
5568 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005569 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5570 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005571 case CXCursor_OverloadCandidate:
5572 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005573 case CXCursor_TypeAliasTemplateDecl:
5574 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005575 case CXCursor_StaticAssert:
5576 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005577 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005578 return cxstring::createRef("FriendDecl");
5579 case CXCursor_ConvergentAttr:
5580 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005581 case CXCursor_WarnUnusedAttr:
5582 return cxstring::createRef("attribute(warn_unused)");
5583 case CXCursor_WarnUnusedResultAttr:
5584 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005585 case CXCursor_AlignedAttr:
5586 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005587 }
5588
5589 llvm_unreachable("Unhandled CXCursorKind");
5590}
5591
5592struct GetCursorData {
5593 SourceLocation TokenBeginLoc;
5594 bool PointsAtMacroArgExpansion;
5595 bool VisitedObjCPropertyImplDecl;
5596 SourceLocation VisitedDeclaratorDeclStartLoc;
5597 CXCursor &BestCursor;
5598
5599 GetCursorData(SourceManager &SM,
5600 SourceLocation tokenBegin, CXCursor &outputCursor)
5601 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5602 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5603 VisitedObjCPropertyImplDecl = false;
5604 }
5605};
5606
5607static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5608 CXCursor parent,
5609 CXClientData client_data) {
5610 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5611 CXCursor *BestCursor = &Data->BestCursor;
5612
5613 // If we point inside a macro argument we should provide info of what the
5614 // token is so use the actual cursor, don't replace it with a macro expansion
5615 // cursor.
5616 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5617 return CXChildVisit_Recurse;
5618
5619 if (clang_isDeclaration(cursor.kind)) {
5620 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005621 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005622 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5623 if (MD->isImplicit())
5624 return CXChildVisit_Break;
5625
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005626 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005627 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5628 // Check that when we have multiple @class references in the same line,
5629 // that later ones do not override the previous ones.
5630 // If we have:
5631 // @class Foo, Bar;
5632 // source ranges for both start at '@', so 'Bar' will end up overriding
5633 // 'Foo' even though the cursor location was at 'Foo'.
5634 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5635 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005636 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005637 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5638 if (PrevID != ID &&
5639 !PrevID->isThisDeclarationADefinition() &&
5640 !ID->isThisDeclarationADefinition())
5641 return CXChildVisit_Break;
5642 }
5643
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005644 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005645 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5646 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5647 // Check that when we have multiple declarators in the same line,
5648 // that later ones do not override the previous ones.
5649 // If we have:
5650 // int Foo, Bar;
5651 // source ranges for both start at 'int', so 'Bar' will end up overriding
5652 // 'Foo' even though the cursor location was at 'Foo'.
5653 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5654 return CXChildVisit_Break;
5655 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5656
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005657 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5659 (void)PropImp;
5660 // Check that when we have multiple @synthesize in the same line,
5661 // that later ones do not override the previous ones.
5662 // If we have:
5663 // @synthesize Foo, Bar;
5664 // source ranges for both start at '@', so 'Bar' will end up overriding
5665 // 'Foo' even though the cursor location was at 'Foo'.
5666 if (Data->VisitedObjCPropertyImplDecl)
5667 return CXChildVisit_Break;
5668 Data->VisitedObjCPropertyImplDecl = true;
5669 }
5670 }
5671
5672 if (clang_isExpression(cursor.kind) &&
5673 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005674 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005675 // Avoid having the cursor of an expression replace the declaration cursor
5676 // when the expression source range overlaps the declaration range.
5677 // This can happen for C++ constructor expressions whose range generally
5678 // include the variable declaration, e.g.:
5679 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5680 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5681 D->getLocation() == Data->TokenBeginLoc)
5682 return CXChildVisit_Break;
5683 }
5684 }
5685
5686 // If our current best cursor is the construction of a temporary object,
5687 // don't replace that cursor with a type reference, because we want
5688 // clang_getCursor() to point at the constructor.
5689 if (clang_isExpression(BestCursor->kind) &&
5690 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5691 cursor.kind == CXCursor_TypeRef) {
5692 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5693 // as having the actual point on the type reference.
5694 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5695 return CXChildVisit_Recurse;
5696 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005697
5698 // If we already have an Objective-C superclass reference, don't
5699 // update it further.
5700 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5701 return CXChildVisit_Break;
5702
Guy Benyei11169dd2012-12-18 14:30:41 +00005703 *BestCursor = cursor;
5704 return CXChildVisit_Recurse;
5705}
5706
5707CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005708 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005709 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005710 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005711 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005712
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005713 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005714 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5715
5716 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5717 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5718
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005719 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005720 CXFile SearchFile;
5721 unsigned SearchLine, SearchColumn;
5722 CXFile ResultFile;
5723 unsigned ResultLine, ResultColumn;
5724 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5725 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5726 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005727
5728 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5729 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005730 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005731 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005732 SearchFileName = clang_getFileName(SearchFile);
5733 ResultFileName = clang_getFileName(ResultFile);
5734 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5735 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005736 *Log << llvm::format("(%s:%d:%d) = %s",
5737 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5738 clang_getCString(KindSpelling))
5739 << llvm::format("(%s:%d:%d):%s%s",
5740 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5741 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005742 clang_disposeString(SearchFileName);
5743 clang_disposeString(ResultFileName);
5744 clang_disposeString(KindSpelling);
5745 clang_disposeString(USR);
5746
5747 CXCursor Definition = clang_getCursorDefinition(Result);
5748 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5749 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5750 CXString DefinitionKindSpelling
5751 = clang_getCursorKindSpelling(Definition.kind);
5752 CXFile DefinitionFile;
5753 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005754 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005755 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005756 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005757 *Log << llvm::format(" -> %s(%s:%d:%d)",
5758 clang_getCString(DefinitionKindSpelling),
5759 clang_getCString(DefinitionFileName),
5760 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005761 clang_disposeString(DefinitionFileName);
5762 clang_disposeString(DefinitionKindSpelling);
5763 }
5764 }
5765
5766 return Result;
5767}
5768
5769CXCursor clang_getNullCursor(void) {
5770 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5771}
5772
5773unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005774 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5775 // can't set consistently. For example, when visiting a DeclStmt we will set
5776 // it but we don't set it on the result of clang_getCursorDefinition for
5777 // a reference of the same declaration.
5778 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5779 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5780 // to provide that kind of info.
5781 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005782 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005783 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005784 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005785
Guy Benyei11169dd2012-12-18 14:30:41 +00005786 return X == Y;
5787}
5788
5789unsigned clang_hashCursor(CXCursor C) {
5790 unsigned Index = 0;
5791 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5792 Index = 1;
5793
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005794 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005795 std::make_pair(C.kind, C.data[Index]));
5796}
5797
5798unsigned clang_isInvalid(enum CXCursorKind K) {
5799 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5800}
5801
5802unsigned clang_isDeclaration(enum CXCursorKind K) {
5803 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005804 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5805}
5806
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005807unsigned clang_isInvalidDeclaration(CXCursor C) {
5808 if (clang_isDeclaration(C.kind)) {
5809 if (const Decl *D = getCursorDecl(C))
5810 return D->isInvalidDecl();
5811 }
5812
5813 return 0;
5814}
5815
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005816unsigned clang_isReference(enum CXCursorKind K) {
5817 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5818}
Guy Benyei11169dd2012-12-18 14:30:41 +00005819
5820unsigned clang_isExpression(enum CXCursorKind K) {
5821 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5822}
5823
5824unsigned clang_isStatement(enum CXCursorKind K) {
5825 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5826}
5827
5828unsigned clang_isAttribute(enum CXCursorKind K) {
5829 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5830}
5831
5832unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5833 return K == CXCursor_TranslationUnit;
5834}
5835
5836unsigned clang_isPreprocessing(enum CXCursorKind K) {
5837 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5838}
5839
5840unsigned clang_isUnexposed(enum CXCursorKind K) {
5841 switch (K) {
5842 case CXCursor_UnexposedDecl:
5843 case CXCursor_UnexposedExpr:
5844 case CXCursor_UnexposedStmt:
5845 case CXCursor_UnexposedAttr:
5846 return true;
5847 default:
5848 return false;
5849 }
5850}
5851
5852CXCursorKind clang_getCursorKind(CXCursor C) {
5853 return C.kind;
5854}
5855
5856CXSourceLocation clang_getCursorLocation(CXCursor C) {
5857 if (clang_isReference(C.kind)) {
5858 switch (C.kind) {
5859 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005860 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005861 = getCursorObjCSuperClassRef(C);
5862 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5863 }
5864
5865 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005866 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 = getCursorObjCProtocolRef(C);
5868 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5869 }
5870
5871 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005872 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005873 = getCursorObjCClassRef(C);
5874 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5875 }
5876
5877 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005878 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005879 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5880 }
5881
5882 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005883 std::pair<const TemplateDecl *, SourceLocation> P =
5884 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005885 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5886 }
5887
5888 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005889 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005890 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5891 }
5892
5893 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005894 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005895 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5896 }
5897
5898 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005899 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005900 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5901 }
5902
5903 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005904 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005905 if (!BaseSpec)
5906 return clang_getNullLocation();
5907
5908 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5909 return cxloc::translateSourceLocation(getCursorContext(C),
5910 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005911
Guy Benyei11169dd2012-12-18 14:30:41 +00005912 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005913 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005914 }
5915
5916 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005917 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005918 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5919 }
5920
5921 case CXCursor_OverloadedDeclRef:
5922 return cxloc::translateSourceLocation(getCursorContext(C),
5923 getCursorOverloadedDeclRef(C).second);
5924
5925 default:
5926 // FIXME: Need a way to enumerate all non-reference cases.
5927 llvm_unreachable("Missed a reference kind");
5928 }
5929 }
5930
5931 if (clang_isExpression(C.kind))
5932 return cxloc::translateSourceLocation(getCursorContext(C),
5933 getLocationFromExpr(getCursorExpr(C)));
5934
5935 if (clang_isStatement(C.kind))
5936 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005937 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005938
5939 if (C.kind == CXCursor_PreprocessingDirective) {
5940 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5941 return cxloc::translateSourceLocation(getCursorContext(C), L);
5942 }
5943
5944 if (C.kind == CXCursor_MacroExpansion) {
5945 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005946 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005947 return cxloc::translateSourceLocation(getCursorContext(C), L);
5948 }
5949
5950 if (C.kind == CXCursor_MacroDefinition) {
5951 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5952 return cxloc::translateSourceLocation(getCursorContext(C), L);
5953 }
5954
5955 if (C.kind == CXCursor_InclusionDirective) {
5956 SourceLocation L
5957 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5958 return cxloc::translateSourceLocation(getCursorContext(C), L);
5959 }
5960
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005961 if (clang_isAttribute(C.kind)) {
5962 SourceLocation L
5963 = cxcursor::getCursorAttr(C)->getLocation();
5964 return cxloc::translateSourceLocation(getCursorContext(C), L);
5965 }
5966
Guy Benyei11169dd2012-12-18 14:30:41 +00005967 if (!clang_isDeclaration(C.kind))
5968 return clang_getNullLocation();
5969
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005970 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005971 if (!D)
5972 return clang_getNullLocation();
5973
5974 SourceLocation Loc = D->getLocation();
5975 // FIXME: Multiple variables declared in a single declaration
5976 // currently lack the information needed to correctly determine their
5977 // ranges when accounting for the type-specifier. We use context
5978 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5979 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005980 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005981 if (!cxcursor::isFirstInDeclGroup(C))
5982 Loc = VD->getLocation();
5983 }
5984
5985 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005986 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005987 Loc = MD->getSelectorStartLoc();
5988
5989 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5990}
5991
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005992} // end extern "C"
5993
Guy Benyei11169dd2012-12-18 14:30:41 +00005994CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5995 assert(TU);
5996
5997 // Guard against an invalid SourceLocation, or we may assert in one
5998 // of the following calls.
5999 if (SLoc.isInvalid())
6000 return clang_getNullCursor();
6001
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006002 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006003
6004 // Translate the given source location to make it point at the beginning of
6005 // the token under the cursor.
6006 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
6007 CXXUnit->getASTContext().getLangOpts());
6008
6009 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
6010 if (SLoc.isValid()) {
6011 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
6012 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
6013 /*VisitPreprocessorLast=*/true,
6014 /*VisitIncludedEntities=*/false,
6015 SourceLocation(SLoc));
6016 CursorVis.visitFileRegion();
6017 }
6018
6019 return Result;
6020}
6021
6022static SourceRange getRawCursorExtent(CXCursor C) {
6023 if (clang_isReference(C.kind)) {
6024 switch (C.kind) {
6025 case CXCursor_ObjCSuperClassRef:
6026 return getCursorObjCSuperClassRef(C).second;
6027
6028 case CXCursor_ObjCProtocolRef:
6029 return getCursorObjCProtocolRef(C).second;
6030
6031 case CXCursor_ObjCClassRef:
6032 return getCursorObjCClassRef(C).second;
6033
6034 case CXCursor_TypeRef:
6035 return getCursorTypeRef(C).second;
6036
6037 case CXCursor_TemplateRef:
6038 return getCursorTemplateRef(C).second;
6039
6040 case CXCursor_NamespaceRef:
6041 return getCursorNamespaceRef(C).second;
6042
6043 case CXCursor_MemberRef:
6044 return getCursorMemberRef(C).second;
6045
6046 case CXCursor_CXXBaseSpecifier:
6047 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6048
6049 case CXCursor_LabelRef:
6050 return getCursorLabelRef(C).second;
6051
6052 case CXCursor_OverloadedDeclRef:
6053 return getCursorOverloadedDeclRef(C).second;
6054
6055 case CXCursor_VariableRef:
6056 return getCursorVariableRef(C).second;
6057
6058 default:
6059 // FIXME: Need a way to enumerate all non-reference cases.
6060 llvm_unreachable("Missed a reference kind");
6061 }
6062 }
6063
6064 if (clang_isExpression(C.kind))
6065 return getCursorExpr(C)->getSourceRange();
6066
6067 if (clang_isStatement(C.kind))
6068 return getCursorStmt(C)->getSourceRange();
6069
6070 if (clang_isAttribute(C.kind))
6071 return getCursorAttr(C)->getRange();
6072
6073 if (C.kind == CXCursor_PreprocessingDirective)
6074 return cxcursor::getCursorPreprocessingDirective(C);
6075
6076 if (C.kind == CXCursor_MacroExpansion) {
6077 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006078 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006079 return TU->mapRangeFromPreamble(Range);
6080 }
6081
6082 if (C.kind == CXCursor_MacroDefinition) {
6083 ASTUnit *TU = getCursorASTUnit(C);
6084 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6085 return TU->mapRangeFromPreamble(Range);
6086 }
6087
6088 if (C.kind == CXCursor_InclusionDirective) {
6089 ASTUnit *TU = getCursorASTUnit(C);
6090 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6091 return TU->mapRangeFromPreamble(Range);
6092 }
6093
6094 if (C.kind == CXCursor_TranslationUnit) {
6095 ASTUnit *TU = getCursorASTUnit(C);
6096 FileID MainID = TU->getSourceManager().getMainFileID();
6097 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6098 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6099 return SourceRange(Start, End);
6100 }
6101
6102 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006103 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 if (!D)
6105 return SourceRange();
6106
6107 SourceRange R = D->getSourceRange();
6108 // FIXME: Multiple variables declared in a single declaration
6109 // currently lack the information needed to correctly determine their
6110 // ranges when accounting for the type-specifier. We use context
6111 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6112 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006113 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 if (!cxcursor::isFirstInDeclGroup(C))
6115 R.setBegin(VD->getLocation());
6116 }
6117 return R;
6118 }
6119 return SourceRange();
6120}
6121
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006122/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006123/// the decl-specifier-seq for declarations.
6124static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6125 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006126 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006127 if (!D)
6128 return SourceRange();
6129
6130 SourceRange R = D->getSourceRange();
6131
6132 // Adjust the start of the location for declarations preceded by
6133 // declaration specifiers.
6134 SourceLocation StartLoc;
6135 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6136 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006137 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006138 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006139 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006140 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006141 }
6142
6143 if (StartLoc.isValid() && R.getBegin().isValid() &&
6144 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6145 R.setBegin(StartLoc);
6146
6147 // FIXME: Multiple variables declared in a single declaration
6148 // currently lack the information needed to correctly determine their
6149 // ranges when accounting for the type-specifier. We use context
6150 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6151 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006152 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 if (!cxcursor::isFirstInDeclGroup(C))
6154 R.setBegin(VD->getLocation());
6155 }
6156
6157 return R;
6158 }
6159
6160 return getRawCursorExtent(C);
6161}
6162
Guy Benyei11169dd2012-12-18 14:30:41 +00006163CXSourceRange clang_getCursorExtent(CXCursor C) {
6164 SourceRange R = getRawCursorExtent(C);
6165 if (R.isInvalid())
6166 return clang_getNullRange();
6167
6168 return cxloc::translateSourceRange(getCursorContext(C), R);
6169}
6170
6171CXCursor clang_getCursorReferenced(CXCursor C) {
6172 if (clang_isInvalid(C.kind))
6173 return clang_getNullCursor();
6174
6175 CXTranslationUnit tu = getCursorTU(C);
6176 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006177 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 if (!D)
6179 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006180 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006182 if (const ObjCPropertyImplDecl *PropImpl =
6183 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006184 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6185 return MakeCXCursor(Property, tu);
6186
6187 return C;
6188 }
6189
6190 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006191 const Expr *E = getCursorExpr(C);
6192 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006193 if (D) {
6194 CXCursor declCursor = MakeCXCursor(D, tu);
6195 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6196 declCursor);
6197 return declCursor;
6198 }
6199
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006200 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006201 return MakeCursorOverloadedDeclRef(Ovl, tu);
6202
6203 return clang_getNullCursor();
6204 }
6205
6206 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006207 const Stmt *S = getCursorStmt(C);
6208 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006209 if (LabelDecl *label = Goto->getLabel())
6210 if (LabelStmt *labelS = label->getStmt())
6211 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6212
6213 return clang_getNullCursor();
6214 }
Richard Smith66a81862015-05-04 02:25:31 +00006215
Guy Benyei11169dd2012-12-18 14:30:41 +00006216 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006217 if (const MacroDefinitionRecord *Def =
6218 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006219 return MakeMacroDefinitionCursor(Def, tu);
6220 }
6221
6222 if (!clang_isReference(C.kind))
6223 return clang_getNullCursor();
6224
6225 switch (C.kind) {
6226 case CXCursor_ObjCSuperClassRef:
6227 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6228
6229 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006230 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6231 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 return MakeCXCursor(Def, tu);
6233
6234 return MakeCXCursor(Prot, tu);
6235 }
6236
6237 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006238 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6239 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006240 return MakeCXCursor(Def, tu);
6241
6242 return MakeCXCursor(Class, tu);
6243 }
6244
6245 case CXCursor_TypeRef:
6246 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6247
6248 case CXCursor_TemplateRef:
6249 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6250
6251 case CXCursor_NamespaceRef:
6252 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6253
6254 case CXCursor_MemberRef:
6255 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6256
6257 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006258 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006259 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6260 tu ));
6261 }
6262
6263 case CXCursor_LabelRef:
6264 // FIXME: We end up faking the "parent" declaration here because we
6265 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006266 return MakeCXCursor(getCursorLabelRef(C).first,
6267 cxtu::getASTUnit(tu)->getASTContext()
6268 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006269 tu);
6270
6271 case CXCursor_OverloadedDeclRef:
6272 return C;
6273
6274 case CXCursor_VariableRef:
6275 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6276
6277 default:
6278 // We would prefer to enumerate all non-reference cursor kinds here.
6279 llvm_unreachable("Unhandled reference cursor kind");
6280 }
6281}
6282
6283CXCursor clang_getCursorDefinition(CXCursor C) {
6284 if (clang_isInvalid(C.kind))
6285 return clang_getNullCursor();
6286
6287 CXTranslationUnit TU = getCursorTU(C);
6288
6289 bool WasReference = false;
6290 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6291 C = clang_getCursorReferenced(C);
6292 WasReference = true;
6293 }
6294
6295 if (C.kind == CXCursor_MacroExpansion)
6296 return clang_getCursorReferenced(C);
6297
6298 if (!clang_isDeclaration(C.kind))
6299 return clang_getNullCursor();
6300
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006301 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006302 if (!D)
6303 return clang_getNullCursor();
6304
6305 switch (D->getKind()) {
6306 // Declaration kinds that don't really separate the notions of
6307 // declaration and definition.
6308 case Decl::Namespace:
6309 case Decl::Typedef:
6310 case Decl::TypeAlias:
6311 case Decl::TypeAliasTemplate:
6312 case Decl::TemplateTypeParm:
6313 case Decl::EnumConstant:
6314 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006315 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006316 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006317 case Decl::IndirectField:
6318 case Decl::ObjCIvar:
6319 case Decl::ObjCAtDefsField:
6320 case Decl::ImplicitParam:
6321 case Decl::ParmVar:
6322 case Decl::NonTypeTemplateParm:
6323 case Decl::TemplateTemplateParm:
6324 case Decl::ObjCCategoryImpl:
6325 case Decl::ObjCImplementation:
6326 case Decl::AccessSpec:
6327 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006328 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006329 case Decl::ObjCPropertyImpl:
6330 case Decl::FileScopeAsm:
6331 case Decl::StaticAssert:
6332 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006333 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006334 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006335 case Decl::Label: // FIXME: Is this right??
6336 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006337 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006338 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006339 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006340 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006341 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006342 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006343 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006344 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006345 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006346 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006347 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006348 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006349 case Decl::Concept:
Tykerb0561b32019-11-17 11:41:55 +01006350 case Decl::LifetimeExtendedTemporary:
Saar Raza0f50d72020-01-18 09:11:43 +02006351 case Decl::RequiresExprBody:
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 return C;
6353
6354 // Declaration kinds that don't make any sense here, but are
6355 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006356 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006357 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006358 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006359 break;
6360
6361 // Declaration kinds for which the definition is not resolvable.
6362 case Decl::UnresolvedUsingTypename:
6363 case Decl::UnresolvedUsingValue:
6364 break;
6365
6366 case Decl::UsingDirective:
6367 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6368 TU);
6369
6370 case Decl::NamespaceAlias:
6371 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6372
6373 case Decl::Enum:
6374 case Decl::Record:
6375 case Decl::CXXRecord:
6376 case Decl::ClassTemplateSpecialization:
6377 case Decl::ClassTemplatePartialSpecialization:
6378 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6379 return MakeCXCursor(Def, TU);
6380 return clang_getNullCursor();
6381
6382 case Decl::Function:
6383 case Decl::CXXMethod:
6384 case Decl::CXXConstructor:
6385 case Decl::CXXDestructor:
6386 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006387 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006388 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006389 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 return clang_getNullCursor();
6391 }
6392
Larisse Voufo39a1e502013-08-06 01:03:05 +00006393 case Decl::Var:
6394 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006395 case Decl::VarTemplatePartialSpecialization:
6396 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006397 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006398 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006399 return MakeCXCursor(Def, TU);
6400 return clang_getNullCursor();
6401 }
6402
6403 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006404 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006405 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6406 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6407 return clang_getNullCursor();
6408 }
6409
6410 case Decl::ClassTemplate: {
6411 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6412 ->getDefinition())
6413 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6414 TU);
6415 return clang_getNullCursor();
6416 }
6417
Larisse Voufo39a1e502013-08-06 01:03:05 +00006418 case Decl::VarTemplate: {
6419 if (VarDecl *Def =
6420 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6421 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6422 return clang_getNullCursor();
6423 }
6424
Guy Benyei11169dd2012-12-18 14:30:41 +00006425 case Decl::Using:
6426 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6427 D->getLocation(), TU);
6428
6429 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006430 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006431 return clang_getCursorDefinition(
6432 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6433 TU));
6434
6435 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006436 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006437 if (Method->isThisDeclarationADefinition())
6438 return C;
6439
6440 // Dig out the method definition in the associated
6441 // @implementation, if we have it.
6442 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006443 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006444 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6445 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6446 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6447 Method->isInstanceMethod()))
6448 if (Def->isThisDeclarationADefinition())
6449 return MakeCXCursor(Def, TU);
6450
6451 return clang_getNullCursor();
6452 }
6453
6454 case Decl::ObjCCategory:
6455 if (ObjCCategoryImplDecl *Impl
6456 = cast<ObjCCategoryDecl>(D)->getImplementation())
6457 return MakeCXCursor(Impl, TU);
6458 return clang_getNullCursor();
6459
6460 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006461 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006462 return MakeCXCursor(Def, TU);
6463 return clang_getNullCursor();
6464
6465 case Decl::ObjCInterface: {
6466 // There are two notions of a "definition" for an Objective-C
6467 // class: the interface and its implementation. When we resolved a
6468 // reference to an Objective-C class, produce the @interface as
6469 // the definition; when we were provided with the interface,
6470 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006471 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006473 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006474 return MakeCXCursor(Def, TU);
6475 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6476 return MakeCXCursor(Impl, TU);
6477 return clang_getNullCursor();
6478 }
6479
6480 case Decl::ObjCProperty:
6481 // FIXME: We don't really know where to find the
6482 // ObjCPropertyImplDecls that implement this property.
6483 return clang_getNullCursor();
6484
6485 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006486 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006487 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006488 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006489 return MakeCXCursor(Def, TU);
6490
6491 return clang_getNullCursor();
6492
6493 case Decl::Friend:
6494 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6495 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6496 return clang_getNullCursor();
6497
6498 case Decl::FriendTemplate:
6499 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6500 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6501 return clang_getNullCursor();
6502 }
6503
6504 return clang_getNullCursor();
6505}
6506
6507unsigned clang_isCursorDefinition(CXCursor C) {
6508 if (!clang_isDeclaration(C.kind))
6509 return 0;
6510
6511 return clang_getCursorDefinition(C) == C;
6512}
6513
6514CXCursor clang_getCanonicalCursor(CXCursor C) {
6515 if (!clang_isDeclaration(C.kind))
6516 return C;
6517
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006518 if (const Decl *D = getCursorDecl(C)) {
6519 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006520 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6521 return MakeCXCursor(CatD, getCursorTU(C));
6522
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006523 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6524 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006525 return MakeCXCursor(IFD, getCursorTU(C));
6526
6527 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6528 }
6529
6530 return C;
6531}
6532
6533int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6534 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6535}
6536
6537unsigned clang_getNumOverloadedDecls(CXCursor C) {
6538 if (C.kind != CXCursor_OverloadedDeclRef)
6539 return 0;
6540
6541 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006542 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006543 return E->getNumDecls();
6544
6545 if (OverloadedTemplateStorage *S
6546 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6547 return S->size();
6548
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006549 const Decl *D = Storage.get<const Decl *>();
6550 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006551 return Using->shadow_size();
6552
6553 return 0;
6554}
6555
6556CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6557 if (cursor.kind != CXCursor_OverloadedDeclRef)
6558 return clang_getNullCursor();
6559
6560 if (index >= clang_getNumOverloadedDecls(cursor))
6561 return clang_getNullCursor();
6562
6563 CXTranslationUnit TU = getCursorTU(cursor);
6564 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006565 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006566 return MakeCXCursor(E->decls_begin()[index], TU);
6567
6568 if (OverloadedTemplateStorage *S
6569 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6570 return MakeCXCursor(S->begin()[index], TU);
6571
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006572 const Decl *D = Storage.get<const Decl *>();
6573 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006574 // FIXME: This is, unfortunately, linear time.
6575 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6576 std::advance(Pos, index);
6577 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6578 }
6579
6580 return clang_getNullCursor();
6581}
6582
6583void clang_getDefinitionSpellingAndExtent(CXCursor C,
6584 const char **startBuf,
6585 const char **endBuf,
6586 unsigned *startLine,
6587 unsigned *startColumn,
6588 unsigned *endLine,
6589 unsigned *endColumn) {
6590 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006591 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6593
6594 SourceManager &SM = FD->getASTContext().getSourceManager();
6595 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6596 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6597 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6598 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6599 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6600 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6601}
6602
6603
6604CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6605 unsigned PieceIndex) {
6606 RefNamePieces Pieces;
6607
6608 switch (C.kind) {
6609 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006610 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006611 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6612 E->getQualifierLoc().getSourceRange());
6613 break;
6614
6615 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006616 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6617 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6618 Pieces =
6619 buildPieces(NameFlags, false, E->getNameInfo(),
6620 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6621 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006622 break;
6623
6624 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006625 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006626 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006627 const Expr *Callee = OCE->getCallee();
6628 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006629 Callee = ICE->getSubExpr();
6630
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006631 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006632 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6633 DRE->getQualifierLoc().getSourceRange());
6634 }
6635 break;
6636
6637 default:
6638 break;
6639 }
6640
6641 if (Pieces.empty()) {
6642 if (PieceIndex == 0)
6643 return clang_getCursorExtent(C);
6644 } else if (PieceIndex < Pieces.size()) {
6645 SourceRange R = Pieces[PieceIndex];
6646 if (R.isValid())
6647 return cxloc::translateSourceRange(getCursorContext(C), R);
6648 }
6649
6650 return clang_getNullRange();
6651}
6652
6653void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006654 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6655 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006656}
6657
6658void clang_executeOnThread(void (*fn)(void*), void *user_data,
6659 unsigned stack_size) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05006660 llvm::llvm_execute_on_thread(fn, user_data,
6661 stack_size == 0
6662 ? clang::DesiredStackSize
6663 : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006664}
6665
Guy Benyei11169dd2012-12-18 14:30:41 +00006666//===----------------------------------------------------------------------===//
6667// Token-based Operations.
6668//===----------------------------------------------------------------------===//
6669
6670/* CXToken layout:
6671 * int_data[0]: a CXTokenKind
6672 * int_data[1]: starting token location
6673 * int_data[2]: token length
6674 * int_data[3]: reserved
6675 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6676 * otherwise unused.
6677 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006678CXTokenKind clang_getTokenKind(CXToken CXTok) {
6679 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6680}
6681
6682CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6683 switch (clang_getTokenKind(CXTok)) {
6684 case CXToken_Identifier:
6685 case CXToken_Keyword:
6686 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006687 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006688 ->getNameStart());
6689
6690 case CXToken_Literal: {
6691 // We have stashed the starting pointer in the ptr_data field. Use it.
6692 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006693 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 }
6695
6696 case CXToken_Punctuation:
6697 case CXToken_Comment:
6698 break;
6699 }
6700
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006701 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006702 LOG_BAD_TU(TU);
6703 return cxstring::createEmpty();
6704 }
6705
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 // We have to find the starting buffer pointer the hard way, by
6707 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006708 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006709 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006710 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006711
6712 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6713 std::pair<FileID, unsigned> LocInfo
6714 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6715 bool Invalid = false;
6716 StringRef Buffer
6717 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6718 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006719 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006720
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006721 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006722}
6723
6724CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006725 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006726 LOG_BAD_TU(TU);
6727 return clang_getNullLocation();
6728 }
6729
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006730 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006731 if (!CXXUnit)
6732 return clang_getNullLocation();
6733
6734 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6735 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6736}
6737
6738CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006739 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006740 LOG_BAD_TU(TU);
6741 return clang_getNullRange();
6742 }
6743
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006744 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006745 if (!CXXUnit)
6746 return clang_getNullRange();
6747
6748 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6749 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6750}
6751
6752static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6753 SmallVectorImpl<CXToken> &CXTokens) {
6754 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6755 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006756 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006757 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006758 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006759
6760 // Cannot tokenize across files.
6761 if (BeginLocInfo.first != EndLocInfo.first)
6762 return;
6763
6764 // Create a lexer
6765 bool Invalid = false;
6766 StringRef Buffer
6767 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6768 if (Invalid)
6769 return;
6770
6771 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6772 CXXUnit->getASTContext().getLangOpts(),
6773 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6774 Lex.SetCommentRetentionState(true);
6775
6776 // Lex tokens until we hit the end of the range.
6777 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6778 Token Tok;
6779 bool previousWasAt = false;
6780 do {
6781 // Lex the next token
6782 Lex.LexFromRawLexer(Tok);
6783 if (Tok.is(tok::eof))
6784 break;
6785
6786 // Initialize the CXToken.
6787 CXToken CXTok;
6788
6789 // - Common fields
6790 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6791 CXTok.int_data[2] = Tok.getLength();
6792 CXTok.int_data[3] = 0;
6793
6794 // - Kind-specific fields
6795 if (Tok.isLiteral()) {
6796 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006797 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006798 } else if (Tok.is(tok::raw_identifier)) {
6799 // Lookup the identifier to determine whether we have a keyword.
6800 IdentifierInfo *II
6801 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6802
6803 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6804 CXTok.int_data[0] = CXToken_Keyword;
6805 }
6806 else {
6807 CXTok.int_data[0] = Tok.is(tok::identifier)
6808 ? CXToken_Identifier
6809 : CXToken_Keyword;
6810 }
6811 CXTok.ptr_data = II;
6812 } else if (Tok.is(tok::comment)) {
6813 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006814 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006815 } else {
6816 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006817 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006818 }
6819 CXTokens.push_back(CXTok);
6820 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006821 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006822}
6823
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006824CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6825 LOG_FUNC_SECTION {
6826 *Log << TU << ' ' << Location;
6827 }
6828
6829 if (isNotUsableTU(TU)) {
6830 LOG_BAD_TU(TU);
6831 return NULL;
6832 }
6833
6834 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6835 if (!CXXUnit)
6836 return NULL;
6837
6838 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6839 if (Begin.isInvalid())
6840 return NULL;
6841 SourceManager &SM = CXXUnit->getSourceManager();
6842 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6843 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6844
6845 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6846
6847 SmallVector<CXToken, 32> CXTokens;
6848 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6849
6850 if (CXTokens.empty())
6851 return NULL;
6852
6853 CXTokens.resize(1);
6854 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6855
6856 memmove(Token, CXTokens.data(), sizeof(CXToken));
6857 return Token;
6858}
6859
Guy Benyei11169dd2012-12-18 14:30:41 +00006860void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6861 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006862 LOG_FUNC_SECTION {
6863 *Log << TU << ' ' << Range;
6864 }
6865
Guy Benyei11169dd2012-12-18 14:30:41 +00006866 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006867 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006868 if (NumTokens)
6869 *NumTokens = 0;
6870
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006871 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006872 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006873 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006874 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006875
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006876 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006877 if (!CXXUnit || !Tokens || !NumTokens)
6878 return;
6879
6880 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6881
6882 SourceRange R = cxloc::translateCXSourceRange(Range);
6883 if (R.isInvalid())
6884 return;
6885
6886 SmallVector<CXToken, 32> CXTokens;
6887 getTokens(CXXUnit, R, CXTokens);
6888
6889 if (CXTokens.empty())
6890 return;
6891
Serge Pavlov52525732018-02-21 02:02:39 +00006892 *Tokens = static_cast<CXToken *>(
6893 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006894 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6895 *NumTokens = CXTokens.size();
6896}
6897
6898void clang_disposeTokens(CXTranslationUnit TU,
6899 CXToken *Tokens, unsigned NumTokens) {
6900 free(Tokens);
6901}
6902
Guy Benyei11169dd2012-12-18 14:30:41 +00006903//===----------------------------------------------------------------------===//
6904// Token annotation APIs.
6905//===----------------------------------------------------------------------===//
6906
Guy Benyei11169dd2012-12-18 14:30:41 +00006907static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6908 CXCursor parent,
6909 CXClientData client_data);
6910static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6911 CXClientData client_data);
6912
6913namespace {
6914class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006915 CXToken *Tokens;
6916 CXCursor *Cursors;
6917 unsigned NumTokens;
6918 unsigned TokIdx;
6919 unsigned PreprocessingTokIdx;
6920 CursorVisitor AnnotateVis;
6921 SourceManager &SrcMgr;
6922 bool HasContextSensitiveKeywords;
6923
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006924 struct PostChildrenAction {
6925 CXCursor cursor;
6926 enum Action { Invalid, Ignore, Postpone } action;
6927 };
6928 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6929
Guy Benyei11169dd2012-12-18 14:30:41 +00006930 struct PostChildrenInfo {
6931 CXCursor Cursor;
6932 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006933 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006934 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006935 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006937 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006938
6939 CXToken &getTok(unsigned Idx) {
6940 assert(Idx < NumTokens);
6941 return Tokens[Idx];
6942 }
6943 const CXToken &getTok(unsigned Idx) const {
6944 assert(Idx < NumTokens);
6945 return Tokens[Idx];
6946 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 bool MoreTokens() const { return TokIdx < NumTokens; }
6948 unsigned NextToken() const { return TokIdx; }
6949 void AdvanceToken() { ++TokIdx; }
6950 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006951 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 }
6953 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006954 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 }
6956 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006957 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 }
6959
6960 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006961 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006962 SourceRange);
6963
6964public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006965 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006966 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006967 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006968 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006969 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006970 AnnotateTokensVisitor, this,
6971 /*VisitPreprocessorLast=*/true,
6972 /*VisitIncludedEntities=*/false,
6973 RegionOfInterest,
6974 /*VisitDeclsOnly=*/false,
6975 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006976 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006977 HasContextSensitiveKeywords(false) { }
6978
6979 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6980 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006981 bool IsIgnoredChildCursor(CXCursor cursor) const;
6982 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6983
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006985 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6986 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6987
Guy Benyei11169dd2012-12-18 14:30:41 +00006988 void AnnotateTokens();
6989
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006990 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006991 /// context-sensitive keywords.
6992 bool hasContextSensitiveKeywords() const {
6993 return HasContextSensitiveKeywords;
6994 }
6995
6996 ~AnnotateTokensWorker() {
6997 assert(PostChildrenInfos.empty());
6998 }
6999};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007000}
Guy Benyei11169dd2012-12-18 14:30:41 +00007001
7002void AnnotateTokensWorker::AnnotateTokens() {
7003 // Walk the AST within the region of interest, annotating tokens
7004 // along the way.
7005 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007006}
Guy Benyei11169dd2012-12-18 14:30:41 +00007007
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007008bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
7009 if (PostChildrenInfos.empty())
7010 return false;
7011
7012 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
7013 if (ChildAction.cursor == cursor &&
7014 ChildAction.action == PostChildrenAction::Ignore) {
7015 return true;
7016 }
7017 }
7018
7019 return false;
7020}
7021
7022const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
7023 if (!clang_isExpression(Cursor.kind))
7024 return nullptr;
7025
7026 const Expr *E = getCursorExpr(Cursor);
7027 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7028 const OverloadedOperatorKind Kind = OCE->getOperator();
7029 if (Kind == OO_Call || Kind == OO_Subscript)
7030 return OCE;
7031 }
7032
7033 return nullptr;
7034}
7035
7036AnnotateTokensWorker::PostChildrenActions
7037AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7038 PostChildrenActions actions;
7039
7040 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
7041 // visited before the arguments to the operator call. For the Call and
7042 // Subscript operator the range of this DeclRefExpr includes the whole call
7043 // expression, so that all tokens in that range would be mapped to the
7044 // operator function, including the tokens of the arguments. To avoid that,
7045 // ensure to visit this DeclRefExpr as last node.
7046 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7047 const Expr *Callee = OCE->getCallee();
7048 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7049 const Expr *SubExpr = ICE->getSubExpr();
7050 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007051 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007052 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7053
7054 // Visit the DeclRefExpr as last.
7055 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7056 actions.push_back({cxChild, PostChildrenAction::Postpone});
7057
7058 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7059 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7060 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7061 actions.push_back({cxChild, PostChildrenAction::Ignore});
7062 }
7063 }
7064 }
7065
7066 return actions;
7067}
7068
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007069static inline void updateCursorAnnotation(CXCursor &Cursor,
7070 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007071 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007072 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007073 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007074}
7075
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007076/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007077//// between the cursor location and the source range is the same as
7078/// \arg compResult.
7079///
7080/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7081/// Pass RangeOverlap to annotate tokens inside a range.
7082void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7083 RangeComparisonResult compResult,
7084 SourceRange range) {
7085 while (MoreTokens()) {
7086 const unsigned I = NextToken();
7087 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007088 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7089 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007090
7091 SourceLocation TokLoc = GetTokenLoc(I);
7092 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007093 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007094 AdvanceToken();
7095 continue;
7096 }
7097 break;
7098 }
7099}
7100
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007101/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007102/// \returns true if it advanced beyond all macro tokens, false otherwise.
7103bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 CXCursor updateC,
7105 RangeComparisonResult compResult,
7106 SourceRange range) {
7107 assert(MoreTokens());
7108 assert(isFunctionMacroToken(NextToken()) &&
7109 "Should be called only for macro arg tokens");
7110
7111 // This works differently than annotateAndAdvanceTokens; because expanded
7112 // macro arguments can have arbitrary translation-unit source order, we do not
7113 // advance the token index one by one until a token fails the range test.
7114 // We only advance once past all of the macro arg tokens if all of them
7115 // pass the range test. If one of them fails we keep the token index pointing
7116 // at the start of the macro arg tokens so that the failing token will be
7117 // annotated by a subsequent annotation try.
7118
7119 bool atLeastOneCompFail = false;
7120
7121 unsigned I = NextToken();
7122 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7123 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7124 if (TokLoc.isFileID())
7125 continue; // not macro arg token, it's parens or comma.
7126 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7127 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7128 Cursors[I] = updateC;
7129 } else
7130 atLeastOneCompFail = true;
7131 }
7132
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007133 if (atLeastOneCompFail)
7134 return false;
7135
7136 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7137 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007138}
7139
7140enum CXChildVisitResult
7141AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007142 SourceRange cursorRange = getRawCursorExtent(cursor);
7143 if (cursorRange.isInvalid())
7144 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007145
7146 if (IsIgnoredChildCursor(cursor))
7147 return CXChildVisit_Continue;
7148
Guy Benyei11169dd2012-12-18 14:30:41 +00007149 if (!HasContextSensitiveKeywords) {
7150 // Objective-C properties can have context-sensitive keywords.
7151 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007152 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007153 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7154 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7155 }
7156 // Objective-C methods can have context-sensitive keywords.
7157 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7158 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007159 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007160 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7161 if (Method->getObjCDeclQualifier())
7162 HasContextSensitiveKeywords = true;
7163 else {
David Majnemer59f77922016-06-24 04:05:48 +00007164 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007165 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007166 HasContextSensitiveKeywords = true;
7167 break;
7168 }
7169 }
7170 }
7171 }
7172 }
7173 // C++ methods can have context-sensitive keywords.
7174 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007175 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007176 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7177 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7178 HasContextSensitiveKeywords = true;
7179 }
7180 }
7181 // C++ classes can have context-sensitive keywords.
7182 else if (cursor.kind == CXCursor_StructDecl ||
7183 cursor.kind == CXCursor_ClassDecl ||
7184 cursor.kind == CXCursor_ClassTemplate ||
7185 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007186 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007187 if (D->hasAttr<FinalAttr>())
7188 HasContextSensitiveKeywords = true;
7189 }
7190 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007191
7192 // Don't override a property annotation with its getter/setter method.
7193 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7194 parent.kind == CXCursor_ObjCPropertyDecl)
7195 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007196
7197 if (clang_isPreprocessing(cursor.kind)) {
7198 // Items in the preprocessing record are kept separate from items in
7199 // declarations, so we keep a separate token index.
7200 unsigned SavedTokIdx = TokIdx;
7201 TokIdx = PreprocessingTokIdx;
7202
7203 // Skip tokens up until we catch up to the beginning of the preprocessing
7204 // entry.
7205 while (MoreTokens()) {
7206 const unsigned I = NextToken();
7207 SourceLocation TokLoc = GetTokenLoc(I);
7208 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7209 case RangeBefore:
7210 AdvanceToken();
7211 continue;
7212 case RangeAfter:
7213 case RangeOverlap:
7214 break;
7215 }
7216 break;
7217 }
7218
7219 // Look at all of the tokens within this range.
7220 while (MoreTokens()) {
7221 const unsigned I = NextToken();
7222 SourceLocation TokLoc = GetTokenLoc(I);
7223 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7224 case RangeBefore:
7225 llvm_unreachable("Infeasible");
7226 case RangeAfter:
7227 break;
7228 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007229 // For macro expansions, just note where the beginning of the macro
7230 // expansion occurs.
7231 if (cursor.kind == CXCursor_MacroExpansion) {
7232 if (TokLoc == cursorRange.getBegin())
7233 Cursors[I] = cursor;
7234 AdvanceToken();
7235 break;
7236 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007237 // We may have already annotated macro names inside macro definitions.
7238 if (Cursors[I].kind != CXCursor_MacroExpansion)
7239 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007240 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007241 continue;
7242 }
7243 break;
7244 }
7245
7246 // Save the preprocessing token index; restore the non-preprocessing
7247 // token index.
7248 PreprocessingTokIdx = TokIdx;
7249 TokIdx = SavedTokIdx;
7250 return CXChildVisit_Recurse;
7251 }
7252
7253 if (cursorRange.isInvalid())
7254 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007255
7256 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007257 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 const enum CXCursorKind K = clang_getCursorKind(parent);
7259 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007260 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7261 // Attributes are annotated out-of-order, skip tokens until we reach it.
7262 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007263 ? clang_getNullCursor() : parent;
7264
7265 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7266
7267 // Avoid having the cursor of an expression "overwrite" the annotation of the
7268 // variable declaration that it belongs to.
7269 // This can happen for C++ constructor expressions whose range generally
7270 // include the variable declaration, e.g.:
7271 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007272 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007273 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007274 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007275 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007276 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7277 E->getBeginLoc() == D->getLocation() &&
7278 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007279 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007280 AdvanceToken();
7281 }
7282 }
7283 }
7284
7285 // Before recursing into the children keep some state that we are going
7286 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7287 // extra work after the child nodes are visited.
7288 // Note that we don't call VisitChildren here to avoid traversing statements
7289 // code-recursively which can blow the stack.
7290
7291 PostChildrenInfo Info;
7292 Info.Cursor = cursor;
7293 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007294 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007295 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007296 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007297 PostChildrenInfos.push_back(Info);
7298
7299 return CXChildVisit_Recurse;
7300}
7301
7302bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7303 if (PostChildrenInfos.empty())
7304 return false;
7305 const PostChildrenInfo &Info = PostChildrenInfos.back();
7306 if (!clang_equalCursors(Info.Cursor, cursor))
7307 return false;
7308
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007309 HandlePostPonedChildCursors(Info);
7310
Guy Benyei11169dd2012-12-18 14:30:41 +00007311 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7312 const unsigned AfterChildren = NextToken();
7313 SourceRange cursorRange = Info.CursorRange;
7314
7315 // Scan the tokens that are at the end of the cursor, but are not captured
7316 // but the child cursors.
7317 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7318
7319 // Scan the tokens that are at the beginning of the cursor, but are not
7320 // capture by the child cursors.
7321 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7322 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7323 break;
7324
7325 Cursors[I] = cursor;
7326 }
7327
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007328 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7329 // encountered the attribute cursor.
7330 if (clang_isAttribute(cursor.kind))
7331 TokIdx = Info.BeforeReachingCursorIdx;
7332
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 PostChildrenInfos.pop_back();
7334 return false;
7335}
7336
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007337void AnnotateTokensWorker::HandlePostPonedChildCursors(
7338 const PostChildrenInfo &Info) {
7339 for (const auto &ChildAction : Info.ChildActions) {
7340 if (ChildAction.action == PostChildrenAction::Postpone) {
7341 HandlePostPonedChildCursor(ChildAction.cursor,
7342 Info.BeforeChildrenTokenIdx);
7343 }
7344 }
7345}
7346
7347void AnnotateTokensWorker::HandlePostPonedChildCursor(
7348 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007349 unsigned I = StartTokenIndex;
7350
7351 // The bracket tokens of a Call or Subscript operator are mapped to
7352 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7353 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7354 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007355 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7356 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007357 if (clang_Range_isNull(CXRefNameRange))
7358 break; // All ranges handled.
7359
7360 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7361 while (I < NumTokens) {
7362 const SourceLocation TokenLocation = GetTokenLoc(I);
7363 if (!TokenLocation.isValid())
7364 break;
7365
7366 // Adapt the end range, because LocationCompare() reports
7367 // RangeOverlap even for the not-inclusive end location.
7368 const SourceLocation fixedEnd =
7369 RefNameRange.getEnd().getLocWithOffset(-1);
7370 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7371
7372 const RangeComparisonResult ComparisonResult =
7373 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7374
7375 if (ComparisonResult == RangeOverlap) {
7376 Cursors[I++] = Cursor;
7377 } else if (ComparisonResult == RangeBefore) {
7378 ++I; // Not relevant token, check next one.
7379 } else if (ComparisonResult == RangeAfter) {
7380 break; // All tokens updated for current range, check next.
7381 }
7382 }
7383 }
7384}
7385
Guy Benyei11169dd2012-12-18 14:30:41 +00007386static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7387 CXCursor parent,
7388 CXClientData client_data) {
7389 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7390}
7391
7392static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7393 CXClientData client_data) {
7394 return static_cast<AnnotateTokensWorker*>(client_data)->
7395 postVisitChildren(cursor);
7396}
7397
7398namespace {
7399
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007400/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007401/// and mark tokens that are macro arguments. This info is used by the
7402/// AnnotateTokensWorker.
7403class MarkMacroArgTokensVisitor {
7404 SourceManager &SM;
7405 CXToken *Tokens;
7406 unsigned NumTokens;
7407 unsigned CurIdx;
7408
7409public:
7410 MarkMacroArgTokensVisitor(SourceManager &SM,
7411 CXToken *tokens, unsigned numTokens)
7412 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7413
7414 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7415 if (cursor.kind != CXCursor_MacroExpansion)
7416 return CXChildVisit_Continue;
7417
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007418 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007419 if (macroRange.getBegin() == macroRange.getEnd())
7420 return CXChildVisit_Continue; // it's not a function macro.
7421
7422 for (; CurIdx < NumTokens; ++CurIdx) {
7423 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7424 macroRange.getBegin()))
7425 break;
7426 }
7427
7428 if (CurIdx == NumTokens)
7429 return CXChildVisit_Break;
7430
7431 for (; CurIdx < NumTokens; ++CurIdx) {
7432 SourceLocation tokLoc = getTokenLoc(CurIdx);
7433 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7434 break;
7435
7436 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7437 }
7438
7439 if (CurIdx == NumTokens)
7440 return CXChildVisit_Break;
7441
7442 return CXChildVisit_Continue;
7443 }
7444
7445private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007446 CXToken &getTok(unsigned Idx) {
7447 assert(Idx < NumTokens);
7448 return Tokens[Idx];
7449 }
7450 const CXToken &getTok(unsigned Idx) const {
7451 assert(Idx < NumTokens);
7452 return Tokens[Idx];
7453 }
7454
Guy Benyei11169dd2012-12-18 14:30:41 +00007455 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007456 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 }
7458
7459 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7460 // The third field is reserved and currently not used. Use it here
7461 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007462 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007463 }
7464};
7465
7466} // end anonymous namespace
7467
7468static CXChildVisitResult
7469MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7470 CXClientData client_data) {
7471 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7472 parent);
7473}
7474
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007475/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007476/// \returns true if lexing was finished, false otherwise.
7477static bool lexNext(Lexer &Lex, Token &Tok,
7478 unsigned &NextIdx, unsigned NumTokens) {
7479 if (NextIdx >= NumTokens)
7480 return true;
7481
7482 ++NextIdx;
7483 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007484 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007485}
7486
Guy Benyei11169dd2012-12-18 14:30:41 +00007487static void annotatePreprocessorTokens(CXTranslationUnit TU,
7488 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007489 CXCursor *Cursors,
7490 CXToken *Tokens,
7491 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007492 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007493
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007494 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007495 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7496 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007497 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007498 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007499 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007500
7501 if (BeginLocInfo.first != EndLocInfo.first)
7502 return;
7503
7504 StringRef Buffer;
7505 bool Invalid = false;
7506 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7507 if (Buffer.empty() || Invalid)
7508 return;
7509
7510 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7511 CXXUnit->getASTContext().getLangOpts(),
7512 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7513 Buffer.end());
7514 Lex.SetCommentRetentionState(true);
7515
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007516 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007517 // Lex tokens in raw mode until we hit the end of the range, to avoid
7518 // entering #includes or expanding macros.
7519 while (true) {
7520 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007521 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7522 break;
7523 unsigned TokIdx = NextIdx-1;
7524 assert(Tok.getLocation() ==
7525 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007526
7527 reprocess:
7528 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007529 // We have found a preprocessing directive. Annotate the tokens
7530 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007531 //
7532 // FIXME: Some simple tests here could identify macro definitions and
7533 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007534
7535 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007536 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7537 break;
7538
Craig Topper69186e72014-06-08 08:38:04 +00007539 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007540 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007541 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7542 break;
7543
7544 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007545 IdentifierInfo &II =
7546 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007547 SourceLocation MappedTokLoc =
7548 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7549 MI = getMacroInfo(II, MappedTokLoc, TU);
7550 }
7551 }
7552
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007553 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007554 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007555 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7556 finished = true;
7557 break;
7558 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007559 // If we are in a macro definition, check if the token was ever a
7560 // macro name and annotate it if that's the case.
7561 if (MI) {
7562 SourceLocation SaveLoc = Tok.getLocation();
7563 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007564 MacroDefinitionRecord *MacroDef =
7565 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007566 Tok.setLocation(SaveLoc);
7567 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007568 Cursors[NextIdx - 1] =
7569 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007570 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007571 } while (!Tok.isAtStartOfLine());
7572
7573 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7574 assert(TokIdx <= LastIdx);
7575 SourceLocation EndLoc =
7576 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7577 CXCursor Cursor =
7578 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7579
7580 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007581 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007582
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007583 if (finished)
7584 break;
7585 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007586 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007587 }
7588}
7589
7590// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007591static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7592 CXToken *Tokens, unsigned NumTokens,
7593 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007594 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007595 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7596 setThreadBackgroundPriority();
7597
7598 // Determine the region of interest, which contains all of the tokens.
7599 SourceRange RegionOfInterest;
7600 RegionOfInterest.setBegin(
7601 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7602 RegionOfInterest.setEnd(
7603 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7604 Tokens[NumTokens-1])));
7605
Guy Benyei11169dd2012-12-18 14:30:41 +00007606 // Relex the tokens within the source range to look for preprocessing
7607 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007608 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007609
7610 // If begin location points inside a macro argument, set it to the expansion
7611 // location so we can have the full context when annotating semantically.
7612 {
7613 SourceManager &SM = CXXUnit->getSourceManager();
7614 SourceLocation Loc =
7615 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7616 if (Loc.isMacroID())
7617 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7618 }
7619
Guy Benyei11169dd2012-12-18 14:30:41 +00007620 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7621 // Search and mark tokens that are macro argument expansions.
7622 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7623 Tokens, NumTokens);
7624 CursorVisitor MacroArgMarker(TU,
7625 MarkMacroArgTokensVisitorDelegate, &Visitor,
7626 /*VisitPreprocessorLast=*/true,
7627 /*VisitIncludedEntities=*/false,
7628 RegionOfInterest);
7629 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7630 }
7631
7632 // Annotate all of the source locations in the region of interest that map to
7633 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007634 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007635
7636 // FIXME: We use a ridiculous stack size here because the data-recursion
7637 // algorithm uses a large stack frame than the non-data recursive version,
7638 // and AnnotationTokensWorker currently transforms the data-recursion
7639 // algorithm back into a traditional recursion by explicitly calling
7640 // VisitChildren(). We will need to remove this explicit recursive call.
7641 W.AnnotateTokens();
7642
7643 // If we ran into any entities that involve context-sensitive keywords,
7644 // take another pass through the tokens to mark them as such.
7645 if (W.hasContextSensitiveKeywords()) {
7646 for (unsigned I = 0; I != NumTokens; ++I) {
7647 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7648 continue;
7649
7650 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7651 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007652 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007653 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7654 if (Property->getPropertyAttributesAsWritten() != 0 &&
7655 llvm::StringSwitch<bool>(II->getName())
7656 .Case("readonly", true)
7657 .Case("assign", true)
7658 .Case("unsafe_unretained", true)
7659 .Case("readwrite", true)
7660 .Case("retain", true)
7661 .Case("copy", true)
7662 .Case("nonatomic", true)
7663 .Case("atomic", true)
7664 .Case("getter", true)
7665 .Case("setter", true)
7666 .Case("strong", true)
7667 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007668 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007669 .Default(false))
7670 Tokens[I].int_data[0] = CXToken_Keyword;
7671 }
7672 continue;
7673 }
7674
7675 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7676 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7677 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7678 if (llvm::StringSwitch<bool>(II->getName())
7679 .Case("in", true)
7680 .Case("out", true)
7681 .Case("inout", true)
7682 .Case("oneway", true)
7683 .Case("bycopy", true)
7684 .Case("byref", true)
7685 .Default(false))
7686 Tokens[I].int_data[0] = CXToken_Keyword;
7687 continue;
7688 }
7689
7690 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7691 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7692 Tokens[I].int_data[0] = CXToken_Keyword;
7693 continue;
7694 }
7695 }
7696 }
7697}
7698
Guy Benyei11169dd2012-12-18 14:30:41 +00007699void clang_annotateTokens(CXTranslationUnit TU,
7700 CXToken *Tokens, unsigned NumTokens,
7701 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007702 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007703 LOG_BAD_TU(TU);
7704 return;
7705 }
7706 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007707 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007708 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007709 }
7710
7711 LOG_FUNC_SECTION {
7712 *Log << TU << ' ';
7713 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7714 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7715 *Log << clang_getRange(bloc, eloc);
7716 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007717
7718 // Any token we don't specifically annotate will have a NULL cursor.
7719 CXCursor C = clang_getNullCursor();
7720 for (unsigned I = 0; I != NumTokens; ++I)
7721 Cursors[I] = C;
7722
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007723 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007724 if (!CXXUnit)
7725 return;
7726
7727 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007728
7729 auto AnnotateTokensImpl = [=]() {
7730 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7731 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007732 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007733 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007734 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7735 }
7736}
7737
Guy Benyei11169dd2012-12-18 14:30:41 +00007738//===----------------------------------------------------------------------===//
7739// Operations for querying linkage of a cursor.
7740//===----------------------------------------------------------------------===//
7741
Guy Benyei11169dd2012-12-18 14:30:41 +00007742CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7743 if (!clang_isDeclaration(cursor.kind))
7744 return CXLinkage_Invalid;
7745
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007746 const Decl *D = cxcursor::getCursorDecl(cursor);
7747 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007748 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007749 case NoLinkage:
7750 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007751 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007752 case InternalLinkage: return CXLinkage_Internal;
7753 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007754 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007755 case ExternalLinkage: return CXLinkage_External;
7756 };
7757
7758 return CXLinkage_Invalid;
7759}
Guy Benyei11169dd2012-12-18 14:30:41 +00007760
7761//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007762// Operations for querying visibility of a cursor.
7763//===----------------------------------------------------------------------===//
7764
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007765CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7766 if (!clang_isDeclaration(cursor.kind))
7767 return CXVisibility_Invalid;
7768
7769 const Decl *D = cxcursor::getCursorDecl(cursor);
7770 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7771 switch (ND->getVisibility()) {
7772 case HiddenVisibility: return CXVisibility_Hidden;
7773 case ProtectedVisibility: return CXVisibility_Protected;
7774 case DefaultVisibility: return CXVisibility_Default;
7775 };
7776
7777 return CXVisibility_Invalid;
7778}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007779
7780//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007781// Operations for querying language of a cursor.
7782//===----------------------------------------------------------------------===//
7783
7784static CXLanguageKind getDeclLanguage(const Decl *D) {
7785 if (!D)
7786 return CXLanguage_C;
7787
7788 switch (D->getKind()) {
7789 default:
7790 break;
7791 case Decl::ImplicitParam:
7792 case Decl::ObjCAtDefsField:
7793 case Decl::ObjCCategory:
7794 case Decl::ObjCCategoryImpl:
7795 case Decl::ObjCCompatibleAlias:
7796 case Decl::ObjCImplementation:
7797 case Decl::ObjCInterface:
7798 case Decl::ObjCIvar:
7799 case Decl::ObjCMethod:
7800 case Decl::ObjCProperty:
7801 case Decl::ObjCPropertyImpl:
7802 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007803 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007804 return CXLanguage_ObjC;
7805 case Decl::CXXConstructor:
7806 case Decl::CXXConversion:
7807 case Decl::CXXDestructor:
7808 case Decl::CXXMethod:
7809 case Decl::CXXRecord:
7810 case Decl::ClassTemplate:
7811 case Decl::ClassTemplatePartialSpecialization:
7812 case Decl::ClassTemplateSpecialization:
7813 case Decl::Friend:
7814 case Decl::FriendTemplate:
7815 case Decl::FunctionTemplate:
7816 case Decl::LinkageSpec:
7817 case Decl::Namespace:
7818 case Decl::NamespaceAlias:
7819 case Decl::NonTypeTemplateParm:
7820 case Decl::StaticAssert:
7821 case Decl::TemplateTemplateParm:
7822 case Decl::TemplateTypeParm:
7823 case Decl::UnresolvedUsingTypename:
7824 case Decl::UnresolvedUsingValue:
7825 case Decl::Using:
7826 case Decl::UsingDirective:
7827 case Decl::UsingShadow:
7828 return CXLanguage_CPlusPlus;
7829 }
7830
7831 return CXLanguage_C;
7832}
7833
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007834static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7835 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007836 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007837
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007838 switch (D->getAvailability()) {
7839 case AR_Available:
7840 case AR_NotYetIntroduced:
7841 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007842 return getCursorAvailabilityForDecl(
7843 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007844 return CXAvailability_Available;
7845
7846 case AR_Deprecated:
7847 return CXAvailability_Deprecated;
7848
7849 case AR_Unavailable:
7850 return CXAvailability_NotAvailable;
7851 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007852
7853 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007854}
7855
Guy Benyei11169dd2012-12-18 14:30:41 +00007856enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7857 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007858 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7859 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007860
7861 return CXAvailability_Available;
7862}
7863
7864static CXVersion convertVersion(VersionTuple In) {
7865 CXVersion Out = { -1, -1, -1 };
7866 if (In.empty())
7867 return Out;
7868
7869 Out.Major = In.getMajor();
7870
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007871 Optional<unsigned> Minor = In.getMinor();
7872 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007873 Out.Minor = *Minor;
7874 else
7875 return Out;
7876
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007877 Optional<unsigned> Subminor = In.getSubminor();
7878 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007879 Out.Subminor = *Subminor;
7880
7881 return Out;
7882}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007883
Alex Lorenz1345ea22017-06-12 19:06:30 +00007884static void getCursorPlatformAvailabilityForDecl(
7885 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7886 int *always_unavailable, CXString *unavailable_message,
7887 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007888 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007889 for (auto A : D->attrs()) {
7890 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007891 HadAvailAttr = true;
7892 if (always_deprecated)
7893 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007894 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007895 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007896 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007897 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007898 continue;
7899 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007900
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007901 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007902 HadAvailAttr = true;
7903 if (always_unavailable)
7904 *always_unavailable = 1;
7905 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007906 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007907 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7908 }
7909 continue;
7910 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007911
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007912 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007913 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007914 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007915 }
7916 }
7917
7918 if (!HadAvailAttr)
7919 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7920 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007921 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7922 deprecated_message, always_unavailable, unavailable_message,
7923 AvailabilityAttrs);
7924
7925 if (AvailabilityAttrs.empty())
7926 return;
7927
Fangrui Song55fab262018-09-26 22:16:28 +00007928 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007929 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7930 return LHS->getPlatform()->getName() <
7931 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007932 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007933 ASTContext &Ctx = D->getASTContext();
7934 auto It = std::unique(
7935 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7936 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7937 if (LHS->getPlatform() != RHS->getPlatform())
7938 return false;
7939
7940 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7941 LHS->getDeprecated() == RHS->getDeprecated() &&
7942 LHS->getObsoleted() == RHS->getObsoleted() &&
7943 LHS->getMessage() == RHS->getMessage() &&
7944 LHS->getReplacement() == RHS->getReplacement())
7945 return true;
7946
7947 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7948 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7949 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7950 return false;
7951
7952 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7953 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7954
7955 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7956 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7957 if (LHS->getMessage().empty())
7958 LHS->setMessage(Ctx, RHS->getMessage());
7959 if (LHS->getReplacement().empty())
7960 LHS->setReplacement(Ctx, RHS->getReplacement());
7961 }
7962
7963 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7964 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7965 if (LHS->getMessage().empty())
7966 LHS->setMessage(Ctx, RHS->getMessage());
7967 if (LHS->getReplacement().empty())
7968 LHS->setReplacement(Ctx, RHS->getReplacement());
7969 }
7970
7971 return true;
7972 });
7973 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007974}
7975
Alex Lorenz1345ea22017-06-12 19:06:30 +00007976int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007977 CXString *deprecated_message,
7978 int *always_unavailable,
7979 CXString *unavailable_message,
7980 CXPlatformAvailability *availability,
7981 int availability_size) {
7982 if (always_deprecated)
7983 *always_deprecated = 0;
7984 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007985 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007986 if (always_unavailable)
7987 *always_unavailable = 0;
7988 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007989 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007990
Guy Benyei11169dd2012-12-18 14:30:41 +00007991 if (!clang_isDeclaration(cursor.kind))
7992 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007993
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007994 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007995 if (!D)
7996 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007997
Alex Lorenz1345ea22017-06-12 19:06:30 +00007998 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7999 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
8000 always_unavailable, unavailable_message,
8001 AvailabilityAttrs);
8002 for (const auto &Avail :
8003 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
8004 .take_front(availability_size))) {
8005 availability[Avail.index()].Platform =
8006 cxstring::createDup(Avail.value()->getPlatform()->getName());
8007 availability[Avail.index()].Introduced =
8008 convertVersion(Avail.value()->getIntroduced());
8009 availability[Avail.index()].Deprecated =
8010 convertVersion(Avail.value()->getDeprecated());
8011 availability[Avail.index()].Obsoleted =
8012 convertVersion(Avail.value()->getObsoleted());
8013 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
8014 availability[Avail.index()].Message =
8015 cxstring::createDup(Avail.value()->getMessage());
8016 }
8017
8018 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008019}
Alex Lorenz1345ea22017-06-12 19:06:30 +00008020
Guy Benyei11169dd2012-12-18 14:30:41 +00008021void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
8022 clang_disposeString(availability->Platform);
8023 clang_disposeString(availability->Message);
8024}
8025
8026CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
8027 if (clang_isDeclaration(cursor.kind))
8028 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
8029
8030 return CXLanguage_Invalid;
8031}
8032
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00008033CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
8034 const Decl *D = cxcursor::getCursorDecl(cursor);
8035 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8036 switch (VD->getTLSKind()) {
8037 case VarDecl::TLS_None:
8038 return CXTLS_None;
8039 case VarDecl::TLS_Dynamic:
8040 return CXTLS_Dynamic;
8041 case VarDecl::TLS_Static:
8042 return CXTLS_Static;
8043 }
8044 }
8045
8046 return CXTLS_None;
8047}
8048
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008049 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008050 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008051 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008052static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008053 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008054 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008055
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008056 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008057 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8058 return FunTmpl;
8059
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008060 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8062 return ClassTmpl;
8063
8064 return D;
8065}
8066
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008067
8068enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8069 StorageClass sc = SC_None;
8070 const Decl *D = getCursorDecl(C);
8071 if (D) {
8072 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8073 sc = FD->getStorageClass();
8074 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8075 sc = VD->getStorageClass();
8076 } else {
8077 return CX_SC_Invalid;
8078 }
8079 } else {
8080 return CX_SC_Invalid;
8081 }
8082 switch (sc) {
8083 case SC_None:
8084 return CX_SC_None;
8085 case SC_Extern:
8086 return CX_SC_Extern;
8087 case SC_Static:
8088 return CX_SC_Static;
8089 case SC_PrivateExtern:
8090 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008091 case SC_Auto:
8092 return CX_SC_Auto;
8093 case SC_Register:
8094 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008095 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008096 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008097}
8098
Guy Benyei11169dd2012-12-18 14:30:41 +00008099CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8100 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008101 if (const Decl *D = getCursorDecl(cursor)) {
8102 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008103 if (!DC)
8104 return clang_getNullCursor();
8105
8106 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8107 getCursorTU(cursor));
8108 }
8109 }
8110
8111 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008112 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008113 return MakeCXCursor(D, getCursorTU(cursor));
8114 }
8115
8116 return clang_getNullCursor();
8117}
8118
8119CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8120 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008121 if (const Decl *D = getCursorDecl(cursor)) {
8122 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008123 if (!DC)
8124 return clang_getNullCursor();
8125
8126 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8127 getCursorTU(cursor));
8128 }
8129 }
8130
8131 // FIXME: Note that we can't easily compute the lexical context of a
8132 // statement or expression, so we return nothing.
8133 return clang_getNullCursor();
8134}
8135
8136CXFile clang_getIncludedFile(CXCursor cursor) {
8137 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008138 return nullptr;
8139
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008140 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008141 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008142}
8143
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008144unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8145 if (C.kind != CXCursor_ObjCPropertyDecl)
8146 return CXObjCPropertyAttr_noattr;
8147
8148 unsigned Result = CXObjCPropertyAttr_noattr;
8149 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8150 ObjCPropertyDecl::PropertyAttributeKind Attr =
8151 PD->getPropertyAttributesAsWritten();
8152
8153#define SET_CXOBJCPROP_ATTR(A) \
8154 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8155 Result |= CXObjCPropertyAttr_##A
8156 SET_CXOBJCPROP_ATTR(readonly);
8157 SET_CXOBJCPROP_ATTR(getter);
8158 SET_CXOBJCPROP_ATTR(assign);
8159 SET_CXOBJCPROP_ATTR(readwrite);
8160 SET_CXOBJCPROP_ATTR(retain);
8161 SET_CXOBJCPROP_ATTR(copy);
8162 SET_CXOBJCPROP_ATTR(nonatomic);
8163 SET_CXOBJCPROP_ATTR(setter);
8164 SET_CXOBJCPROP_ATTR(atomic);
8165 SET_CXOBJCPROP_ATTR(weak);
8166 SET_CXOBJCPROP_ATTR(strong);
8167 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008168 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008169#undef SET_CXOBJCPROP_ATTR
8170
8171 return Result;
8172}
8173
Michael Wu6e88f532018-08-03 05:38:29 +00008174CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8175 if (C.kind != CXCursor_ObjCPropertyDecl)
8176 return cxstring::createNull();
8177
8178 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8179 Selector sel = PD->getGetterName();
8180 if (sel.isNull())
8181 return cxstring::createNull();
8182
8183 return cxstring::createDup(sel.getAsString());
8184}
8185
8186CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8187 if (C.kind != CXCursor_ObjCPropertyDecl)
8188 return cxstring::createNull();
8189
8190 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8191 Selector sel = PD->getSetterName();
8192 if (sel.isNull())
8193 return cxstring::createNull();
8194
8195 return cxstring::createDup(sel.getAsString());
8196}
8197
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008198unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8199 if (!clang_isDeclaration(C.kind))
8200 return CXObjCDeclQualifier_None;
8201
8202 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8203 const Decl *D = getCursorDecl(C);
8204 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8205 QT = MD->getObjCDeclQualifier();
8206 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8207 QT = PD->getObjCDeclQualifier();
8208 if (QT == Decl::OBJC_TQ_None)
8209 return CXObjCDeclQualifier_None;
8210
8211 unsigned Result = CXObjCDeclQualifier_None;
8212 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8213 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8214 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8215 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8216 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8217 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8218
8219 return Result;
8220}
8221
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008222unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8223 if (!clang_isDeclaration(C.kind))
8224 return 0;
8225
8226 const Decl *D = getCursorDecl(C);
8227 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8228 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8229 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8230 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8231
8232 return 0;
8233}
8234
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008235unsigned clang_Cursor_isVariadic(CXCursor C) {
8236 if (!clang_isDeclaration(C.kind))
8237 return 0;
8238
8239 const Decl *D = getCursorDecl(C);
8240 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8241 return FD->isVariadic();
8242 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8243 return MD->isVariadic();
8244
8245 return 0;
8246}
8247
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008248unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8249 CXString *language, CXString *definedIn,
8250 unsigned *isGenerated) {
8251 if (!clang_isDeclaration(C.kind))
8252 return 0;
8253
8254 const Decl *D = getCursorDecl(C);
8255
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008256 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008257 if (language)
8258 *language = cxstring::createDup(attr->getLanguage());
8259 if (definedIn)
8260 *definedIn = cxstring::createDup(attr->getDefinedIn());
8261 if (isGenerated)
8262 *isGenerated = attr->getGeneratedDeclaration();
8263 return 1;
8264 }
8265 return 0;
8266}
8267
Guy Benyei11169dd2012-12-18 14:30:41 +00008268CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8269 if (!clang_isDeclaration(C.kind))
8270 return clang_getNullRange();
8271
8272 const Decl *D = getCursorDecl(C);
8273 ASTContext &Context = getCursorContext(C);
8274 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8275 if (!RC)
8276 return clang_getNullRange();
8277
8278 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8279}
8280
8281CXString clang_Cursor_getRawCommentText(CXCursor C) {
8282 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008283 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008284
8285 const Decl *D = getCursorDecl(C);
8286 ASTContext &Context = getCursorContext(C);
8287 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8288 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8289 StringRef();
8290
8291 // Don't duplicate the string because RawText points directly into source
8292 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008293 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008294}
8295
8296CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8297 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008298 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008299
8300 const Decl *D = getCursorDecl(C);
8301 const ASTContext &Context = getCursorContext(C);
8302 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8303
8304 if (RC) {
8305 StringRef BriefText = RC->getBriefText(Context);
8306
8307 // Don't duplicate the string because RawComment ensures that this memory
8308 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008309 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008310 }
8311
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008312 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008313}
8314
Guy Benyei11169dd2012-12-18 14:30:41 +00008315CXModule clang_Cursor_getModule(CXCursor C) {
8316 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008317 if (const ImportDecl *ImportD =
8318 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008319 return ImportD->getImportedModule();
8320 }
8321
Craig Topper69186e72014-06-08 08:38:04 +00008322 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008323}
8324
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008325CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8326 if (isNotUsableTU(TU)) {
8327 LOG_BAD_TU(TU);
8328 return nullptr;
8329 }
8330 if (!File)
8331 return nullptr;
8332 FileEntry *FE = static_cast<FileEntry *>(File);
8333
8334 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8335 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8336 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8337
Richard Smithfeb54b62014-10-23 02:01:19 +00008338 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008339}
8340
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008341CXFile clang_Module_getASTFile(CXModule CXMod) {
8342 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008343 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008344 Module *Mod = static_cast<Module*>(CXMod);
8345 return const_cast<FileEntry *>(Mod->getASTFile());
8346}
8347
Guy Benyei11169dd2012-12-18 14:30:41 +00008348CXModule clang_Module_getParent(CXModule CXMod) {
8349 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008350 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008351 Module *Mod = static_cast<Module*>(CXMod);
8352 return Mod->Parent;
8353}
8354
8355CXString clang_Module_getName(CXModule CXMod) {
8356 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008357 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008358 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008359 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008360}
8361
8362CXString clang_Module_getFullName(CXModule CXMod) {
8363 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008364 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008365 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008366 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008367}
8368
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008369int clang_Module_isSystem(CXModule CXMod) {
8370 if (!CXMod)
8371 return 0;
8372 Module *Mod = static_cast<Module*>(CXMod);
8373 return Mod->IsSystem;
8374}
8375
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008376unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8377 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008378 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008379 LOG_BAD_TU(TU);
8380 return 0;
8381 }
8382 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008383 return 0;
8384 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008385 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8386 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8387 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008388}
8389
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008390CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8391 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008392 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008393 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008394 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008395 }
8396 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008397 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008398 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008399 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008400
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008401 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8402 if (Index < TopHeaders.size())
8403 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008404
Craig Topper69186e72014-06-08 08:38:04 +00008405 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008406}
8407
Guy Benyei11169dd2012-12-18 14:30:41 +00008408//===----------------------------------------------------------------------===//
8409// C++ AST instrospection.
8410//===----------------------------------------------------------------------===//
8411
Jonathan Coe29565352016-04-27 12:48:25 +00008412unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8413 if (!clang_isDeclaration(C.kind))
8414 return 0;
8415
8416 const Decl *D = cxcursor::getCursorDecl(C);
8417 const CXXConstructorDecl *Constructor =
8418 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8419 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8420}
8421
8422unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8423 if (!clang_isDeclaration(C.kind))
8424 return 0;
8425
8426 const Decl *D = cxcursor::getCursorDecl(C);
8427 const CXXConstructorDecl *Constructor =
8428 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8429 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8430}
8431
8432unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8433 if (!clang_isDeclaration(C.kind))
8434 return 0;
8435
8436 const Decl *D = cxcursor::getCursorDecl(C);
8437 const CXXConstructorDecl *Constructor =
8438 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8439 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8440}
8441
8442unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8443 if (!clang_isDeclaration(C.kind))
8444 return 0;
8445
8446 const Decl *D = cxcursor::getCursorDecl(C);
8447 const CXXConstructorDecl *Constructor =
8448 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8449 // Passing 'false' excludes constructors marked 'explicit'.
8450 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8451}
8452
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008453unsigned clang_CXXField_isMutable(CXCursor C) {
8454 if (!clang_isDeclaration(C.kind))
8455 return 0;
8456
8457 if (const auto D = cxcursor::getCursorDecl(C))
8458 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8459 return FD->isMutable() ? 1 : 0;
8460 return 0;
8461}
8462
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008463unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8464 if (!clang_isDeclaration(C.kind))
8465 return 0;
8466
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008467 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008468 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008469 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008470 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8471}
8472
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008473unsigned clang_CXXMethod_isConst(CXCursor C) {
8474 if (!clang_isDeclaration(C.kind))
8475 return 0;
8476
8477 const Decl *D = cxcursor::getCursorDecl(C);
8478 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008479 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008480 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008481}
8482
Jonathan Coe29565352016-04-27 12:48:25 +00008483unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8484 if (!clang_isDeclaration(C.kind))
8485 return 0;
8486
8487 const Decl *D = cxcursor::getCursorDecl(C);
8488 const CXXMethodDecl *Method =
8489 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8490 return (Method && Method->isDefaulted()) ? 1 : 0;
8491}
8492
Guy Benyei11169dd2012-12-18 14:30:41 +00008493unsigned clang_CXXMethod_isStatic(CXCursor C) {
8494 if (!clang_isDeclaration(C.kind))
8495 return 0;
8496
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008497 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008498 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008499 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008500 return (Method && Method->isStatic()) ? 1 : 0;
8501}
8502
8503unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8504 if (!clang_isDeclaration(C.kind))
8505 return 0;
8506
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008507 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008508 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008509 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008510 return (Method && Method->isVirtual()) ? 1 : 0;
8511}
Guy Benyei11169dd2012-12-18 14:30:41 +00008512
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008513unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8514 if (!clang_isDeclaration(C.kind))
8515 return 0;
8516
8517 const auto *D = cxcursor::getCursorDecl(C);
8518 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8519 if (RD)
8520 RD = RD->getDefinition();
8521 return (RD && RD->isAbstract()) ? 1 : 0;
8522}
8523
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008524unsigned clang_EnumDecl_isScoped(CXCursor C) {
8525 if (!clang_isDeclaration(C.kind))
8526 return 0;
8527
8528 const Decl *D = cxcursor::getCursorDecl(C);
8529 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8530 return (Enum && Enum->isScoped()) ? 1 : 0;
8531}
8532
Guy Benyei11169dd2012-12-18 14:30:41 +00008533//===----------------------------------------------------------------------===//
8534// Attribute introspection.
8535//===----------------------------------------------------------------------===//
8536
Guy Benyei11169dd2012-12-18 14:30:41 +00008537CXType clang_getIBOutletCollectionType(CXCursor C) {
8538 if (C.kind != CXCursor_IBOutletCollectionAttr)
8539 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8540
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008541 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008542 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8543
8544 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8545}
Guy Benyei11169dd2012-12-18 14:30:41 +00008546
8547//===----------------------------------------------------------------------===//
8548// Inspecting memory usage.
8549//===----------------------------------------------------------------------===//
8550
8551typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8552
8553static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8554 enum CXTUResourceUsageKind k,
8555 unsigned long amount) {
8556 CXTUResourceUsageEntry entry = { k, amount };
8557 entries.push_back(entry);
8558}
8559
Guy Benyei11169dd2012-12-18 14:30:41 +00008560const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8561 const char *str = "";
8562 switch (kind) {
8563 case CXTUResourceUsage_AST:
8564 str = "ASTContext: expressions, declarations, and types";
8565 break;
8566 case CXTUResourceUsage_Identifiers:
8567 str = "ASTContext: identifiers";
8568 break;
8569 case CXTUResourceUsage_Selectors:
8570 str = "ASTContext: selectors";
8571 break;
8572 case CXTUResourceUsage_GlobalCompletionResults:
8573 str = "Code completion: cached global results";
8574 break;
8575 case CXTUResourceUsage_SourceManagerContentCache:
8576 str = "SourceManager: content cache allocator";
8577 break;
8578 case CXTUResourceUsage_AST_SideTables:
8579 str = "ASTContext: side tables";
8580 break;
8581 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8582 str = "SourceManager: malloc'ed memory buffers";
8583 break;
8584 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8585 str = "SourceManager: mmap'ed memory buffers";
8586 break;
8587 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8588 str = "ExternalASTSource: malloc'ed memory buffers";
8589 break;
8590 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8591 str = "ExternalASTSource: mmap'ed memory buffers";
8592 break;
8593 case CXTUResourceUsage_Preprocessor:
8594 str = "Preprocessor: malloc'ed memory";
8595 break;
8596 case CXTUResourceUsage_PreprocessingRecord:
8597 str = "Preprocessor: PreprocessingRecord";
8598 break;
8599 case CXTUResourceUsage_SourceManager_DataStructures:
8600 str = "SourceManager: data structures and tables";
8601 break;
8602 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8603 str = "Preprocessor: header search tables";
8604 break;
8605 }
8606 return str;
8607}
8608
8609CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008610 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008611 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008612 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008613 return usage;
8614 }
8615
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008616 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008617 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008618 ASTContext &astContext = astUnit->getASTContext();
8619
8620 // How much memory is used by AST nodes and types?
8621 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8622 (unsigned long) astContext.getASTAllocatedMemory());
8623
8624 // How much memory is used by identifiers?
8625 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8626 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8627
8628 // How much memory is used for selectors?
8629 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8630 (unsigned long) astContext.Selectors.getTotalMemory());
8631
8632 // How much memory is used by ASTContext's side tables?
8633 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8634 (unsigned long) astContext.getSideTableAllocatedMemory());
8635
8636 // How much memory is used for caching global code completion results?
8637 unsigned long completionBytes = 0;
8638 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008639 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008640 completionBytes = completionAllocator->getTotalMemory();
8641 }
8642 createCXTUResourceUsageEntry(*entries,
8643 CXTUResourceUsage_GlobalCompletionResults,
8644 completionBytes);
8645
8646 // How much memory is being used by SourceManager's content cache?
8647 createCXTUResourceUsageEntry(*entries,
8648 CXTUResourceUsage_SourceManagerContentCache,
8649 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8650
8651 // How much memory is being used by the MemoryBuffer's in SourceManager?
8652 const SourceManager::MemoryBufferSizes &srcBufs =
8653 astUnit->getSourceManager().getMemoryBufferSizes();
8654
8655 createCXTUResourceUsageEntry(*entries,
8656 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8657 (unsigned long) srcBufs.malloc_bytes);
8658 createCXTUResourceUsageEntry(*entries,
8659 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8660 (unsigned long) srcBufs.mmap_bytes);
8661 createCXTUResourceUsageEntry(*entries,
8662 CXTUResourceUsage_SourceManager_DataStructures,
8663 (unsigned long) astContext.getSourceManager()
8664 .getDataStructureSizes());
8665
8666 // How much memory is being used by the ExternalASTSource?
8667 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8668 const ExternalASTSource::MemoryBufferSizes &sizes =
8669 esrc->getMemoryBufferSizes();
8670
8671 createCXTUResourceUsageEntry(*entries,
8672 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8673 (unsigned long) sizes.malloc_bytes);
8674 createCXTUResourceUsageEntry(*entries,
8675 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8676 (unsigned long) sizes.mmap_bytes);
8677 }
8678
8679 // How much memory is being used by the Preprocessor?
8680 Preprocessor &pp = astUnit->getPreprocessor();
8681 createCXTUResourceUsageEntry(*entries,
8682 CXTUResourceUsage_Preprocessor,
8683 pp.getTotalMemory());
8684
8685 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8686 createCXTUResourceUsageEntry(*entries,
8687 CXTUResourceUsage_PreprocessingRecord,
8688 pRec->getTotalMemory());
8689 }
8690
8691 createCXTUResourceUsageEntry(*entries,
8692 CXTUResourceUsage_Preprocessor_HeaderSearch,
8693 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008694
Guy Benyei11169dd2012-12-18 14:30:41 +00008695 CXTUResourceUsage usage = { (void*) entries.get(),
8696 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008697 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008698 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008699 return usage;
8700}
8701
8702void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8703 if (usage.data)
8704 delete (MemUsageEntries*) usage.data;
8705}
8706
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008707CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8708 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008709 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008710 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008711
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008712 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008713 LOG_BAD_TU(TU);
8714 return skipped;
8715 }
8716
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008717 if (!file)
8718 return skipped;
8719
8720 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8721 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8722 if (!ppRec)
8723 return skipped;
8724
8725 ASTContext &Ctx = astUnit->getASTContext();
8726 SourceManager &sm = Ctx.getSourceManager();
8727 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8728 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008729 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008730
8731 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8732 std::vector<SourceRange> wantedRanges;
8733 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8734 i != ei; ++i) {
8735 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8736 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008737 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8738 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008739 }
8740
8741 skipped->count = wantedRanges.size();
8742 skipped->ranges = new CXSourceRange[skipped->count];
8743 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8744 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8745
8746 return skipped;
8747}
8748
Cameron Desrochersd8091282016-08-18 15:43:55 +00008749CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8750 CXSourceRangeList *skipped = new CXSourceRangeList;
8751 skipped->count = 0;
8752 skipped->ranges = nullptr;
8753
8754 if (isNotUsableTU(TU)) {
8755 LOG_BAD_TU(TU);
8756 return skipped;
8757 }
8758
8759 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8760 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8761 if (!ppRec)
8762 return skipped;
8763
8764 ASTContext &Ctx = astUnit->getASTContext();
8765
8766 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8767
8768 skipped->count = SkippedRanges.size();
8769 skipped->ranges = new CXSourceRange[skipped->count];
8770 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8771 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8772
8773 return skipped;
8774}
8775
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008776void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8777 if (ranges) {
8778 delete[] ranges->ranges;
8779 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008780 }
8781}
8782
Guy Benyei11169dd2012-12-18 14:30:41 +00008783void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8784 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8785 for (unsigned I = 0; I != Usage.numEntries; ++I)
8786 fprintf(stderr, " %s: %lu\n",
8787 clang_getTUResourceUsageName(Usage.entries[I].kind),
8788 Usage.entries[I].amount);
8789
8790 clang_disposeCXTUResourceUsage(Usage);
8791}
8792
8793//===----------------------------------------------------------------------===//
8794// Misc. utility functions.
8795//===----------------------------------------------------------------------===//
8796
Richard Smith0a7b2972018-07-03 21:34:13 +00008797/// Default to using our desired 8 MB stack size on "safety" threads.
8798static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008799
8800namespace clang {
8801
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008802bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008803 unsigned Size) {
8804 if (!Size)
8805 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008806 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008807 return CRC.RunSafelyOnThread(Fn, Size);
8808 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008809}
8810
8811unsigned GetSafetyThreadStackSize() {
8812 return SafetyStackThreadSize;
8813}
8814
8815void SetSafetyThreadStackSize(unsigned Value) {
8816 SafetyStackThreadSize = Value;
8817}
8818
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008819}
Guy Benyei11169dd2012-12-18 14:30:41 +00008820
8821void clang::setThreadBackgroundPriority() {
8822 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8823 return;
8824
Nico Weber18cfd9f2019-04-21 19:18:41 +00008825#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008826 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008827#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008828}
8829
8830void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8831 if (!Unit)
8832 return;
8833
8834 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8835 DEnd = Unit->stored_diag_end();
8836 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008837 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008838 CXString Msg = clang_formatDiagnostic(&Diag,
8839 clang_defaultDiagnosticDisplayOptions());
8840 fprintf(stderr, "%s\n", clang_getCString(Msg));
8841 clang_disposeString(Msg);
8842 }
Nico Weber1865df42018-04-27 19:11:14 +00008843#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008844 // On Windows, force a flush, since there may be multiple copies of
8845 // stderr and stdout in the file system, all with different buffers
8846 // but writing to the same device.
8847 fflush(stderr);
8848#endif
8849}
8850
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008851MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8852 SourceLocation MacroDefLoc,
8853 CXTranslationUnit TU){
8854 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008855 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008856 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008857 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008858
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008859 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008860 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008861 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008862 if (MD) {
8863 for (MacroDirective::DefInfo
8864 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8865 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8866 return Def.getMacroInfo();
8867 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008868 }
8869
Craig Topper69186e72014-06-08 08:38:04 +00008870 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008871}
8872
Richard Smith66a81862015-05-04 02:25:31 +00008873const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008874 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008875 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008876 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008877 const IdentifierInfo *II = MacroDef->getName();
8878 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008879 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008880
8881 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8882}
8883
Richard Smith66a81862015-05-04 02:25:31 +00008884MacroDefinitionRecord *
8885cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8886 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008887 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008888 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008889 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008890 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008891
8892 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008893 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008894 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8895 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008896 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008897
8898 // Check that the token is inside the definition and not its argument list.
8899 SourceManager &SM = Unit->getSourceManager();
8900 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008901 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008902 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008903 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008904
8905 Preprocessor &PP = Unit->getPreprocessor();
8906 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8907 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008908 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008909
Alp Toker2d57cea2014-05-17 04:53:25 +00008910 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008911 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008912 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008913
8914 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008915 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008916 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008917
Richard Smith20e883e2015-04-29 23:20:19 +00008918 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008919 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008920 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008921
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008922 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008923}
8924
Richard Smith66a81862015-05-04 02:25:31 +00008925MacroDefinitionRecord *
8926cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8927 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008928 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008929 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008930
8931 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008932 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008933 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008934 Preprocessor &PP = Unit->getPreprocessor();
8935 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008936 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008937 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8938 Token Tok;
8939 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008940 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008941
8942 return checkForMacroInMacroDefinition(MI, Tok, TU);
8943}
8944
Guy Benyei11169dd2012-12-18 14:30:41 +00008945CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008946 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008947}
8948
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008949Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8950 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008951 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008952 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008953 if (Unit->isMainFileAST())
8954 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008955 return *this;
8956 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008957 } else {
8958 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008959 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008960 return *this;
8961}
8962
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008963Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8964 *this << FE->getName();
8965 return *this;
8966}
8967
8968Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8969 CXString cursorName = clang_getCursorDisplayName(cursor);
8970 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8971 clang_disposeString(cursorName);
8972 return *this;
8973}
8974
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008975Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8976 CXFile File;
8977 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008978 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008979 CXString FileName = clang_getFileName(File);
8980 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8981 clang_disposeString(FileName);
8982 return *this;
8983}
8984
8985Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8986 CXSourceLocation BLoc = clang_getRangeStart(range);
8987 CXSourceLocation ELoc = clang_getRangeEnd(range);
8988
8989 CXFile BFile;
8990 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008991 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008992
8993 CXFile EFile;
8994 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008995 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008996
8997 CXString BFileName = clang_getFileName(BFile);
8998 if (BFile == EFile) {
8999 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
9000 BLine, BColumn, ELine, EColumn);
9001 } else {
9002 CXString EFileName = clang_getFileName(EFile);
9003 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
9004 BLine, BColumn)
9005 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
9006 ELine, EColumn);
9007 clang_disposeString(EFileName);
9008 }
9009 clang_disposeString(BFileName);
9010 return *this;
9011}
9012
9013Logger &cxindex::Logger::operator<<(CXString Str) {
9014 *this << clang_getCString(Str);
9015 return *this;
9016}
9017
9018Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
9019 LogOS << Fmt;
9020 return *this;
9021}
9022
Benjamin Kramer762bc332019-08-07 14:44:40 +00009023static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00009024
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009025cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00009026 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009027
9028 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
9029
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009030 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009031 OS << "[libclang:" << Name << ':';
9032
Alp Toker1a86ad22014-07-06 06:24:00 +00009033#ifdef USE_DARWIN_THREADS
9034 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009035 mach_port_t tid = pthread_mach_thread_np(pthread_self());
9036 OS << tid << ':';
9037#endif
9038
9039 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
9040 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00009041 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009042
9043 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00009044 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009045 OS << "--------------------------------------------------\n";
9046 }
9047}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00009048
9049#ifdef CLANG_TOOL_EXTRA_BUILD
9050// This anchor is used to force the linker to link the clang-tidy plugin.
9051extern volatile int ClangTidyPluginAnchorSource;
9052static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9053 ClangTidyPluginAnchorSource;
9054
9055// This anchor is used to force the linker to link the clang-include-fixer
9056// plugin.
9057extern volatile int ClangIncludeFixerPluginAnchorSource;
9058static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9059 ClangIncludeFixerPluginAnchorSource;
9060#endif