blob: 6f32240fe6e48b8ea621c35883f04f1008e51a34 [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 Bataev9a8defc2020-02-11 11:10:43 -05002244void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {}
2245
Alexey Bataev346265e2015-09-25 10:37:12 +00002246void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2247
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002248void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2249
Alexey Bataevb825de12015-12-07 10:51:44 +00002250void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2251
Kelvin Li1408f912018-09-26 04:28:39 +00002252void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2253 const OMPUnifiedAddressClause *) {}
2254
Patrick Lyster4a370b92018-10-01 13:47:43 +00002255void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2256 const OMPUnifiedSharedMemoryClause *) {}
2257
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002258void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2259 const OMPReverseOffloadClause *) {}
2260
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002261void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2262 const OMPDynamicAllocatorsClause *) {}
2263
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002264void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2265 const OMPAtomicDefaultMemOrderClause *) {}
2266
Michael Wonge710d542015-08-07 16:16:36 +00002267void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2268 Visitor->AddStmt(C->getDevice());
2269}
2270
Kelvin Li099bb8c2015-11-24 20:50:12 +00002271void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002272 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002273 Visitor->AddStmt(C->getNumTeams());
2274}
2275
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002276void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002277 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002278 Visitor->AddStmt(C->getThreadLimit());
2279}
2280
Alexey Bataeva0569352015-12-01 10:17:31 +00002281void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2282 Visitor->AddStmt(C->getPriority());
2283}
2284
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002285void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2286 Visitor->AddStmt(C->getGrainsize());
2287}
2288
Alexey Bataev382967a2015-12-08 12:06:20 +00002289void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2290 Visitor->AddStmt(C->getNumTasks());
2291}
2292
Alexey Bataev28c75412015-12-15 08:19:24 +00002293void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2294 Visitor->AddStmt(C->getHint());
2295}
2296
Alexey Bataev756c1962013-09-24 03:17:45 +00002297template<typename T>
2298void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002299 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002300 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002301 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002302}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002303
Alexey Bataeve04483e2019-03-27 14:14:31 +00002304void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2305 VisitOMPClauseList(C);
2306 Visitor->AddStmt(C->getAllocator());
2307}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002308void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002309 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002310 for (const auto *E : C->private_copies()) {
2311 Visitor->AddStmt(E);
2312 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002313}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002314void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2315 const OMPFirstprivateClause *C) {
2316 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002317 VisitOMPClauseWithPreInit(C);
2318 for (const auto *E : C->private_copies()) {
2319 Visitor->AddStmt(E);
2320 }
2321 for (const auto *E : C->inits()) {
2322 Visitor->AddStmt(E);
2323 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002324}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002325void OMPClauseEnqueue::VisitOMPLastprivateClause(
2326 const OMPLastprivateClause *C) {
2327 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002328 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002329 for (auto *E : C->private_copies()) {
2330 Visitor->AddStmt(E);
2331 }
2332 for (auto *E : C->source_exprs()) {
2333 Visitor->AddStmt(E);
2334 }
2335 for (auto *E : C->destination_exprs()) {
2336 Visitor->AddStmt(E);
2337 }
2338 for (auto *E : C->assignment_ops()) {
2339 Visitor->AddStmt(E);
2340 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002341}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002342void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002343 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002344}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002345void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2346 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002347 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002348 for (auto *E : C->privates()) {
2349 Visitor->AddStmt(E);
2350 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002351 for (auto *E : C->lhs_exprs()) {
2352 Visitor->AddStmt(E);
2353 }
2354 for (auto *E : C->rhs_exprs()) {
2355 Visitor->AddStmt(E);
2356 }
2357 for (auto *E : C->reduction_ops()) {
2358 Visitor->AddStmt(E);
2359 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002360}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002361void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2362 const OMPTaskReductionClause *C) {
2363 VisitOMPClauseList(C);
2364 VisitOMPClauseWithPostUpdate(C);
2365 for (auto *E : C->privates()) {
2366 Visitor->AddStmt(E);
2367 }
2368 for (auto *E : C->lhs_exprs()) {
2369 Visitor->AddStmt(E);
2370 }
2371 for (auto *E : C->rhs_exprs()) {
2372 Visitor->AddStmt(E);
2373 }
2374 for (auto *E : C->reduction_ops()) {
2375 Visitor->AddStmt(E);
2376 }
2377}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002378void OMPClauseEnqueue::VisitOMPInReductionClause(
2379 const OMPInReductionClause *C) {
2380 VisitOMPClauseList(C);
2381 VisitOMPClauseWithPostUpdate(C);
2382 for (auto *E : C->privates()) {
2383 Visitor->AddStmt(E);
2384 }
2385 for (auto *E : C->lhs_exprs()) {
2386 Visitor->AddStmt(E);
2387 }
2388 for (auto *E : C->rhs_exprs()) {
2389 Visitor->AddStmt(E);
2390 }
2391 for (auto *E : C->reduction_ops()) {
2392 Visitor->AddStmt(E);
2393 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002394 for (auto *E : C->taskgroup_descriptors())
2395 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002396}
Alexander Musman8dba6642014-04-22 13:09:42 +00002397void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2398 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002399 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002400 for (const auto *E : C->privates()) {
2401 Visitor->AddStmt(E);
2402 }
Alexander Musman3276a272015-03-21 10:12:56 +00002403 for (const auto *E : C->inits()) {
2404 Visitor->AddStmt(E);
2405 }
2406 for (const auto *E : C->updates()) {
2407 Visitor->AddStmt(E);
2408 }
2409 for (const auto *E : C->finals()) {
2410 Visitor->AddStmt(E);
2411 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002412 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002413 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002414}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002415void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2416 VisitOMPClauseList(C);
2417 Visitor->AddStmt(C->getAlignment());
2418}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002419void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2420 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002421 for (auto *E : C->source_exprs()) {
2422 Visitor->AddStmt(E);
2423 }
2424 for (auto *E : C->destination_exprs()) {
2425 Visitor->AddStmt(E);
2426 }
2427 for (auto *E : C->assignment_ops()) {
2428 Visitor->AddStmt(E);
2429 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002430}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002431void
2432OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2433 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002434 for (auto *E : C->source_exprs()) {
2435 Visitor->AddStmt(E);
2436 }
2437 for (auto *E : C->destination_exprs()) {
2438 Visitor->AddStmt(E);
2439 }
2440 for (auto *E : C->assignment_ops()) {
2441 Visitor->AddStmt(E);
2442 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002443}
Alexey Bataev6125da92014-07-21 11:26:11 +00002444void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2445 VisitOMPClauseList(C);
2446}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002447void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2448 VisitOMPClauseList(C);
2449}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002450void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2451 VisitOMPClauseList(C);
2452}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002453void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2454 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002455 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002456 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002457}
Alexey Bataev3392d762016-02-16 11:18:12 +00002458void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2459 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002460void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2461 VisitOMPClauseList(C);
2462}
Samuel Antaoec172c62016-05-26 17:49:04 +00002463void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2464 VisitOMPClauseList(C);
2465}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002466void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2467 VisitOMPClauseList(C);
2468}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002469void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2470 VisitOMPClauseList(C);
2471}
Alexey Bataevb6e70842019-12-16 15:54:17 -05002472void OMPClauseEnqueue::VisitOMPNontemporalClause(
2473 const OMPNontemporalClause *C) {
2474 VisitOMPClauseList(C);
Alexey Bataev0860db92019-12-19 10:01:10 -05002475 for (const auto *E : C->private_refs())
2476 Visitor->AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05002477}
Alexey Bataevcb8e6912020-01-31 16:09:26 -05002478void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002479}
Alexey Bataev756c1962013-09-24 03:17:45 +00002480
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002481void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2482 unsigned size = WL.size();
2483 OMPClauseEnqueue Visitor(this);
2484 Visitor.Visit(S);
2485 if (size == WL.size())
2486 return;
2487 // Now reverse the entries we just added. This will match the DFS
2488 // ordering performed by the worklist.
2489 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2490 std::reverse(I, E);
2491}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002492void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2494}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002495void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 AddDecl(B->getBlockDecl());
2497}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002498void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 EnqueueChildren(E);
2500 AddTypeLoc(E->getTypeSourceInfo());
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002503 for (auto &I : llvm::reverse(S->body()))
2504 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002505}
2506void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002507VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 AddStmt(S->getSubStmt());
2509 AddDeclarationNameInfo(S);
2510 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2511 AddNestedNameSpecifierLoc(QualifierLoc);
2512}
2513
2514void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002515VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002516 if (E->hasExplicitTemplateArgs())
2517 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 AddDeclarationNameInfo(E);
2519 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2520 AddNestedNameSpecifierLoc(QualifierLoc);
2521 if (!E->isImplicitAccess())
2522 AddStmt(E->getBase());
2523}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002524void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 // Enqueue the initializer , if any.
2526 AddStmt(E->getInitializer());
2527 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002528 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 // Enqueue the allocated type.
2530 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2531 // Enqueue the placement arguments.
2532 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2533 AddStmt(E->getPlacementArg(I-1));
2534}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002535void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2537 AddStmt(CE->getArg(I-1));
2538 AddStmt(CE->getCallee());
2539 AddStmt(CE->getArg(0));
2540}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002541void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2542 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 // Visit the name of the type being destroyed.
2544 AddTypeLoc(E->getDestroyedTypeInfo());
2545 // Visit the scope type that looks disturbingly like the nested-name-specifier
2546 // but isn't.
2547 AddTypeLoc(E->getScopeTypeInfo());
2548 // Visit the nested-name-specifier.
2549 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2550 AddNestedNameSpecifierLoc(QualifierLoc);
2551 // Visit base expression.
2552 AddStmt(E->getBase());
2553}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002554void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2555 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 AddTypeLoc(E->getTypeSourceInfo());
2557}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002558void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2559 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 EnqueueChildren(E);
2561 AddTypeLoc(E->getTypeSourceInfo());
2562}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002563void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 EnqueueChildren(E);
2565 if (E->isTypeOperand())
2566 AddTypeLoc(E->getTypeOperandSourceInfo());
2567}
2568
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002569void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2570 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 EnqueueChildren(E);
2572 AddTypeLoc(E->getTypeSourceInfo());
2573}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002574void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 EnqueueChildren(E);
2576 if (E->isTypeOperand())
2577 AddTypeLoc(E->getTypeOperandSourceInfo());
2578}
2579
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002580void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 EnqueueChildren(S);
2582 AddDecl(S->getExceptionDecl());
2583}
2584
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002585void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002586 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002587 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002588 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002589}
2590
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002591void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002592 if (DR->hasExplicitTemplateArgs())
2593 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 WL.push_back(DeclRefExprParts(DR, Parent));
2595}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002596void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2597 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002598 if (E->hasExplicitTemplateArgs())
2599 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 AddDeclarationNameInfo(E);
2601 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2602}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002603void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 unsigned size = WL.size();
2605 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002606 for (const auto *D : S->decls()) {
2607 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 isFirst = false;
2609 }
2610 if (size == WL.size())
2611 return;
2612 // Now reverse the entries we just added. This will match the DFS
2613 // ordering performed by the worklist.
2614 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2615 std::reverse(I, E);
2616}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002617void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002619 for (const DesignatedInitExpr::Designator &D :
2620 llvm::reverse(E->designators())) {
2621 if (D.isFieldDesignator()) {
2622 if (FieldDecl *Field = D.getField())
2623 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 continue;
2625 }
David Majnemerf7e36092016-06-23 00:15:04 +00002626 if (D.isArrayDesignator()) {
2627 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 continue;
2629 }
David Majnemerf7e36092016-06-23 00:15:04 +00002630 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2631 AddStmt(E->getArrayRangeEnd(D));
2632 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 }
2634}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002635void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 EnqueueChildren(E);
2637 AddTypeLoc(E->getTypeInfoAsWritten());
2638}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002639void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 AddStmt(FS->getBody());
2641 AddStmt(FS->getInc());
2642 AddStmt(FS->getCond());
2643 AddDecl(FS->getConditionVariable());
2644 AddStmt(FS->getInit());
2645}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002646void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2648}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002649void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 AddStmt(If->getElse());
2651 AddStmt(If->getThen());
2652 AddStmt(If->getCond());
2653 AddDecl(If->getConditionVariable());
2654}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002655void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 // We care about the syntactic form of the initializer list, only.
2657 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2658 IE = Syntactic;
2659 EnqueueChildren(IE);
2660}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002661void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 WL.push_back(MemberExprParts(M, Parent));
2663
2664 // If the base of the member access expression is an implicit 'this', don't
2665 // visit it.
2666 // FIXME: If we ever want to show these implicit accesses, this will be
2667 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002668 if (M->isImplicitAccess())
2669 return;
2670
2671 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002672 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002673 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2674 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2675 if (FD->isAnonymousStructOrUnion()) {
2676 AddStmt(SubME->getBase());
2677 return;
2678 }
2679 }
2680 }
2681
2682 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002683}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002684void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 AddTypeLoc(E->getEncodedTypeSourceInfo());
2686}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002687void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 EnqueueChildren(M);
2689 AddTypeLoc(M->getClassReceiverTypeInfo());
2690}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002691void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 // Visit the components of the offsetof expression.
2693 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 const OffsetOfNode &Node = E->getComponent(I-1);
2695 switch (Node.getKind()) {
2696 case OffsetOfNode::Array:
2697 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2698 break;
2699 case OffsetOfNode::Field:
2700 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2701 break;
2702 case OffsetOfNode::Identifier:
2703 case OffsetOfNode::Base:
2704 continue;
2705 }
2706 }
2707 // Visit the type into which we're computing the offset.
2708 AddTypeLoc(E->getTypeSourceInfo());
2709}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002710void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002711 if (E->hasExplicitTemplateArgs())
2712 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 WL.push_back(OverloadExprParts(E, Parent));
2714}
2715void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002716 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 EnqueueChildren(E);
2718 if (E->isArgumentType())
2719 AddTypeLoc(E->getArgumentTypeInfo());
2720}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002721void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002722 EnqueueChildren(S);
2723}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002724void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 AddStmt(S->getBody());
2726 AddStmt(S->getCond());
2727 AddDecl(S->getConditionVariable());
2728}
2729
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002730void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002731 AddStmt(W->getBody());
2732 AddStmt(W->getCond());
2733 AddDecl(W->getConditionVariable());
2734}
2735
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002736void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 for (unsigned I = E->getNumArgs(); I > 0; --I)
2738 AddTypeLoc(E->getArg(I-1));
2739}
2740
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002741void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 AddTypeLoc(E->getQueriedTypeSourceInfo());
2743}
2744
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002745void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002746 EnqueueChildren(E);
2747}
2748
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002749void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002750 VisitOverloadExpr(U);
2751 if (!U->isImplicitAccess())
2752 AddStmt(U->getBase());
2753}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002754void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 AddStmt(E->getSubExpr());
2756 AddTypeLoc(E->getWrittenTypeInfo());
2757}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002758void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 WL.push_back(SizeOfPackExprParts(E, Parent));
2760}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002761void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 // If the opaque value has a source expression, just transparently
2763 // visit that. This is useful for (e.g.) pseudo-object expressions.
2764 if (Expr *SourceExpr = E->getSourceExpr())
2765 return Visit(SourceExpr);
2766}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002767void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 AddStmt(E->getBody());
2769 WL.push_back(LambdaExprParts(E, Parent));
2770}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002771void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 // Treat the expression like its syntactic form.
2773 Visit(E->getSyntacticForm());
2774}
2775
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002776void EnqueueVisitor::VisitOMPExecutableDirective(
2777 const OMPExecutableDirective *D) {
2778 EnqueueChildren(D);
2779 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2780 E = D->clauses().end();
2781 I != E; ++I)
2782 EnqueueChildren(*I);
2783}
2784
Alexander Musman3aaab662014-08-19 11:27:13 +00002785void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2786 VisitOMPExecutableDirective(D);
2787}
2788
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002789void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2790 VisitOMPExecutableDirective(D);
2791}
2792
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002793void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002794 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002795}
2796
Alexey Bataevf29276e2014-06-18 04:14:57 +00002797void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002798 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002799}
2800
Alexander Musmanf82886e2014-09-18 05:12:34 +00002801void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2802 VisitOMPLoopDirective(D);
2803}
2804
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002805void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2806 VisitOMPExecutableDirective(D);
2807}
2808
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002809void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2810 VisitOMPExecutableDirective(D);
2811}
2812
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002813void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2814 VisitOMPExecutableDirective(D);
2815}
2816
Alexander Musman80c22892014-07-17 08:54:58 +00002817void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819}
2820
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002821void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2822 VisitOMPExecutableDirective(D);
2823 AddDeclarationNameInfo(D);
2824}
2825
Alexey Bataev4acb8592014-07-07 13:01:15 +00002826void
2827EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002828 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002829}
2830
Alexander Musmane4e893b2014-09-23 09:33:00 +00002831void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2832 const OMPParallelForSimdDirective *D) {
2833 VisitOMPLoopDirective(D);
2834}
2835
cchen47d60942019-12-05 13:43:48 -05002836void EnqueueVisitor::VisitOMPParallelMasterDirective(
2837 const OMPParallelMasterDirective *D) {
2838 VisitOMPExecutableDirective(D);
2839}
2840
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002841void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2842 const OMPParallelSectionsDirective *D) {
2843 VisitOMPExecutableDirective(D);
2844}
2845
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002846void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2847 VisitOMPExecutableDirective(D);
2848}
2849
Alexey Bataev68446b72014-07-18 07:47:19 +00002850void
2851EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2852 VisitOMPExecutableDirective(D);
2853}
2854
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002855void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2856 VisitOMPExecutableDirective(D);
2857}
2858
Alexey Bataev2df347a2014-07-18 10:17:07 +00002859void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2860 VisitOMPExecutableDirective(D);
2861}
2862
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002863void EnqueueVisitor::VisitOMPTaskgroupDirective(
2864 const OMPTaskgroupDirective *D) {
2865 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002866 if (const Expr *E = D->getReductionRef())
2867 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002868}
2869
Alexey Bataev6125da92014-07-21 11:26:11 +00002870void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2871 VisitOMPExecutableDirective(D);
2872}
2873
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002874void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2875 VisitOMPExecutableDirective(D);
2876}
2877
Alexey Bataev0162e452014-07-22 10:10:35 +00002878void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2879 VisitOMPExecutableDirective(D);
2880}
2881
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002882void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2883 VisitOMPExecutableDirective(D);
2884}
2885
Michael Wong65f367f2015-07-21 13:44:28 +00002886void EnqueueVisitor::VisitOMPTargetDataDirective(const
2887 OMPTargetDataDirective *D) {
2888 VisitOMPExecutableDirective(D);
2889}
2890
Samuel Antaodf67fc42016-01-19 19:15:56 +00002891void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2892 const OMPTargetEnterDataDirective *D) {
2893 VisitOMPExecutableDirective(D);
2894}
2895
Samuel Antao72590762016-01-19 20:04:50 +00002896void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2897 const OMPTargetExitDataDirective *D) {
2898 VisitOMPExecutableDirective(D);
2899}
2900
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002901void EnqueueVisitor::VisitOMPTargetParallelDirective(
2902 const OMPTargetParallelDirective *D) {
2903 VisitOMPExecutableDirective(D);
2904}
2905
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002906void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2907 const OMPTargetParallelForDirective *D) {
2908 VisitOMPLoopDirective(D);
2909}
2910
Alexey Bataev13314bf2014-10-09 04:18:56 +00002911void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2912 VisitOMPExecutableDirective(D);
2913}
2914
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002915void EnqueueVisitor::VisitOMPCancellationPointDirective(
2916 const OMPCancellationPointDirective *D) {
2917 VisitOMPExecutableDirective(D);
2918}
2919
Alexey Bataev80909872015-07-02 11:25:17 +00002920void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2921 VisitOMPExecutableDirective(D);
2922}
2923
Alexey Bataev49f6e782015-12-01 04:18:41 +00002924void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2925 VisitOMPLoopDirective(D);
2926}
2927
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002928void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2929 const OMPTaskLoopSimdDirective *D) {
2930 VisitOMPLoopDirective(D);
2931}
2932
Alexey Bataev60e51c42019-10-10 20:13:02 +00002933void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2934 const OMPMasterTaskLoopDirective *D) {
2935 VisitOMPLoopDirective(D);
2936}
2937
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002938void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2939 const OMPMasterTaskLoopSimdDirective *D) {
2940 VisitOMPLoopDirective(D);
2941}
2942
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002943void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2944 const OMPParallelMasterTaskLoopDirective *D) {
2945 VisitOMPLoopDirective(D);
2946}
2947
Alexey Bataev14a388f2019-10-25 10:27:13 -04002948void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
2949 const OMPParallelMasterTaskLoopSimdDirective *D) {
2950 VisitOMPLoopDirective(D);
2951}
2952
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002953void EnqueueVisitor::VisitOMPDistributeDirective(
2954 const OMPDistributeDirective *D) {
2955 VisitOMPLoopDirective(D);
2956}
2957
Carlo Bertolli9925f152016-06-27 14:55:37 +00002958void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2959 const OMPDistributeParallelForDirective *D) {
2960 VisitOMPLoopDirective(D);
2961}
2962
Kelvin Li4a39add2016-07-05 05:00:15 +00002963void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2964 const OMPDistributeParallelForSimdDirective *D) {
2965 VisitOMPLoopDirective(D);
2966}
2967
Kelvin Li787f3fc2016-07-06 04:45:38 +00002968void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2969 const OMPDistributeSimdDirective *D) {
2970 VisitOMPLoopDirective(D);
2971}
2972
Kelvin Lia579b912016-07-14 02:54:56 +00002973void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2974 const OMPTargetParallelForSimdDirective *D) {
2975 VisitOMPLoopDirective(D);
2976}
2977
Kelvin Li986330c2016-07-20 22:57:10 +00002978void EnqueueVisitor::VisitOMPTargetSimdDirective(
2979 const OMPTargetSimdDirective *D) {
2980 VisitOMPLoopDirective(D);
2981}
2982
Kelvin Li02532872016-08-05 14:37:37 +00002983void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2984 const OMPTeamsDistributeDirective *D) {
2985 VisitOMPLoopDirective(D);
2986}
2987
Kelvin Li4e325f72016-10-25 12:50:55 +00002988void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2989 const OMPTeamsDistributeSimdDirective *D) {
2990 VisitOMPLoopDirective(D);
2991}
2992
Kelvin Li579e41c2016-11-30 23:51:03 +00002993void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2994 const OMPTeamsDistributeParallelForSimdDirective *D) {
2995 VisitOMPLoopDirective(D);
2996}
2997
Kelvin Li7ade93f2016-12-09 03:24:30 +00002998void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2999 const OMPTeamsDistributeParallelForDirective *D) {
3000 VisitOMPLoopDirective(D);
3001}
3002
Kelvin Libf594a52016-12-17 05:48:59 +00003003void EnqueueVisitor::VisitOMPTargetTeamsDirective(
3004 const OMPTargetTeamsDirective *D) {
3005 VisitOMPExecutableDirective(D);
3006}
3007
Kelvin Li83c451e2016-12-25 04:52:54 +00003008void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3009 const OMPTargetTeamsDistributeDirective *D) {
3010 VisitOMPLoopDirective(D);
3011}
3012
Kelvin Li80e8f562016-12-29 22:16:30 +00003013void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3014 const OMPTargetTeamsDistributeParallelForDirective *D) {
3015 VisitOMPLoopDirective(D);
3016}
3017
Kelvin Li1851df52017-01-03 05:23:48 +00003018void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3019 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3020 VisitOMPLoopDirective(D);
3021}
3022
Kelvin Lida681182017-01-10 18:08:18 +00003023void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3024 const OMPTargetTeamsDistributeSimdDirective *D) {
3025 VisitOMPLoopDirective(D);
3026}
3027
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003028void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
3030}
3031
3032bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3033 if (RegionOfInterest.isValid()) {
3034 SourceRange Range = getRawCursorExtent(C);
3035 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3036 return false;
3037 }
3038 return true;
3039}
3040
3041bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3042 while (!WL.empty()) {
3043 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003044 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003045
3046 // Set the Parent field, then back to its old value once we're done.
3047 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3048
3049 switch (LI.getKind()) {
3050 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003051 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003052 if (!D)
3053 continue;
3054
3055 // For now, perform default visitation for Decls.
3056 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3057 cast<DeclVisit>(&LI)->isFirst())))
3058 return true;
3059
3060 continue;
3061 }
3062 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003063 for (const TemplateArgumentLoc &Arg :
3064 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3065 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003066 return true;
3067 }
3068 continue;
3069 }
3070 case VisitorJob::TypeLocVisitKind: {
3071 // Perform default visitation for TypeLocs.
3072 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3073 return true;
3074 continue;
3075 }
3076 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003077 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 if (LabelStmt *stmt = LS->getStmt()) {
3079 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3080 TU))) {
3081 return true;
3082 }
3083 }
3084 continue;
3085 }
3086
3087 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3088 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3089 if (VisitNestedNameSpecifierLoc(V->get()))
3090 return true;
3091 continue;
3092 }
3093
3094 case VisitorJob::DeclarationNameInfoVisitKind: {
3095 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3096 ->get()))
3097 return true;
3098 continue;
3099 }
3100 case VisitorJob::MemberRefVisitKind: {
3101 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3102 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3103 return true;
3104 continue;
3105 }
3106 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003107 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 if (!S)
3109 continue;
3110
3111 // Update the current cursor.
3112 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3113 if (!IsInRegionOfInterest(Cursor))
3114 continue;
3115 switch (Visitor(Cursor, Parent, ClientData)) {
3116 case CXChildVisit_Break: return true;
3117 case CXChildVisit_Continue: break;
3118 case CXChildVisit_Recurse:
3119 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003120 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 EnqueueWorkList(WL, S);
3122 break;
3123 }
3124 continue;
3125 }
3126 case VisitorJob::MemberExprPartsKind: {
3127 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003128 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003129
3130 // Visit the nested-name-specifier
3131 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3132 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3133 return true;
3134
3135 // Visit the declaration name.
3136 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3137 return true;
3138
3139 // Visit the explicitly-specified template arguments, if any.
3140 if (M->hasExplicitTemplateArgs()) {
3141 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3142 *ArgEnd = Arg + M->getNumTemplateArgs();
3143 Arg != ArgEnd; ++Arg) {
3144 if (VisitTemplateArgumentLoc(*Arg))
3145 return true;
3146 }
3147 }
3148 continue;
3149 }
3150 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003151 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 // Visit nested-name-specifier, if present.
3153 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3154 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3155 return true;
3156 // Visit declaration name.
3157 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3158 return true;
3159 continue;
3160 }
3161 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003162 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 // Visit the nested-name-specifier.
3164 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3165 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3166 return true;
3167 // Visit the declaration name.
3168 if (VisitDeclarationNameInfo(O->getNameInfo()))
3169 return true;
3170 // Visit the overloaded declaration reference.
3171 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3172 return true;
3173 continue;
3174 }
3175 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003176 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 NamedDecl *Pack = E->getPack();
3178 if (isa<TemplateTypeParmDecl>(Pack)) {
3179 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3180 E->getPackLoc(), TU)))
3181 return true;
3182
3183 continue;
3184 }
3185
3186 if (isa<TemplateTemplateParmDecl>(Pack)) {
3187 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3188 E->getPackLoc(), TU)))
3189 return true;
3190
3191 continue;
3192 }
3193
3194 // Non-type template parameter packs and function parameter packs are
3195 // treated like DeclRefExpr cursors.
3196 continue;
3197 }
3198
3199 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003200 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003201 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3203 CEnd = E->explicit_capture_end();
3204 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003205 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003206 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003207
Guy Benyei11169dd2012-12-18 14:30:41 +00003208 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3209 C->getLocation(),
3210 TU)))
3211 return true;
3212 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003213 // Visit init captures
3214 for (auto InitExpr : E->capture_inits()) {
3215 if (Visit(InitExpr))
3216 return true;
3217 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003218
Haojian Wuef87c262018-12-18 15:29:12 +00003219 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003220 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003221 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3222 if (E->hasExplicitParameters()) {
3223 // Visit parameters.
3224 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3225 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003226 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003227 }
3228 if (E->hasExplicitResultType()) {
3229 // Visit result type.
3230 if (Visit(Proto.getReturnLoc()))
3231 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003232 }
3233 }
3234 break;
3235 }
3236
3237 case VisitorJob::PostChildrenVisitKind:
3238 if (PostChildrenVisitor(Parent, ClientData))
3239 return true;
3240 break;
3241 }
3242 }
3243 return false;
3244}
3245
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003246bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003247 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 if (!WorkListFreeList.empty()) {
3249 WL = WorkListFreeList.back();
3250 WL->clear();
3251 WorkListFreeList.pop_back();
3252 }
3253 else {
3254 WL = new VisitorWorkList();
3255 WorkListCache.push_back(WL);
3256 }
3257 EnqueueWorkList(*WL, S);
3258 bool result = RunVisitorWorkList(*WL);
3259 WorkListFreeList.push_back(WL);
3260 return result;
3261}
3262
3263namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003264typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003265RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3266 const DeclarationNameInfo &NI, SourceRange QLoc,
3267 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3269 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3270 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3271
3272 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3273
3274 RefNamePieces Pieces;
3275
3276 if (WantQualifier && QLoc.isValid())
3277 Pieces.push_back(QLoc);
3278
3279 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3280 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003281
3282 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3283 Pieces.push_back(*TemplateArgsLoc);
3284
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 if (Kind == DeclarationName::CXXOperatorName) {
3286 Pieces.push_back(SourceLocation::getFromRawEncoding(
3287 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3288 Pieces.push_back(SourceLocation::getFromRawEncoding(
3289 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3290 }
3291
3292 if (WantSinglePiece) {
3293 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3294 Pieces.clear();
3295 Pieces.push_back(R);
3296 }
3297
3298 return Pieces;
3299}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003300}
Guy Benyei11169dd2012-12-18 14:30:41 +00003301
3302//===----------------------------------------------------------------------===//
3303// Misc. API hooks.
3304//===----------------------------------------------------------------------===//
3305
Chandler Carruth66660742014-06-27 16:37:27 +00003306namespace {
3307struct RegisterFatalErrorHandler {
3308 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003309 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003310 }
3311};
3312}
3313
3314static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3315
Guy Benyei11169dd2012-12-18 14:30:41 +00003316CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3317 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 // We use crash recovery to make some of our APIs more reliable, implicitly
3319 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003320 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3321 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003322
Chandler Carruth66660742014-06-27 16:37:27 +00003323 // Look through the managed static to trigger construction of the managed
3324 // static which registers our fatal error handler. This ensures it is only
3325 // registered once.
3326 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003327
Adrian Prantlbc068582015-07-08 01:00:30 +00003328 // Initialize targets for clang module support.
3329 llvm::InitializeAllTargets();
3330 llvm::InitializeAllTargetMCs();
3331 llvm::InitializeAllAsmPrinters();
3332 llvm::InitializeAllAsmParsers();
3333
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003334 CIndexer *CIdxr = new CIndexer();
3335
Guy Benyei11169dd2012-12-18 14:30:41 +00003336 if (excludeDeclarationsFromPCH)
3337 CIdxr->setOnlyLocalDecls();
3338 if (displayDiagnostics)
3339 CIdxr->setDisplayDiagnostics();
3340
3341 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3342 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3343 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3344 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3345 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3346 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3347
3348 return CIdxr;
3349}
3350
3351void clang_disposeIndex(CXIndex CIdx) {
3352 if (CIdx)
3353 delete static_cast<CIndexer *>(CIdx);
3354}
3355
3356void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3357 if (CIdx)
3358 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3359}
3360
3361unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3362 if (CIdx)
3363 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3364 return 0;
3365}
3366
Alex Lorenz08615792017-12-04 21:56:36 +00003367void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3368 const char *Path) {
3369 if (CIdx)
3370 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3371}
3372
Guy Benyei11169dd2012-12-18 14:30:41 +00003373void clang_toggleCrashRecovery(unsigned isEnabled) {
3374 if (isEnabled)
3375 llvm::CrashRecoveryContext::Enable();
3376 else
3377 llvm::CrashRecoveryContext::Disable();
3378}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003379
Guy Benyei11169dd2012-12-18 14:30:41 +00003380CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3381 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003382 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003383 enum CXErrorCode Result =
3384 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003385 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003386 assert((TU && Result == CXError_Success) ||
3387 (!TU && Result != CXError_Success));
3388 return TU;
3389}
3390
3391enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3392 const char *ast_filename,
3393 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003394 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003395 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003396
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003397 if (!CIdx || !ast_filename || !out_TU)
3398 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003399
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003400 LOG_FUNC_SECTION {
3401 *Log << ast_filename;
3402 }
3403
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3405 FileSystemOptions FileSystemOpts;
3406
Justin Bognerd512c1e2014-10-15 00:33:06 +00003407 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3408 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003409 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003410 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3411 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003412 FileSystemOpts, /*UseDebugInfo=*/false,
3413 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003414 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003415 /*AllowPCHWithCompilerErrors=*/true,
3416 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003417 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003418 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003419}
3420
3421unsigned clang_defaultEditingTranslationUnitOptions() {
3422 return CXTranslationUnit_PrecompiledPreamble |
3423 CXTranslationUnit_CacheCompletionResults;
3424}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003425
Guy Benyei11169dd2012-12-18 14:30:41 +00003426CXTranslationUnit
3427clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3428 const char *source_filename,
3429 int num_command_line_args,
3430 const char * const *command_line_args,
3431 unsigned num_unsaved_files,
3432 struct CXUnsavedFile *unsaved_files) {
3433 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3434 return clang_parseTranslationUnit(CIdx, source_filename,
3435 command_line_args, num_command_line_args,
3436 unsaved_files, num_unsaved_files,
3437 Options);
3438}
3439
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003440static CXErrorCode
3441clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3442 const char *const *command_line_args,
3443 int num_command_line_args,
3444 ArrayRef<CXUnsavedFile> unsaved_files,
3445 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003446 // Set up the initial return values.
3447 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003448 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003449
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003450 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003451 if (!CIdx || !out_TU)
3452 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003453
Guy Benyei11169dd2012-12-18 14:30:41 +00003454 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3455
3456 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3457 setThreadBackgroundPriority();
3458
3459 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003460 bool CreatePreambleOnFirstParse =
3461 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003462 // FIXME: Add a flag for modules.
3463 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003464 = (options & (CXTranslationUnit_Incomplete |
3465 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003466 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003467 = options & CXTranslationUnit_CacheCompletionResults;
3468 bool IncludeBriefCommentsInCodeCompletion
3469 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003470 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3471 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003472 bool RetainExcludedCB = options &
3473 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003474 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3475 if (options & CXTranslationUnit_SkipFunctionBodies) {
3476 SkipFunctionBodies =
3477 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3478 ? SkipFunctionBodiesScope::Preamble
3479 : SkipFunctionBodiesScope::PreambleAndMainFile;
3480 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003481
3482 // Configure the diagnostics.
3483 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003484 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003485
Manuel Klimek016c0242016-03-01 10:56:19 +00003486 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003487 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003488
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003489 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3490 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3491 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3492
Guy Benyei11169dd2012-12-18 14:30:41 +00003493 // Recover resources if we crash before exiting this function.
3494 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3495 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003496 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003497
Ahmed Charlesb8984322014-03-07 20:03:18 +00003498 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3499 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003500
3501 // Recover resources if we crash before exiting this function.
3502 llvm::CrashRecoveryContextCleanupRegistrar<
3503 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3504
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003505 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003506 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003507 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003508 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 }
3510
Ahmed Charlesb8984322014-03-07 20:03:18 +00003511 std::unique_ptr<std::vector<const char *>> Args(
3512 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003513
3514 // Recover resources if we crash before exiting this method.
3515 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3516 ArgsCleanup(Args.get());
3517
3518 // Since the Clang C library is primarily used by batch tools dealing with
3519 // (often very broken) source code, where spell-checking can have a
3520 // significant negative impact on performance (particularly when
3521 // precompiled headers are involved), we disable it by default.
3522 // Only do this if we haven't found a spell-checking-related argument.
3523 bool FoundSpellCheckingArgument = false;
3524 for (int I = 0; I != num_command_line_args; ++I) {
3525 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3526 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3527 FoundSpellCheckingArgument = true;
3528 break;
3529 }
3530 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003531 Args->insert(Args->end(), command_line_args,
3532 command_line_args + num_command_line_args);
3533
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003534 if (!FoundSpellCheckingArgument)
3535 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3536
Guy Benyei11169dd2012-12-18 14:30:41 +00003537 // The 'source_filename' argument is optional. If the caller does not
3538 // specify it then it is assumed that the source file is specified
3539 // in the actual argument list.
3540 // Put the source file after command_line_args otherwise if '-x' flag is
3541 // present it will be unused.
3542 if (source_filename)
3543 Args->push_back(source_filename);
3544
3545 // Do we need the detailed preprocessing record?
3546 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3547 Args->push_back("-Xclang");
3548 Args->push_back("-detailed-preprocessing-record");
3549 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003550
3551 // Suppress any editor placeholder diagnostics.
3552 Args->push_back("-fallow-editor-placeholders");
3553
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003555 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003556 // Unless the user specified that they want the preamble on the first parse
3557 // set it up to be created on the first reparse. This makes the first parse
3558 // faster, trading for a slower (first) reparse.
3559 unsigned PrecompilePreambleAfterNParses =
3560 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003561
Alex Lorenz08615792017-12-04 21:56:36 +00003562 LibclangInvocationReporter InvocationReporter(
3563 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003564 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3565 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003566 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003567 Args->data(), Args->data() + Args->size(),
3568 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003569 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003570 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003571 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3572 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003573 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003574 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003575 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3576 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003577
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003578 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003579 if (!Unit && !ErrUnit)
3580 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003581
Guy Benyei11169dd2012-12-18 14:30:41 +00003582 if (NumErrors != Diags->getClient()->getNumErrors()) {
3583 // Make sure to check that 'Unit' is non-NULL.
3584 if (CXXIdx->getDisplayDiagnostics())
3585 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3586 }
3587
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003588 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3589 return CXError_ASTReadError;
3590
David Blaikieea4395e2017-01-06 19:49:01 +00003591 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003592 if (CXTranslationUnitImpl *TU = *out_TU) {
3593 TU->ParsingOptions = options;
3594 TU->Arguments.reserve(Args->size());
3595 for (const char *Arg : *Args)
3596 TU->Arguments.push_back(Arg);
3597 return CXError_Success;
3598 }
3599 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003600}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003601
3602CXTranslationUnit
3603clang_parseTranslationUnit(CXIndex CIdx,
3604 const char *source_filename,
3605 const char *const *command_line_args,
3606 int num_command_line_args,
3607 struct CXUnsavedFile *unsaved_files,
3608 unsigned num_unsaved_files,
3609 unsigned options) {
3610 CXTranslationUnit TU;
3611 enum CXErrorCode Result = clang_parseTranslationUnit2(
3612 CIdx, source_filename, command_line_args, num_command_line_args,
3613 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003614 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003615 assert((TU && Result == CXError_Success) ||
3616 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003617 return TU;
3618}
3619
3620enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003621 CXIndex CIdx, const char *source_filename,
3622 const char *const *command_line_args, int num_command_line_args,
3623 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3624 unsigned options, CXTranslationUnit *out_TU) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003625 noteBottomOfStack();
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003626 SmallVector<const char *, 4> Args;
3627 Args.push_back("clang");
3628 Args.append(command_line_args, command_line_args + num_command_line_args);
3629 return clang_parseTranslationUnit2FullArgv(
3630 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3631 num_unsaved_files, options, out_TU);
3632}
3633
3634enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3635 CXIndex CIdx, const char *source_filename,
3636 const char *const *command_line_args, int num_command_line_args,
3637 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3638 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003639 LOG_FUNC_SECTION {
3640 *Log << source_filename << ": ";
3641 for (int i = 0; i != num_command_line_args; ++i)
3642 *Log << command_line_args[i] << " ";
3643 }
3644
Alp Toker9d85b182014-07-07 01:23:14 +00003645 if (num_unsaved_files && !unsaved_files)
3646 return CXError_InvalidArguments;
3647
Alp Toker5c532982014-07-07 22:42:03 +00003648 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003649 auto ParseTranslationUnitImpl = [=, &result] {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003650 noteBottomOfStack();
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003651 result = clang_parseTranslationUnit_Impl(
3652 CIdx, source_filename, command_line_args, num_command_line_args,
3653 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3654 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003655
Guy Benyei11169dd2012-12-18 14:30:41 +00003656 llvm::CrashRecoveryContext CRC;
3657
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003658 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003659 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3660 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3661 fprintf(stderr, " 'command_line_args' : [");
3662 for (int i = 0; i != num_command_line_args; ++i) {
3663 if (i)
3664 fprintf(stderr, ", ");
3665 fprintf(stderr, "'%s'", command_line_args[i]);
3666 }
3667 fprintf(stderr, "],\n");
3668 fprintf(stderr, " 'unsaved_files' : [");
3669 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3670 if (i)
3671 fprintf(stderr, ", ");
3672 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3673 unsaved_files[i].Length);
3674 }
3675 fprintf(stderr, "],\n");
3676 fprintf(stderr, " 'options' : %d,\n", options);
3677 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003678
3679 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003680 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003681 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003682 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003683 }
Alp Toker5c532982014-07-07 22:42:03 +00003684
3685 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003686}
3687
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003688CXString clang_Type_getObjCEncoding(CXType CT) {
3689 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3690 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3691 std::string encoding;
3692 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3693 encoding);
3694
3695 return cxstring::createDup(encoding);
3696}
3697
3698static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3699 if (C.kind == CXCursor_MacroDefinition) {
3700 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3701 return MDR->getName();
3702 } else if (C.kind == CXCursor_MacroExpansion) {
3703 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3704 return ME.getName();
3705 }
3706 return nullptr;
3707}
3708
3709unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3710 const IdentifierInfo *II = getMacroIdentifier(C);
3711 if (!II) {
3712 return false;
3713 }
3714 ASTUnit *ASTU = getCursorASTUnit(C);
3715 Preprocessor &PP = ASTU->getPreprocessor();
3716 if (const MacroInfo *MI = PP.getMacroInfo(II))
3717 return MI->isFunctionLike();
3718 return false;
3719}
3720
3721unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3722 const IdentifierInfo *II = getMacroIdentifier(C);
3723 if (!II) {
3724 return false;
3725 }
3726 ASTUnit *ASTU = getCursorASTUnit(C);
3727 Preprocessor &PP = ASTU->getPreprocessor();
3728 if (const MacroInfo *MI = PP.getMacroInfo(II))
3729 return MI->isBuiltinMacro();
3730 return false;
3731}
3732
3733unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3734 const Decl *D = getCursorDecl(C);
3735 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3736 if (!FD) {
3737 return false;
3738 }
3739 return FD->isInlined();
3740}
3741
3742static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3743 if (callExpr->getNumArgs() != 1) {
3744 return nullptr;
3745 }
3746
3747 StringLiteral *S = nullptr;
3748 auto *arg = callExpr->getArg(0);
3749 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3750 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3751 auto *subExpr = I->getSubExprAsWritten();
3752
3753 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3754 return nullptr;
3755 }
3756
3757 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3758 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3759 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3760 } else {
3761 return nullptr;
3762 }
3763 return S;
3764}
3765
David Blaikie59272572016-04-13 18:23:33 +00003766struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003767 CXEvalResultKind EvalType;
3768 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003769 unsigned long long unsignedVal;
3770 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003771 double floatVal;
3772 char *stringVal;
3773 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003774 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003775 ~ExprEvalResult() {
3776 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3777 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003778 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003779 }
3780 }
3781};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003782
3783void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003784 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003785}
3786
3787CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3788 if (!E) {
3789 return CXEval_UnExposed;
3790 }
3791 return ((ExprEvalResult *)E)->EvalType;
3792}
3793
3794int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003795 return clang_EvalResult_getAsLongLong(E);
3796}
3797
3798long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003799 if (!E) {
3800 return 0;
3801 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003802 ExprEvalResult *Result = (ExprEvalResult*)E;
3803 if (Result->IsUnsignedInt)
3804 return Result->EvalData.unsignedVal;
3805 return Result->EvalData.intVal;
3806}
3807
3808unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3809 return ((ExprEvalResult *)E)->IsUnsignedInt;
3810}
3811
3812unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3813 if (!E) {
3814 return 0;
3815 }
3816
3817 ExprEvalResult *Result = (ExprEvalResult*)E;
3818 if (Result->IsUnsignedInt)
3819 return Result->EvalData.unsignedVal;
3820 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003821}
3822
3823double clang_EvalResult_getAsDouble(CXEvalResult E) {
3824 if (!E) {
3825 return 0;
3826 }
3827 return ((ExprEvalResult *)E)->EvalData.floatVal;
3828}
3829
3830const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3831 if (!E) {
3832 return nullptr;
3833 }
3834 return ((ExprEvalResult *)E)->EvalData.stringVal;
3835}
3836
3837static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3838 Expr::EvalResult ER;
3839 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003840 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003841 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003842
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003843 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003844 if (expr->isValueDependent())
3845 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003846 if (!expr->EvaluateAsRValue(ER, ctx))
3847 return nullptr;
3848
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003849 QualType rettype;
3850 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003851 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003852 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003853 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003854
David Blaikiebbc00882016-04-13 18:36:19 +00003855 if (ER.Val.isInt()) {
3856 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003857
3858 auto& val = ER.Val.getInt();
3859 if (val.isUnsigned()) {
3860 result->IsUnsignedInt = true;
3861 result->EvalData.unsignedVal = val.getZExtValue();
3862 } else {
3863 result->EvalData.intVal = val.getExtValue();
3864 }
3865
David Blaikiebbc00882016-04-13 18:36:19 +00003866 return result.release();
3867 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003868
David Blaikiebbc00882016-04-13 18:36:19 +00003869 if (ER.Val.isFloat()) {
3870 llvm::SmallVector<char, 100> Buffer;
3871 ER.Val.getFloat().toString(Buffer);
3872 std::string floatStr(Buffer.data(), Buffer.size());
3873 result->EvalType = CXEval_Float;
3874 bool ignored;
3875 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003876 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003877 llvm::APFloat::rmNearestTiesToEven, &ignored);
3878 result->EvalData.floatVal = apFloat.convertToDouble();
3879 return result.release();
3880 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003881
David Blaikiebbc00882016-04-13 18:36:19 +00003882 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3883 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3884 auto *subExpr = I->getSubExprAsWritten();
3885 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3886 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003887 const StringLiteral *StrE = nullptr;
3888 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003889 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003890
3891 if (ObjCExpr) {
3892 StrE = ObjCExpr->getString();
3893 result->EvalType = CXEval_ObjCStrLiteral;
3894 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003895 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003896 result->EvalType = CXEval_StrLiteral;
3897 }
3898
3899 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003900 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003901 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3902 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003903 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003904 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003905 }
3906 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3907 expr->getStmtClass() == Stmt::StringLiteralClass) {
3908 const StringLiteral *StrE = nullptr;
3909 const ObjCStringLiteral *ObjCExpr;
3910 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003911
David Blaikiebbc00882016-04-13 18:36:19 +00003912 if (ObjCExpr) {
3913 StrE = ObjCExpr->getString();
3914 result->EvalType = CXEval_ObjCStrLiteral;
3915 } else {
3916 StrE = cast<StringLiteral>(expr);
3917 result->EvalType = CXEval_StrLiteral;
3918 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003919
David Blaikiebbc00882016-04-13 18:36:19 +00003920 std::string strRef(StrE->getString().str());
3921 result->EvalData.stringVal = new char[strRef.size() + 1];
3922 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3923 result->EvalData.stringVal[strRef.size()] = '\0';
3924 return result.release();
3925 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003926
David Blaikiebbc00882016-04-13 18:36:19 +00003927 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3928 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003929
David Blaikiebbc00882016-04-13 18:36:19 +00003930 rettype = CC->getType();
3931 if (rettype.getAsString() == "CFStringRef" &&
3932 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003933
David Blaikiebbc00882016-04-13 18:36:19 +00003934 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3935 StringLiteral *S = getCFSTR_value(callExpr);
3936 if (S) {
3937 std::string strLiteral(S->getString().str());
3938 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003939
David Blaikiebbc00882016-04-13 18:36:19 +00003940 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3941 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3942 strLiteral.size());
3943 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003944 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003945 }
3946 }
3947
David Blaikiebbc00882016-04-13 18:36:19 +00003948 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3949 callExpr = static_cast<CallExpr *>(expr);
3950 rettype = callExpr->getCallReturnType(ctx);
3951
3952 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3953 return nullptr;
3954
3955 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3956 if (callExpr->getNumArgs() == 1 &&
3957 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3958 return nullptr;
3959 } else if (rettype.getAsString() == "CFStringRef") {
3960
3961 StringLiteral *S = getCFSTR_value(callExpr);
3962 if (S) {
3963 std::string strLiteral(S->getString().str());
3964 result->EvalType = CXEval_CFStr;
3965 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3966 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3967 strLiteral.size());
3968 result->EvalData.stringVal[strLiteral.size()] = '\0';
3969 return result.release();
3970 }
3971 }
3972 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3973 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3974 ValueDecl *V = D->getDecl();
3975 if (V->getKind() == Decl::Function) {
3976 std::string strName = V->getNameAsString();
3977 result->EvalType = CXEval_Other;
3978 result->EvalData.stringVal = new char[strName.size() + 1];
3979 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3980 result->EvalData.stringVal[strName.size()] = '\0';
3981 return result.release();
3982 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003983 }
3984
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003985 return nullptr;
3986}
3987
Alex Lorenz65317e12019-01-08 22:32:51 +00003988static const Expr *evaluateDeclExpr(const Decl *D) {
3989 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003990 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003991 if (auto *Var = dyn_cast<VarDecl>(D))
3992 return Var->getInit();
3993 else if (auto *Field = dyn_cast<FieldDecl>(D))
3994 return Field->getInClassInitializer();
3995 return nullptr;
3996}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003997
Alex Lorenz65317e12019-01-08 22:32:51 +00003998static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3999 assert(CS && "invalid compound statement");
4000 for (auto *bodyIterator : CS->body()) {
4001 if (const auto *E = dyn_cast<Expr>(bodyIterator))
4002 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00004003 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00004004 return nullptr;
4005}
4006
Alex Lorenz65317e12019-01-08 22:32:51 +00004007CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4008 if (const Expr *E =
4009 clang_getCursorKind(C) == CXCursor_CompoundStmt
4010 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
4011 : evaluateDeclExpr(getCursorDecl(C)))
4012 return const_cast<CXEvalResult>(
4013 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4014 return nullptr;
4015}
4016
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004017unsigned clang_Cursor_hasAttrs(CXCursor C) {
4018 const Decl *D = getCursorDecl(C);
4019 if (!D) {
4020 return 0;
4021 }
4022
4023 if (D->hasAttrs()) {
4024 return 1;
4025 }
4026
4027 return 0;
4028}
Guy Benyei11169dd2012-12-18 14:30:41 +00004029unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4030 return CXSaveTranslationUnit_None;
4031}
4032
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004033static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4034 const char *FileName,
4035 unsigned options) {
4036 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004037 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4038 setThreadBackgroundPriority();
4039
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004040 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4041 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004042}
4043
4044int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4045 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004046 LOG_FUNC_SECTION {
4047 *Log << TU << ' ' << FileName;
4048 }
4049
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004050 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004051 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004052 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004053 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004054
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004055 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4057 if (!CXXUnit->hasSema())
4058 return CXSaveError_InvalidTU;
4059
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004060 CXSaveError result;
4061 auto SaveTranslationUnitImpl = [=, &result]() {
4062 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4063 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004064
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004065 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004066 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004067
4068 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4069 PrintLibclangResourceUsage(TU);
4070
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004071 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 }
4073
4074 // We have an AST that has invalid nodes due to compiler errors.
4075 // Use a crash recovery thread for protection.
4076
4077 llvm::CrashRecoveryContext CRC;
4078
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004079 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004080 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4081 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4082 fprintf(stderr, " 'options' : %d,\n", options);
4083 fprintf(stderr, "}\n");
4084
4085 return CXSaveError_Unknown;
4086
4087 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4088 PrintLibclangResourceUsage(TU);
4089 }
4090
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004091 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004092}
4093
4094void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4095 if (CTUnit) {
4096 // If the translation unit has been marked as unsafe to free, just discard
4097 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004098 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4099 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 return;
4101
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004102 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004103 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4105 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004106 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004107 delete CTUnit;
4108 }
4109}
4110
Erik Verbruggen346066b2017-05-30 14:25:54 +00004111unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4112 if (CTUnit) {
4113 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4114
4115 if (Unit && Unit->isUnsafeToFree())
4116 return false;
4117
4118 Unit->ResetForParse();
4119 return true;
4120 }
4121
4122 return false;
4123}
4124
Guy Benyei11169dd2012-12-18 14:30:41 +00004125unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4126 return CXReparse_None;
4127}
4128
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004129static CXErrorCode
4130clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4131 ArrayRef<CXUnsavedFile> unsaved_files,
4132 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004133 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004134 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004135 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004136 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004137 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004138
4139 // Reset the associated diagnostics.
4140 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004141 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004142
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004143 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004144 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4145 setThreadBackgroundPriority();
4146
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004147 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004149
4150 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4151 new std::vector<ASTUnit::RemappedFile>());
4152
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 // Recover resources if we crash before exiting this function.
4154 llvm::CrashRecoveryContextCleanupRegistrar<
4155 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004156
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004157 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004158 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004159 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004160 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004161 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004162
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004163 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4164 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004165 return CXError_Success;
4166 if (isASTReadError(CXXUnit))
4167 return CXError_ASTReadError;
4168 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004169}
4170
4171int clang_reparseTranslationUnit(CXTranslationUnit TU,
4172 unsigned num_unsaved_files,
4173 struct CXUnsavedFile *unsaved_files,
4174 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004175 LOG_FUNC_SECTION {
4176 *Log << TU;
4177 }
4178
Alp Toker9d85b182014-07-07 01:23:14 +00004179 if (num_unsaved_files && !unsaved_files)
4180 return CXError_InvalidArguments;
4181
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004182 CXErrorCode result;
4183 auto ReparseTranslationUnitImpl = [=, &result]() {
4184 result = clang_reparseTranslationUnit_Impl(
4185 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4186 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004187
Guy Benyei11169dd2012-12-18 14:30:41 +00004188 llvm::CrashRecoveryContext CRC;
4189
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004190 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004191 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004192 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004193 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4195 PrintLibclangResourceUsage(TU);
4196
Alp Toker5c532982014-07-07 22:42:03 +00004197 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004198}
4199
4200
4201CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004202 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004203 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004204 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004205 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004206
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004207 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004208 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004209}
4210
4211CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004212 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004213 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004214 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004215 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004216
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004217 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004218 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4219}
4220
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004221CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4222 if (isNotUsableTU(CTUnit)) {
4223 LOG_BAD_TU(CTUnit);
4224 return nullptr;
4225 }
4226
4227 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4228 impl->TranslationUnit = CTUnit;
4229 return impl;
4230}
4231
4232CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4233 if (!TargetInfo)
4234 return cxstring::createEmpty();
4235
4236 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4237 assert(!isNotUsableTU(CTUnit) &&
4238 "Unexpected unusable translation unit in TargetInfo");
4239
4240 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4241 std::string Triple =
4242 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4243 return cxstring::createDup(Triple);
4244}
4245
4246int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4247 if (!TargetInfo)
4248 return -1;
4249
4250 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4251 assert(!isNotUsableTU(CTUnit) &&
4252 "Unexpected unusable translation unit in TargetInfo");
4253
4254 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4255 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4256}
4257
4258void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4259 if (!TargetInfo)
4260 return;
4261
4262 delete TargetInfo;
4263}
4264
Guy Benyei11169dd2012-12-18 14:30:41 +00004265//===----------------------------------------------------------------------===//
4266// CXFile Operations.
4267//===----------------------------------------------------------------------===//
4268
Guy Benyei11169dd2012-12-18 14:30:41 +00004269CXString clang_getFileName(CXFile SFile) {
4270 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004271 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004272
4273 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004274 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004275}
4276
4277time_t clang_getFileTime(CXFile SFile) {
4278 if (!SFile)
4279 return 0;
4280
4281 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4282 return FEnt->getModificationTime();
4283}
4284
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004285CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004286 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004287 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004288 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004289 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004290
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004291 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004292
4293 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004294 auto File = FMgr.getFile(file_name);
4295 if (!File)
4296 return nullptr;
4297 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004298}
4299
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004300const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4301 size_t *size) {
4302 if (isNotUsableTU(TU)) {
4303 LOG_BAD_TU(TU);
4304 return nullptr;
4305 }
4306
4307 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4308 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4309 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004310 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004311 if (Invalid) {
4312 if (size)
4313 *size = 0;
4314 return nullptr;
4315 }
4316 if (size)
4317 *size = buf->getBufferSize();
4318 return buf->getBufferStart();
4319}
4320
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004321unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4322 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004323 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004324 LOG_BAD_TU(TU);
4325 return 0;
4326 }
4327
4328 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 return 0;
4330
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004331 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 FileEntry *FEnt = static_cast<FileEntry *>(file);
4333 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4334 .isFileMultipleIncludeGuarded(FEnt);
4335}
4336
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004337int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4338 if (!file || !outID)
4339 return 1;
4340
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004341 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004342 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4343 outID->data[0] = ID.getDevice();
4344 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004345 outID->data[2] = FEnt->getModificationTime();
4346 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004347}
4348
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004349int clang_File_isEqual(CXFile file1, CXFile file2) {
4350 if (file1 == file2)
4351 return true;
4352
4353 if (!file1 || !file2)
4354 return false;
4355
4356 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4357 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4358 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4359}
4360
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004361CXString clang_File_tryGetRealPathName(CXFile SFile) {
4362 if (!SFile)
4363 return cxstring::createNull();
4364
4365 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4366 return cxstring::createRef(FEnt->tryGetRealPathName());
4367}
4368
Guy Benyei11169dd2012-12-18 14:30:41 +00004369//===----------------------------------------------------------------------===//
4370// CXCursor Operations.
4371//===----------------------------------------------------------------------===//
4372
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004373static const Decl *getDeclFromExpr(const Stmt *E) {
4374 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 return getDeclFromExpr(CE->getSubExpr());
4376
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004377 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004378 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004379 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004381 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004383 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 if (PRE->isExplicitProperty())
4385 return PRE->getExplicitProperty();
4386 // It could be messaging both getter and setter as in:
4387 // ++myobj.myprop;
4388 // in which case prefer to associate the setter since it is less obvious
4389 // from inspecting the source that the setter is going to get called.
4390 if (PRE->isMessagingSetter())
4391 return PRE->getImplicitPropertySetter();
4392 return PRE->getImplicitPropertyGetter();
4393 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004394 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004395 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004396 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 if (Expr *Src = OVE->getSourceExpr())
4398 return getDeclFromExpr(Src);
4399
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004400 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004402 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 if (!CE->isElidable())
4404 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004405 if (const CXXInheritedCtorInitExpr *CE =
4406 dyn_cast<CXXInheritedCtorInitExpr>(E))
4407 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004408 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 return OME->getMethodDecl();
4410
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004411 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004413 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004414 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4415 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004416 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4418 isa<ParmVarDecl>(SizeOfPack->getPack()))
4419 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004420
4421 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004422}
4423
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004424static SourceLocation getLocationFromExpr(const Expr *E) {
4425 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 return getLocationFromExpr(CE->getSubExpr());
4427
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004428 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004430 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004432 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004434 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004436 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004438 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004440
4441 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004442}
4443
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004444extern "C" {
4445
Guy Benyei11169dd2012-12-18 14:30:41 +00004446unsigned clang_visitChildren(CXCursor parent,
4447 CXCursorVisitor visitor,
4448 CXClientData client_data) {
4449 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4450 /*VisitPreprocessorLast=*/false);
4451 return CursorVis.VisitChildren(parent);
4452}
4453
4454#ifndef __has_feature
4455#define __has_feature(x) 0
4456#endif
4457#if __has_feature(blocks)
4458typedef enum CXChildVisitResult
4459 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4460
4461static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4462 CXClientData client_data) {
4463 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4464 return block(cursor, parent);
4465}
4466#else
4467// If we are compiled with a compiler that doesn't have native blocks support,
4468// define and call the block manually, so the
4469typedef struct _CXChildVisitResult
4470{
4471 void *isa;
4472 int flags;
4473 int reserved;
4474 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4475 CXCursor);
4476} *CXCursorVisitorBlock;
4477
4478static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4479 CXClientData client_data) {
4480 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4481 return block->invoke(block, cursor, parent);
4482}
4483#endif
4484
4485
4486unsigned clang_visitChildrenWithBlock(CXCursor parent,
4487 CXCursorVisitorBlock block) {
4488 return clang_visitChildren(parent, visitWithBlock, block);
4489}
4490
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004491static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004493 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004494
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004495 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004497 if (const ObjCPropertyImplDecl *PropImpl =
4498 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004500 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004501
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004502 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004504 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004505
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004506 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 }
4508
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004509 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004510 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004511
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004512 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4514 // and returns different names. NamedDecl returns the class name and
4515 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004516 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004517
4518 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004519 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004520
4521 SmallString<1024> S;
4522 llvm::raw_svector_ostream os(S);
4523 ND->printName(os);
4524
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004525 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004526}
4527
4528CXString clang_getCursorSpelling(CXCursor C) {
4529 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004530 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004531
4532 if (clang_isReference(C.kind)) {
4533 switch (C.kind) {
4534 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004535 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004536 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 }
4538 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004539 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004540 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 }
4542 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004543 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004545 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 }
4547 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004548 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004549 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 }
4551 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004552 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 assert(Type && "Missing type decl");
4554
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004555 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 getAsString());
4557 }
4558 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004559 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 assert(Template && "Missing template decl");
4561
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004562 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 }
4564
4565 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004566 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 assert(NS && "Missing namespace decl");
4568
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004569 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 }
4571
4572 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004573 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 assert(Field && "Missing member decl");
4575
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004576 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 }
4578
4579 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004580 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 assert(Label && "Missing label");
4582
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004583 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 }
4585
4586 case CXCursor_OverloadedDeclRef: {
4587 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004588 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4589 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004590 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004591 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004593 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004594 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 OverloadedTemplateStorage *Ovl
4596 = Storage.get<OverloadedTemplateStorage*>();
4597 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004598 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004599 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 }
4601
4602 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004603 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 assert(Var && "Missing variable decl");
4605
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004606 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 }
4608
4609 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004610 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 }
4612 }
4613
4614 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004615 const Expr *E = getCursorExpr(C);
4616
4617 if (C.kind == CXCursor_ObjCStringLiteral ||
4618 C.kind == CXCursor_StringLiteral) {
4619 const StringLiteral *SLit;
4620 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4621 SLit = OSL->getString();
4622 } else {
4623 SLit = cast<StringLiteral>(E);
4624 }
4625 SmallString<256> Buf;
4626 llvm::raw_svector_ostream OS(Buf);
4627 SLit->outputString(OS);
4628 return cxstring::createDup(OS.str());
4629 }
4630
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004631 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 if (D)
4633 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004634 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 }
4636
4637 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004638 const Stmt *S = getCursorStmt(C);
4639 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004640 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004641
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004642 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 }
4644
4645 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004646 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 ->getNameStart());
4648
4649 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004650 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 ->getNameStart());
4652
4653 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004654 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004655
4656 if (clang_isDeclaration(C.kind))
4657 return getDeclSpelling(getCursorDecl(C));
4658
4659 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004660 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004661 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 }
4663
4664 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004665 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004666 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 }
4668
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004669 if (C.kind == CXCursor_PackedAttr) {
4670 return cxstring::createRef("packed");
4671 }
4672
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004673 if (C.kind == CXCursor_VisibilityAttr) {
4674 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4675 switch (AA->getVisibility()) {
4676 case VisibilityAttr::VisibilityType::Default:
4677 return cxstring::createRef("default");
4678 case VisibilityAttr::VisibilityType::Hidden:
4679 return cxstring::createRef("hidden");
4680 case VisibilityAttr::VisibilityType::Protected:
4681 return cxstring::createRef("protected");
4682 }
4683 llvm_unreachable("unknown visibility type");
4684 }
4685
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004686 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004687}
4688
4689CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4690 unsigned pieceIndex,
4691 unsigned options) {
4692 if (clang_Cursor_isNull(C))
4693 return clang_getNullRange();
4694
4695 ASTContext &Ctx = getCursorContext(C);
4696
4697 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004698 const Stmt *S = getCursorStmt(C);
4699 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 if (pieceIndex > 0)
4701 return clang_getNullRange();
4702 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4703 }
4704
4705 return clang_getNullRange();
4706 }
4707
4708 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004709 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4711 if (pieceIndex >= ME->getNumSelectorLocs())
4712 return clang_getNullRange();
4713 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4714 }
4715 }
4716
4717 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4718 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004719 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4721 if (pieceIndex >= MD->getNumSelectorLocs())
4722 return clang_getNullRange();
4723 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4724 }
4725 }
4726
4727 if (C.kind == CXCursor_ObjCCategoryDecl ||
4728 C.kind == CXCursor_ObjCCategoryImplDecl) {
4729 if (pieceIndex > 0)
4730 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004731 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004732 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4733 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004734 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4736 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4737 }
4738
4739 if (C.kind == CXCursor_ModuleImportDecl) {
4740 if (pieceIndex > 0)
4741 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004742 if (const ImportDecl *ImportD =
4743 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4745 if (!Locs.empty())
4746 return cxloc::translateSourceRange(Ctx,
4747 SourceRange(Locs.front(), Locs.back()));
4748 }
4749 return clang_getNullRange();
4750 }
4751
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004752 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004753 C.kind == CXCursor_ConversionFunction ||
4754 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004755 if (pieceIndex > 0)
4756 return clang_getNullRange();
4757 if (const FunctionDecl *FD =
4758 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4759 DeclarationNameInfo FunctionName = FD->getNameInfo();
4760 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4761 }
4762 return clang_getNullRange();
4763 }
4764
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 // FIXME: A CXCursor_InclusionDirective should give the location of the
4766 // filename, but we don't keep track of this.
4767
4768 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4769 // but we don't keep track of this.
4770
4771 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4772 // but we don't keep track of this.
4773
4774 // Default handling, give the location of the cursor.
4775
4776 if (pieceIndex > 0)
4777 return clang_getNullRange();
4778
4779 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4780 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4781 return cxloc::translateSourceRange(Ctx, Loc);
4782}
4783
Eli Bendersky44a206f2014-07-31 18:04:56 +00004784CXString clang_Cursor_getMangling(CXCursor C) {
4785 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4786 return cxstring::createEmpty();
4787
Eli Bendersky44a206f2014-07-31 18:04:56 +00004788 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004789 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004790 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4791 return cxstring::createEmpty();
4792
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004793 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004794 ASTNameGenerator ASTNameGen(Ctx);
4795 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004796}
4797
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004798CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4799 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4800 return nullptr;
4801
4802 const Decl *D = getCursorDecl(C);
4803 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4804 return nullptr;
4805
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004806 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004807 ASTNameGenerator ASTNameGen(Ctx);
4808 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004809 return cxstring::createSet(Manglings);
4810}
4811
Dave Lee1a532c92017-09-22 16:58:57 +00004812CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4813 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4814 return nullptr;
4815
4816 const Decl *D = getCursorDecl(C);
4817 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4818 return nullptr;
4819
4820 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004821 ASTNameGenerator ASTNameGen(Ctx);
4822 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004823 return cxstring::createSet(Manglings);
4824}
4825
Jonathan Coe45ef5032018-01-16 10:19:56 +00004826CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4827 if (clang_Cursor_isNull(C))
4828 return 0;
4829 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4830}
4831
4832void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4833 if (Policy)
4834 delete static_cast<PrintingPolicy *>(Policy);
4835}
4836
4837unsigned
4838clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4839 enum CXPrintingPolicyProperty Property) {
4840 if (!Policy)
4841 return 0;
4842
4843 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4844 switch (Property) {
4845 case CXPrintingPolicy_Indentation:
4846 return P->Indentation;
4847 case CXPrintingPolicy_SuppressSpecifiers:
4848 return P->SuppressSpecifiers;
4849 case CXPrintingPolicy_SuppressTagKeyword:
4850 return P->SuppressTagKeyword;
4851 case CXPrintingPolicy_IncludeTagDefinition:
4852 return P->IncludeTagDefinition;
4853 case CXPrintingPolicy_SuppressScope:
4854 return P->SuppressScope;
4855 case CXPrintingPolicy_SuppressUnwrittenScope:
4856 return P->SuppressUnwrittenScope;
4857 case CXPrintingPolicy_SuppressInitializers:
4858 return P->SuppressInitializers;
4859 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4860 return P->ConstantArraySizeAsWritten;
4861 case CXPrintingPolicy_AnonymousTagLocations:
4862 return P->AnonymousTagLocations;
4863 case CXPrintingPolicy_SuppressStrongLifetime:
4864 return P->SuppressStrongLifetime;
4865 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4866 return P->SuppressLifetimeQualifiers;
4867 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4868 return P->SuppressTemplateArgsInCXXConstructors;
4869 case CXPrintingPolicy_Bool:
4870 return P->Bool;
4871 case CXPrintingPolicy_Restrict:
4872 return P->Restrict;
4873 case CXPrintingPolicy_Alignof:
4874 return P->Alignof;
4875 case CXPrintingPolicy_UnderscoreAlignof:
4876 return P->UnderscoreAlignof;
4877 case CXPrintingPolicy_UseVoidForZeroParams:
4878 return P->UseVoidForZeroParams;
4879 case CXPrintingPolicy_TerseOutput:
4880 return P->TerseOutput;
4881 case CXPrintingPolicy_PolishForDeclaration:
4882 return P->PolishForDeclaration;
4883 case CXPrintingPolicy_Half:
4884 return P->Half;
4885 case CXPrintingPolicy_MSWChar:
4886 return P->MSWChar;
4887 case CXPrintingPolicy_IncludeNewlines:
4888 return P->IncludeNewlines;
4889 case CXPrintingPolicy_MSVCFormatting:
4890 return P->MSVCFormatting;
4891 case CXPrintingPolicy_ConstantsAsWritten:
4892 return P->ConstantsAsWritten;
4893 case CXPrintingPolicy_SuppressImplicitBase:
4894 return P->SuppressImplicitBase;
4895 case CXPrintingPolicy_FullyQualifiedName:
4896 return P->FullyQualifiedName;
4897 }
4898
4899 assert(false && "Invalid CXPrintingPolicyProperty");
4900 return 0;
4901}
4902
4903void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4904 enum CXPrintingPolicyProperty Property,
4905 unsigned Value) {
4906 if (!Policy)
4907 return;
4908
4909 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4910 switch (Property) {
4911 case CXPrintingPolicy_Indentation:
4912 P->Indentation = Value;
4913 return;
4914 case CXPrintingPolicy_SuppressSpecifiers:
4915 P->SuppressSpecifiers = Value;
4916 return;
4917 case CXPrintingPolicy_SuppressTagKeyword:
4918 P->SuppressTagKeyword = Value;
4919 return;
4920 case CXPrintingPolicy_IncludeTagDefinition:
4921 P->IncludeTagDefinition = Value;
4922 return;
4923 case CXPrintingPolicy_SuppressScope:
4924 P->SuppressScope = Value;
4925 return;
4926 case CXPrintingPolicy_SuppressUnwrittenScope:
4927 P->SuppressUnwrittenScope = Value;
4928 return;
4929 case CXPrintingPolicy_SuppressInitializers:
4930 P->SuppressInitializers = Value;
4931 return;
4932 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4933 P->ConstantArraySizeAsWritten = Value;
4934 return;
4935 case CXPrintingPolicy_AnonymousTagLocations:
4936 P->AnonymousTagLocations = Value;
4937 return;
4938 case CXPrintingPolicy_SuppressStrongLifetime:
4939 P->SuppressStrongLifetime = Value;
4940 return;
4941 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4942 P->SuppressLifetimeQualifiers = Value;
4943 return;
4944 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4945 P->SuppressTemplateArgsInCXXConstructors = Value;
4946 return;
4947 case CXPrintingPolicy_Bool:
4948 P->Bool = Value;
4949 return;
4950 case CXPrintingPolicy_Restrict:
4951 P->Restrict = Value;
4952 return;
4953 case CXPrintingPolicy_Alignof:
4954 P->Alignof = Value;
4955 return;
4956 case CXPrintingPolicy_UnderscoreAlignof:
4957 P->UnderscoreAlignof = Value;
4958 return;
4959 case CXPrintingPolicy_UseVoidForZeroParams:
4960 P->UseVoidForZeroParams = Value;
4961 return;
4962 case CXPrintingPolicy_TerseOutput:
4963 P->TerseOutput = Value;
4964 return;
4965 case CXPrintingPolicy_PolishForDeclaration:
4966 P->PolishForDeclaration = Value;
4967 return;
4968 case CXPrintingPolicy_Half:
4969 P->Half = Value;
4970 return;
4971 case CXPrintingPolicy_MSWChar:
4972 P->MSWChar = Value;
4973 return;
4974 case CXPrintingPolicy_IncludeNewlines:
4975 P->IncludeNewlines = Value;
4976 return;
4977 case CXPrintingPolicy_MSVCFormatting:
4978 P->MSVCFormatting = Value;
4979 return;
4980 case CXPrintingPolicy_ConstantsAsWritten:
4981 P->ConstantsAsWritten = Value;
4982 return;
4983 case CXPrintingPolicy_SuppressImplicitBase:
4984 P->SuppressImplicitBase = Value;
4985 return;
4986 case CXPrintingPolicy_FullyQualifiedName:
4987 P->FullyQualifiedName = Value;
4988 return;
4989 }
4990
4991 assert(false && "Invalid CXPrintingPolicyProperty");
4992}
4993
4994CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4995 if (clang_Cursor_isNull(C))
4996 return cxstring::createEmpty();
4997
4998 if (clang_isDeclaration(C.kind)) {
4999 const Decl *D = getCursorDecl(C);
5000 if (!D)
5001 return cxstring::createEmpty();
5002
5003 SmallString<128> Str;
5004 llvm::raw_svector_ostream OS(Str);
5005 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
5006 D->print(OS, UserPolicy ? *UserPolicy
5007 : getCursorContext(C).getPrintingPolicy());
5008
5009 return cxstring::createDup(OS.str());
5010 }
5011
5012 return cxstring::createEmpty();
5013}
5014
Guy Benyei11169dd2012-12-18 14:30:41 +00005015CXString clang_getCursorDisplayName(CXCursor C) {
5016 if (!clang_isDeclaration(C.kind))
5017 return clang_getCursorSpelling(C);
5018
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005019 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005021 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005022
5023 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005024 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 D = FunTmpl->getTemplatedDecl();
5026
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005027 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 SmallString<64> Str;
5029 llvm::raw_svector_ostream OS(Str);
5030 OS << *Function;
5031 if (Function->getPrimaryTemplate())
5032 OS << "<>";
5033 OS << "(";
5034 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5035 if (I)
5036 OS << ", ";
5037 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5038 }
5039
5040 if (Function->isVariadic()) {
5041 if (Function->getNumParams())
5042 OS << ", ";
5043 OS << "...";
5044 }
5045 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005046 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 }
5048
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005049 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 SmallString<64> Str;
5051 llvm::raw_svector_ostream OS(Str);
5052 OS << *ClassTemplate;
5053 OS << "<";
5054 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5055 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5056 if (I)
5057 OS << ", ";
5058
5059 NamedDecl *Param = Params->getParam(I);
5060 if (Param->getIdentifier()) {
5061 OS << Param->getIdentifier()->getName();
5062 continue;
5063 }
5064
5065 // There is no parameter name, which makes this tricky. Try to come up
5066 // with something useful that isn't too long.
5067 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Saar Razff1e0fc2020-01-15 02:48:42 +02005068 if (const auto *TC = TTP->getTypeConstraint()) {
5069 TC->getConceptNameInfo().printName(OS, Policy);
5070 if (TC->hasExplicitTemplateArgs())
5071 OS << "<...>";
5072 } else
5073 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 else if (NonTypeTemplateParmDecl *NTTP
5075 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5076 OS << NTTP->getType().getAsString(Policy);
5077 else
5078 OS << "template<...> class";
5079 }
5080
5081 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005082 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 }
5084
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005085 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5087 // If the type was explicitly written, use that.
5088 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005089 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005090
Benjamin Kramer9170e912013-02-22 15:46:01 +00005091 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 llvm::raw_svector_ostream OS(Str);
5093 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005094 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5095 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005096 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 }
5098
5099 return clang_getCursorSpelling(C);
5100}
5101
5102CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5103 switch (Kind) {
5104 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005168 case CXCursor_FixedPointLiteral:
5169 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005184 case CXCursor_OMPArraySectionExpr:
5185 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005236 case CXCursor_ObjCAvailabilityCheckExpr:
5237 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005238 case CXCursor_ObjCSelfExpr:
5239 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005257 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005265 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005266 case CXCursor_BuiltinBitCastExpr:
5267 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005277 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005297 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005307 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005309 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005311 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005313 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005315 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005317 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005319 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005321 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005323 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005325 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005327 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005328 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005329 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005330 case CXCursor_SEHLeaveStmt:
5331 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005333 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005335 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005337 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005338 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005339 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005340 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005341 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005343 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005345 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005347 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005349 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005350 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005351 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005352 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005353 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005355 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005357 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005359 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005360 case CXCursor_PackedAttr:
5361 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005362 case CXCursor_PureAttr:
5363 return cxstring::createRef("attribute(pure)");
5364 case CXCursor_ConstAttr:
5365 return cxstring::createRef("attribute(const)");
5366 case CXCursor_NoDuplicateAttr:
5367 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005368 case CXCursor_CUDAConstantAttr:
5369 return cxstring::createRef("attribute(constant)");
5370 case CXCursor_CUDADeviceAttr:
5371 return cxstring::createRef("attribute(device)");
5372 case CXCursor_CUDAGlobalAttr:
5373 return cxstring::createRef("attribute(global)");
5374 case CXCursor_CUDAHostAttr:
5375 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005376 case CXCursor_CUDASharedAttr:
5377 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005378 case CXCursor_VisibilityAttr:
5379 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005380 case CXCursor_DLLExport:
5381 return cxstring::createRef("attribute(dllexport)");
5382 case CXCursor_DLLImport:
5383 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005384 case CXCursor_NSReturnsRetained:
5385 return cxstring::createRef("attribute(ns_returns_retained)");
5386 case CXCursor_NSReturnsNotRetained:
5387 return cxstring::createRef("attribute(ns_returns_not_retained)");
5388 case CXCursor_NSReturnsAutoreleased:
5389 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5390 case CXCursor_NSConsumesSelf:
5391 return cxstring::createRef("attribute(ns_consumes_self)");
5392 case CXCursor_NSConsumed:
5393 return cxstring::createRef("attribute(ns_consumed)");
5394 case CXCursor_ObjCException:
5395 return cxstring::createRef("attribute(objc_exception)");
5396 case CXCursor_ObjCNSObject:
5397 return cxstring::createRef("attribute(NSObject)");
5398 case CXCursor_ObjCIndependentClass:
5399 return cxstring::createRef("attribute(objc_independent_class)");
5400 case CXCursor_ObjCPreciseLifetime:
5401 return cxstring::createRef("attribute(objc_precise_lifetime)");
5402 case CXCursor_ObjCReturnsInnerPointer:
5403 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5404 case CXCursor_ObjCRequiresSuper:
5405 return cxstring::createRef("attribute(objc_requires_super)");
5406 case CXCursor_ObjCRootClass:
5407 return cxstring::createRef("attribute(objc_root_class)");
5408 case CXCursor_ObjCSubclassingRestricted:
5409 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5410 case CXCursor_ObjCExplicitProtocolImpl:
5411 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5412 case CXCursor_ObjCDesignatedInitializer:
5413 return cxstring::createRef("attribute(objc_designated_initializer)");
5414 case CXCursor_ObjCRuntimeVisible:
5415 return cxstring::createRef("attribute(objc_runtime_visible)");
5416 case CXCursor_ObjCBoxable:
5417 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005418 case CXCursor_FlagEnum:
5419 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005420 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005421 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005422 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005423 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005425 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005426 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005427 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005428 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005429 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005431 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005432 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005433 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005434 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005435 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005436 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005437 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005438 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005439 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005441 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005442 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005443 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005444 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005445 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005446 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005447 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005448 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005449 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005451 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005453 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005454 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005455 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005457 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005458 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005459 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005460 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005461 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005462 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005463 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005464 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005465 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005466 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005467 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005468 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005469 return cxstring::createRef("OMPParallelDirective");
5470 case CXCursor_OMPSimdDirective:
5471 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005472 case CXCursor_OMPForDirective:
5473 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005474 case CXCursor_OMPForSimdDirective:
5475 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005476 case CXCursor_OMPSectionsDirective:
5477 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005478 case CXCursor_OMPSectionDirective:
5479 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005480 case CXCursor_OMPSingleDirective:
5481 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005482 case CXCursor_OMPMasterDirective:
5483 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005484 case CXCursor_OMPCriticalDirective:
5485 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005486 case CXCursor_OMPParallelForDirective:
5487 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005488 case CXCursor_OMPParallelForSimdDirective:
5489 return cxstring::createRef("OMPParallelForSimdDirective");
cchen47d60942019-12-05 13:43:48 -05005490 case CXCursor_OMPParallelMasterDirective:
5491 return cxstring::createRef("OMPParallelMasterDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005492 case CXCursor_OMPParallelSectionsDirective:
5493 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005494 case CXCursor_OMPTaskDirective:
5495 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005496 case CXCursor_OMPTaskyieldDirective:
5497 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005498 case CXCursor_OMPBarrierDirective:
5499 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005500 case CXCursor_OMPTaskwaitDirective:
5501 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005502 case CXCursor_OMPTaskgroupDirective:
5503 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005504 case CXCursor_OMPFlushDirective:
5505 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005506 case CXCursor_OMPOrderedDirective:
5507 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005508 case CXCursor_OMPAtomicDirective:
5509 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005510 case CXCursor_OMPTargetDirective:
5511 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005512 case CXCursor_OMPTargetDataDirective:
5513 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005514 case CXCursor_OMPTargetEnterDataDirective:
5515 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005516 case CXCursor_OMPTargetExitDataDirective:
5517 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005518 case CXCursor_OMPTargetParallelDirective:
5519 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005520 case CXCursor_OMPTargetParallelForDirective:
5521 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005522 case CXCursor_OMPTargetUpdateDirective:
5523 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005524 case CXCursor_OMPTeamsDirective:
5525 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005526 case CXCursor_OMPCancellationPointDirective:
5527 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005528 case CXCursor_OMPCancelDirective:
5529 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005530 case CXCursor_OMPTaskLoopDirective:
5531 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005532 case CXCursor_OMPTaskLoopSimdDirective:
5533 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005534 case CXCursor_OMPMasterTaskLoopDirective:
5535 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005536 case CXCursor_OMPMasterTaskLoopSimdDirective:
5537 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005538 case CXCursor_OMPParallelMasterTaskLoopDirective:
5539 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Alexey Bataev14a388f2019-10-25 10:27:13 -04005540 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5541 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005542 case CXCursor_OMPDistributeDirective:
5543 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005544 case CXCursor_OMPDistributeParallelForDirective:
5545 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005546 case CXCursor_OMPDistributeParallelForSimdDirective:
5547 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005548 case CXCursor_OMPDistributeSimdDirective:
5549 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005550 case CXCursor_OMPTargetParallelForSimdDirective:
5551 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005552 case CXCursor_OMPTargetSimdDirective:
5553 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005554 case CXCursor_OMPTeamsDistributeDirective:
5555 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005556 case CXCursor_OMPTeamsDistributeSimdDirective:
5557 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005558 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5559 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005560 case CXCursor_OMPTeamsDistributeParallelForDirective:
5561 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005562 case CXCursor_OMPTargetTeamsDirective:
5563 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005564 case CXCursor_OMPTargetTeamsDistributeDirective:
5565 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005566 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5567 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005568 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5569 return cxstring::createRef(
5570 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005571 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5572 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005573 case CXCursor_OverloadCandidate:
5574 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005575 case CXCursor_TypeAliasTemplateDecl:
5576 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005577 case CXCursor_StaticAssert:
5578 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005579 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005580 return cxstring::createRef("FriendDecl");
5581 case CXCursor_ConvergentAttr:
5582 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005583 case CXCursor_WarnUnusedAttr:
5584 return cxstring::createRef("attribute(warn_unused)");
5585 case CXCursor_WarnUnusedResultAttr:
5586 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005587 case CXCursor_AlignedAttr:
5588 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005589 }
5590
5591 llvm_unreachable("Unhandled CXCursorKind");
5592}
5593
5594struct GetCursorData {
5595 SourceLocation TokenBeginLoc;
5596 bool PointsAtMacroArgExpansion;
5597 bool VisitedObjCPropertyImplDecl;
5598 SourceLocation VisitedDeclaratorDeclStartLoc;
5599 CXCursor &BestCursor;
5600
5601 GetCursorData(SourceManager &SM,
5602 SourceLocation tokenBegin, CXCursor &outputCursor)
5603 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5604 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5605 VisitedObjCPropertyImplDecl = false;
5606 }
5607};
5608
5609static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5610 CXCursor parent,
5611 CXClientData client_data) {
5612 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5613 CXCursor *BestCursor = &Data->BestCursor;
5614
5615 // If we point inside a macro argument we should provide info of what the
5616 // token is so use the actual cursor, don't replace it with a macro expansion
5617 // cursor.
5618 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5619 return CXChildVisit_Recurse;
5620
5621 if (clang_isDeclaration(cursor.kind)) {
5622 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005623 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005624 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5625 if (MD->isImplicit())
5626 return CXChildVisit_Break;
5627
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005628 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5630 // Check that when we have multiple @class references in the same line,
5631 // that later ones do not override the previous ones.
5632 // If we have:
5633 // @class Foo, Bar;
5634 // source ranges for both start at '@', so 'Bar' will end up overriding
5635 // 'Foo' even though the cursor location was at 'Foo'.
5636 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5637 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005638 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005639 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5640 if (PrevID != ID &&
5641 !PrevID->isThisDeclarationADefinition() &&
5642 !ID->isThisDeclarationADefinition())
5643 return CXChildVisit_Break;
5644 }
5645
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005646 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005647 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5648 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5649 // Check that when we have multiple declarators in the same line,
5650 // that later ones do not override the previous ones.
5651 // If we have:
5652 // int Foo, Bar;
5653 // source ranges for both start at 'int', so 'Bar' will end up overriding
5654 // 'Foo' even though the cursor location was at 'Foo'.
5655 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5656 return CXChildVisit_Break;
5657 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5658
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005659 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005660 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5661 (void)PropImp;
5662 // Check that when we have multiple @synthesize in the same line,
5663 // that later ones do not override the previous ones.
5664 // If we have:
5665 // @synthesize Foo, Bar;
5666 // source ranges for both start at '@', so 'Bar' will end up overriding
5667 // 'Foo' even though the cursor location was at 'Foo'.
5668 if (Data->VisitedObjCPropertyImplDecl)
5669 return CXChildVisit_Break;
5670 Data->VisitedObjCPropertyImplDecl = true;
5671 }
5672 }
5673
5674 if (clang_isExpression(cursor.kind) &&
5675 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005676 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005677 // Avoid having the cursor of an expression replace the declaration cursor
5678 // when the expression source range overlaps the declaration range.
5679 // This can happen for C++ constructor expressions whose range generally
5680 // include the variable declaration, e.g.:
5681 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5682 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5683 D->getLocation() == Data->TokenBeginLoc)
5684 return CXChildVisit_Break;
5685 }
5686 }
5687
5688 // If our current best cursor is the construction of a temporary object,
5689 // don't replace that cursor with a type reference, because we want
5690 // clang_getCursor() to point at the constructor.
5691 if (clang_isExpression(BestCursor->kind) &&
5692 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5693 cursor.kind == CXCursor_TypeRef) {
5694 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5695 // as having the actual point on the type reference.
5696 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5697 return CXChildVisit_Recurse;
5698 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005699
5700 // If we already have an Objective-C superclass reference, don't
5701 // update it further.
5702 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5703 return CXChildVisit_Break;
5704
Guy Benyei11169dd2012-12-18 14:30:41 +00005705 *BestCursor = cursor;
5706 return CXChildVisit_Recurse;
5707}
5708
5709CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005710 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005711 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005713 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005714
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005715 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005716 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5717
5718 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5719 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5720
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005721 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005722 CXFile SearchFile;
5723 unsigned SearchLine, SearchColumn;
5724 CXFile ResultFile;
5725 unsigned ResultLine, ResultColumn;
5726 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5727 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5728 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005729
5730 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5731 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005732 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005733 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 SearchFileName = clang_getFileName(SearchFile);
5735 ResultFileName = clang_getFileName(ResultFile);
5736 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5737 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005738 *Log << llvm::format("(%s:%d:%d) = %s",
5739 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5740 clang_getCString(KindSpelling))
5741 << llvm::format("(%s:%d:%d):%s%s",
5742 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5743 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005744 clang_disposeString(SearchFileName);
5745 clang_disposeString(ResultFileName);
5746 clang_disposeString(KindSpelling);
5747 clang_disposeString(USR);
5748
5749 CXCursor Definition = clang_getCursorDefinition(Result);
5750 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5751 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5752 CXString DefinitionKindSpelling
5753 = clang_getCursorKindSpelling(Definition.kind);
5754 CXFile DefinitionFile;
5755 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005756 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005757 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005758 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005759 *Log << llvm::format(" -> %s(%s:%d:%d)",
5760 clang_getCString(DefinitionKindSpelling),
5761 clang_getCString(DefinitionFileName),
5762 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005763 clang_disposeString(DefinitionFileName);
5764 clang_disposeString(DefinitionKindSpelling);
5765 }
5766 }
5767
5768 return Result;
5769}
5770
5771CXCursor clang_getNullCursor(void) {
5772 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5773}
5774
5775unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005776 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5777 // can't set consistently. For example, when visiting a DeclStmt we will set
5778 // it but we don't set it on the result of clang_getCursorDefinition for
5779 // a reference of the same declaration.
5780 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5781 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5782 // to provide that kind of info.
5783 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005784 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005785 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005786 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005787
Guy Benyei11169dd2012-12-18 14:30:41 +00005788 return X == Y;
5789}
5790
5791unsigned clang_hashCursor(CXCursor C) {
5792 unsigned Index = 0;
5793 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5794 Index = 1;
5795
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005796 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005797 std::make_pair(C.kind, C.data[Index]));
5798}
5799
5800unsigned clang_isInvalid(enum CXCursorKind K) {
5801 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5802}
5803
5804unsigned clang_isDeclaration(enum CXCursorKind K) {
5805 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005806 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5807}
5808
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005809unsigned clang_isInvalidDeclaration(CXCursor C) {
5810 if (clang_isDeclaration(C.kind)) {
5811 if (const Decl *D = getCursorDecl(C))
5812 return D->isInvalidDecl();
5813 }
5814
5815 return 0;
5816}
5817
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005818unsigned clang_isReference(enum CXCursorKind K) {
5819 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5820}
Guy Benyei11169dd2012-12-18 14:30:41 +00005821
5822unsigned clang_isExpression(enum CXCursorKind K) {
5823 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5824}
5825
5826unsigned clang_isStatement(enum CXCursorKind K) {
5827 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5828}
5829
5830unsigned clang_isAttribute(enum CXCursorKind K) {
5831 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5832}
5833
5834unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5835 return K == CXCursor_TranslationUnit;
5836}
5837
5838unsigned clang_isPreprocessing(enum CXCursorKind K) {
5839 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5840}
5841
5842unsigned clang_isUnexposed(enum CXCursorKind K) {
5843 switch (K) {
5844 case CXCursor_UnexposedDecl:
5845 case CXCursor_UnexposedExpr:
5846 case CXCursor_UnexposedStmt:
5847 case CXCursor_UnexposedAttr:
5848 return true;
5849 default:
5850 return false;
5851 }
5852}
5853
5854CXCursorKind clang_getCursorKind(CXCursor C) {
5855 return C.kind;
5856}
5857
5858CXSourceLocation clang_getCursorLocation(CXCursor C) {
5859 if (clang_isReference(C.kind)) {
5860 switch (C.kind) {
5861 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005862 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005863 = getCursorObjCSuperClassRef(C);
5864 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5865 }
5866
5867 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005868 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005869 = getCursorObjCProtocolRef(C);
5870 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5871 }
5872
5873 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005874 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005875 = getCursorObjCClassRef(C);
5876 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5877 }
5878
5879 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005880 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005881 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5882 }
5883
5884 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005885 std::pair<const TemplateDecl *, SourceLocation> P =
5886 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005887 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5888 }
5889
5890 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005891 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005892 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5893 }
5894
5895 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005896 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005897 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5898 }
5899
5900 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005901 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005902 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5903 }
5904
5905 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005906 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005907 if (!BaseSpec)
5908 return clang_getNullLocation();
5909
5910 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5911 return cxloc::translateSourceLocation(getCursorContext(C),
5912 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005913
Guy Benyei11169dd2012-12-18 14:30:41 +00005914 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005915 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005916 }
5917
5918 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005919 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005920 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5921 }
5922
5923 case CXCursor_OverloadedDeclRef:
5924 return cxloc::translateSourceLocation(getCursorContext(C),
5925 getCursorOverloadedDeclRef(C).second);
5926
5927 default:
5928 // FIXME: Need a way to enumerate all non-reference cases.
5929 llvm_unreachable("Missed a reference kind");
5930 }
5931 }
5932
5933 if (clang_isExpression(C.kind))
5934 return cxloc::translateSourceLocation(getCursorContext(C),
5935 getLocationFromExpr(getCursorExpr(C)));
5936
5937 if (clang_isStatement(C.kind))
5938 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005939 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005940
5941 if (C.kind == CXCursor_PreprocessingDirective) {
5942 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5943 return cxloc::translateSourceLocation(getCursorContext(C), L);
5944 }
5945
5946 if (C.kind == CXCursor_MacroExpansion) {
5947 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005948 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005949 return cxloc::translateSourceLocation(getCursorContext(C), L);
5950 }
5951
5952 if (C.kind == CXCursor_MacroDefinition) {
5953 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5954 return cxloc::translateSourceLocation(getCursorContext(C), L);
5955 }
5956
5957 if (C.kind == CXCursor_InclusionDirective) {
5958 SourceLocation L
5959 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5960 return cxloc::translateSourceLocation(getCursorContext(C), L);
5961 }
5962
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005963 if (clang_isAttribute(C.kind)) {
5964 SourceLocation L
5965 = cxcursor::getCursorAttr(C)->getLocation();
5966 return cxloc::translateSourceLocation(getCursorContext(C), L);
5967 }
5968
Guy Benyei11169dd2012-12-18 14:30:41 +00005969 if (!clang_isDeclaration(C.kind))
5970 return clang_getNullLocation();
5971
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005972 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005973 if (!D)
5974 return clang_getNullLocation();
5975
5976 SourceLocation Loc = D->getLocation();
5977 // FIXME: Multiple variables declared in a single declaration
5978 // currently lack the information needed to correctly determine their
5979 // ranges when accounting for the type-specifier. We use context
5980 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5981 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005982 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005983 if (!cxcursor::isFirstInDeclGroup(C))
5984 Loc = VD->getLocation();
5985 }
5986
5987 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005988 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 Loc = MD->getSelectorStartLoc();
5990
5991 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5992}
5993
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005994} // end extern "C"
5995
Guy Benyei11169dd2012-12-18 14:30:41 +00005996CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5997 assert(TU);
5998
5999 // Guard against an invalid SourceLocation, or we may assert in one
6000 // of the following calls.
6001 if (SLoc.isInvalid())
6002 return clang_getNullCursor();
6003
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006004 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006005
6006 // Translate the given source location to make it point at the beginning of
6007 // the token under the cursor.
6008 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
6009 CXXUnit->getASTContext().getLangOpts());
6010
6011 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
6012 if (SLoc.isValid()) {
6013 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
6014 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
6015 /*VisitPreprocessorLast=*/true,
6016 /*VisitIncludedEntities=*/false,
6017 SourceLocation(SLoc));
6018 CursorVis.visitFileRegion();
6019 }
6020
6021 return Result;
6022}
6023
6024static SourceRange getRawCursorExtent(CXCursor C) {
6025 if (clang_isReference(C.kind)) {
6026 switch (C.kind) {
6027 case CXCursor_ObjCSuperClassRef:
6028 return getCursorObjCSuperClassRef(C).second;
6029
6030 case CXCursor_ObjCProtocolRef:
6031 return getCursorObjCProtocolRef(C).second;
6032
6033 case CXCursor_ObjCClassRef:
6034 return getCursorObjCClassRef(C).second;
6035
6036 case CXCursor_TypeRef:
6037 return getCursorTypeRef(C).second;
6038
6039 case CXCursor_TemplateRef:
6040 return getCursorTemplateRef(C).second;
6041
6042 case CXCursor_NamespaceRef:
6043 return getCursorNamespaceRef(C).second;
6044
6045 case CXCursor_MemberRef:
6046 return getCursorMemberRef(C).second;
6047
6048 case CXCursor_CXXBaseSpecifier:
6049 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6050
6051 case CXCursor_LabelRef:
6052 return getCursorLabelRef(C).second;
6053
6054 case CXCursor_OverloadedDeclRef:
6055 return getCursorOverloadedDeclRef(C).second;
6056
6057 case CXCursor_VariableRef:
6058 return getCursorVariableRef(C).second;
6059
6060 default:
6061 // FIXME: Need a way to enumerate all non-reference cases.
6062 llvm_unreachable("Missed a reference kind");
6063 }
6064 }
6065
6066 if (clang_isExpression(C.kind))
6067 return getCursorExpr(C)->getSourceRange();
6068
6069 if (clang_isStatement(C.kind))
6070 return getCursorStmt(C)->getSourceRange();
6071
6072 if (clang_isAttribute(C.kind))
6073 return getCursorAttr(C)->getRange();
6074
6075 if (C.kind == CXCursor_PreprocessingDirective)
6076 return cxcursor::getCursorPreprocessingDirective(C);
6077
6078 if (C.kind == CXCursor_MacroExpansion) {
6079 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006080 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 return TU->mapRangeFromPreamble(Range);
6082 }
6083
6084 if (C.kind == CXCursor_MacroDefinition) {
6085 ASTUnit *TU = getCursorASTUnit(C);
6086 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6087 return TU->mapRangeFromPreamble(Range);
6088 }
6089
6090 if (C.kind == CXCursor_InclusionDirective) {
6091 ASTUnit *TU = getCursorASTUnit(C);
6092 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6093 return TU->mapRangeFromPreamble(Range);
6094 }
6095
6096 if (C.kind == CXCursor_TranslationUnit) {
6097 ASTUnit *TU = getCursorASTUnit(C);
6098 FileID MainID = TU->getSourceManager().getMainFileID();
6099 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6100 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6101 return SourceRange(Start, End);
6102 }
6103
6104 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006105 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 if (!D)
6107 return SourceRange();
6108
6109 SourceRange R = D->getSourceRange();
6110 // FIXME: Multiple variables declared in a single declaration
6111 // currently lack the information needed to correctly determine their
6112 // ranges when accounting for the type-specifier. We use context
6113 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6114 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006115 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006116 if (!cxcursor::isFirstInDeclGroup(C))
6117 R.setBegin(VD->getLocation());
6118 }
6119 return R;
6120 }
6121 return SourceRange();
6122}
6123
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006124/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006125/// the decl-specifier-seq for declarations.
6126static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6127 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006128 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006129 if (!D)
6130 return SourceRange();
6131
6132 SourceRange R = D->getSourceRange();
6133
6134 // Adjust the start of the location for declarations preceded by
6135 // declaration specifiers.
6136 SourceLocation StartLoc;
6137 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6138 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006139 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006140 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006141 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006142 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006143 }
6144
6145 if (StartLoc.isValid() && R.getBegin().isValid() &&
6146 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6147 R.setBegin(StartLoc);
6148
6149 // FIXME: Multiple variables declared in a single declaration
6150 // currently lack the information needed to correctly determine their
6151 // ranges when accounting for the type-specifier. We use context
6152 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6153 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006154 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006155 if (!cxcursor::isFirstInDeclGroup(C))
6156 R.setBegin(VD->getLocation());
6157 }
6158
6159 return R;
6160 }
6161
6162 return getRawCursorExtent(C);
6163}
6164
Guy Benyei11169dd2012-12-18 14:30:41 +00006165CXSourceRange clang_getCursorExtent(CXCursor C) {
6166 SourceRange R = getRawCursorExtent(C);
6167 if (R.isInvalid())
6168 return clang_getNullRange();
6169
6170 return cxloc::translateSourceRange(getCursorContext(C), R);
6171}
6172
6173CXCursor clang_getCursorReferenced(CXCursor C) {
6174 if (clang_isInvalid(C.kind))
6175 return clang_getNullCursor();
6176
6177 CXTranslationUnit tu = getCursorTU(C);
6178 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006179 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006180 if (!D)
6181 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006182 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006183 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006184 if (const ObjCPropertyImplDecl *PropImpl =
6185 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006186 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6187 return MakeCXCursor(Property, tu);
6188
6189 return C;
6190 }
6191
6192 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006193 const Expr *E = getCursorExpr(C);
6194 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006195 if (D) {
6196 CXCursor declCursor = MakeCXCursor(D, tu);
6197 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6198 declCursor);
6199 return declCursor;
6200 }
6201
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006202 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006203 return MakeCursorOverloadedDeclRef(Ovl, tu);
6204
6205 return clang_getNullCursor();
6206 }
6207
6208 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006209 const Stmt *S = getCursorStmt(C);
6210 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006211 if (LabelDecl *label = Goto->getLabel())
6212 if (LabelStmt *labelS = label->getStmt())
6213 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6214
6215 return clang_getNullCursor();
6216 }
Richard Smith66a81862015-05-04 02:25:31 +00006217
Guy Benyei11169dd2012-12-18 14:30:41 +00006218 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006219 if (const MacroDefinitionRecord *Def =
6220 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006221 return MakeMacroDefinitionCursor(Def, tu);
6222 }
6223
6224 if (!clang_isReference(C.kind))
6225 return clang_getNullCursor();
6226
6227 switch (C.kind) {
6228 case CXCursor_ObjCSuperClassRef:
6229 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6230
6231 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006232 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6233 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 return MakeCXCursor(Def, tu);
6235
6236 return MakeCXCursor(Prot, tu);
6237 }
6238
6239 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006240 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6241 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006242 return MakeCXCursor(Def, tu);
6243
6244 return MakeCXCursor(Class, tu);
6245 }
6246
6247 case CXCursor_TypeRef:
6248 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6249
6250 case CXCursor_TemplateRef:
6251 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6252
6253 case CXCursor_NamespaceRef:
6254 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6255
6256 case CXCursor_MemberRef:
6257 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6258
6259 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006260 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006261 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6262 tu ));
6263 }
6264
6265 case CXCursor_LabelRef:
6266 // FIXME: We end up faking the "parent" declaration here because we
6267 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006268 return MakeCXCursor(getCursorLabelRef(C).first,
6269 cxtu::getASTUnit(tu)->getASTContext()
6270 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006271 tu);
6272
6273 case CXCursor_OverloadedDeclRef:
6274 return C;
6275
6276 case CXCursor_VariableRef:
6277 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6278
6279 default:
6280 // We would prefer to enumerate all non-reference cursor kinds here.
6281 llvm_unreachable("Unhandled reference cursor kind");
6282 }
6283}
6284
6285CXCursor clang_getCursorDefinition(CXCursor C) {
6286 if (clang_isInvalid(C.kind))
6287 return clang_getNullCursor();
6288
6289 CXTranslationUnit TU = getCursorTU(C);
6290
6291 bool WasReference = false;
6292 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6293 C = clang_getCursorReferenced(C);
6294 WasReference = true;
6295 }
6296
6297 if (C.kind == CXCursor_MacroExpansion)
6298 return clang_getCursorReferenced(C);
6299
6300 if (!clang_isDeclaration(C.kind))
6301 return clang_getNullCursor();
6302
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006303 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006304 if (!D)
6305 return clang_getNullCursor();
6306
6307 switch (D->getKind()) {
6308 // Declaration kinds that don't really separate the notions of
6309 // declaration and definition.
6310 case Decl::Namespace:
6311 case Decl::Typedef:
6312 case Decl::TypeAlias:
6313 case Decl::TypeAliasTemplate:
6314 case Decl::TemplateTypeParm:
6315 case Decl::EnumConstant:
6316 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006317 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006318 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006319 case Decl::IndirectField:
6320 case Decl::ObjCIvar:
6321 case Decl::ObjCAtDefsField:
6322 case Decl::ImplicitParam:
6323 case Decl::ParmVar:
6324 case Decl::NonTypeTemplateParm:
6325 case Decl::TemplateTemplateParm:
6326 case Decl::ObjCCategoryImpl:
6327 case Decl::ObjCImplementation:
6328 case Decl::AccessSpec:
6329 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006330 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006331 case Decl::ObjCPropertyImpl:
6332 case Decl::FileScopeAsm:
6333 case Decl::StaticAssert:
6334 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006335 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006336 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006337 case Decl::Label: // FIXME: Is this right??
6338 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006339 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006341 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006342 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006343 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006344 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006345 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006346 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006347 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006348 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006349 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006350 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006351 case Decl::Concept:
Tykerb0561b32019-11-17 11:41:55 +01006352 case Decl::LifetimeExtendedTemporary:
Saar Raza0f50d72020-01-18 09:11:43 +02006353 case Decl::RequiresExprBody:
Guy Benyei11169dd2012-12-18 14:30:41 +00006354 return C;
6355
6356 // Declaration kinds that don't make any sense here, but are
6357 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006358 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006359 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006360 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006361 break;
6362
6363 // Declaration kinds for which the definition is not resolvable.
6364 case Decl::UnresolvedUsingTypename:
6365 case Decl::UnresolvedUsingValue:
6366 break;
6367
6368 case Decl::UsingDirective:
6369 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6370 TU);
6371
6372 case Decl::NamespaceAlias:
6373 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6374
6375 case Decl::Enum:
6376 case Decl::Record:
6377 case Decl::CXXRecord:
6378 case Decl::ClassTemplateSpecialization:
6379 case Decl::ClassTemplatePartialSpecialization:
6380 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6381 return MakeCXCursor(Def, TU);
6382 return clang_getNullCursor();
6383
6384 case Decl::Function:
6385 case Decl::CXXMethod:
6386 case Decl::CXXConstructor:
6387 case Decl::CXXDestructor:
6388 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006389 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006391 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006392 return clang_getNullCursor();
6393 }
6394
Larisse Voufo39a1e502013-08-06 01:03:05 +00006395 case Decl::Var:
6396 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006397 case Decl::VarTemplatePartialSpecialization:
6398 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006399 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006400 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 return MakeCXCursor(Def, TU);
6402 return clang_getNullCursor();
6403 }
6404
6405 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006406 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006407 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6408 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6409 return clang_getNullCursor();
6410 }
6411
6412 case Decl::ClassTemplate: {
6413 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6414 ->getDefinition())
6415 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6416 TU);
6417 return clang_getNullCursor();
6418 }
6419
Larisse Voufo39a1e502013-08-06 01:03:05 +00006420 case Decl::VarTemplate: {
6421 if (VarDecl *Def =
6422 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6423 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6424 return clang_getNullCursor();
6425 }
6426
Guy Benyei11169dd2012-12-18 14:30:41 +00006427 case Decl::Using:
6428 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6429 D->getLocation(), TU);
6430
6431 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006432 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006433 return clang_getCursorDefinition(
6434 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6435 TU));
6436
6437 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006438 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 if (Method->isThisDeclarationADefinition())
6440 return C;
6441
6442 // Dig out the method definition in the associated
6443 // @implementation, if we have it.
6444 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006445 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006446 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6447 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6448 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6449 Method->isInstanceMethod()))
6450 if (Def->isThisDeclarationADefinition())
6451 return MakeCXCursor(Def, TU);
6452
6453 return clang_getNullCursor();
6454 }
6455
6456 case Decl::ObjCCategory:
6457 if (ObjCCategoryImplDecl *Impl
6458 = cast<ObjCCategoryDecl>(D)->getImplementation())
6459 return MakeCXCursor(Impl, TU);
6460 return clang_getNullCursor();
6461
6462 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006463 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006464 return MakeCXCursor(Def, TU);
6465 return clang_getNullCursor();
6466
6467 case Decl::ObjCInterface: {
6468 // There are two notions of a "definition" for an Objective-C
6469 // class: the interface and its implementation. When we resolved a
6470 // reference to an Objective-C class, produce the @interface as
6471 // the definition; when we were provided with the interface,
6472 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006473 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006474 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006475 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006476 return MakeCXCursor(Def, TU);
6477 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6478 return MakeCXCursor(Impl, TU);
6479 return clang_getNullCursor();
6480 }
6481
6482 case Decl::ObjCProperty:
6483 // FIXME: We don't really know where to find the
6484 // ObjCPropertyImplDecls that implement this property.
6485 return clang_getNullCursor();
6486
6487 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006488 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006489 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006490 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 return MakeCXCursor(Def, TU);
6492
6493 return clang_getNullCursor();
6494
6495 case Decl::Friend:
6496 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6497 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6498 return clang_getNullCursor();
6499
6500 case Decl::FriendTemplate:
6501 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6502 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6503 return clang_getNullCursor();
6504 }
6505
6506 return clang_getNullCursor();
6507}
6508
6509unsigned clang_isCursorDefinition(CXCursor C) {
6510 if (!clang_isDeclaration(C.kind))
6511 return 0;
6512
6513 return clang_getCursorDefinition(C) == C;
6514}
6515
6516CXCursor clang_getCanonicalCursor(CXCursor C) {
6517 if (!clang_isDeclaration(C.kind))
6518 return C;
6519
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006520 if (const Decl *D = getCursorDecl(C)) {
6521 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6523 return MakeCXCursor(CatD, getCursorTU(C));
6524
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006525 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6526 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006527 return MakeCXCursor(IFD, getCursorTU(C));
6528
6529 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6530 }
6531
6532 return C;
6533}
6534
6535int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6536 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6537}
6538
6539unsigned clang_getNumOverloadedDecls(CXCursor C) {
6540 if (C.kind != CXCursor_OverloadedDeclRef)
6541 return 0;
6542
6543 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006544 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006545 return E->getNumDecls();
6546
6547 if (OverloadedTemplateStorage *S
6548 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6549 return S->size();
6550
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006551 const Decl *D = Storage.get<const Decl *>();
6552 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 return Using->shadow_size();
6554
6555 return 0;
6556}
6557
6558CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6559 if (cursor.kind != CXCursor_OverloadedDeclRef)
6560 return clang_getNullCursor();
6561
6562 if (index >= clang_getNumOverloadedDecls(cursor))
6563 return clang_getNullCursor();
6564
6565 CXTranslationUnit TU = getCursorTU(cursor);
6566 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006567 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006568 return MakeCXCursor(E->decls_begin()[index], TU);
6569
6570 if (OverloadedTemplateStorage *S
6571 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6572 return MakeCXCursor(S->begin()[index], TU);
6573
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006574 const Decl *D = Storage.get<const Decl *>();
6575 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006576 // FIXME: This is, unfortunately, linear time.
6577 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6578 std::advance(Pos, index);
6579 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6580 }
6581
6582 return clang_getNullCursor();
6583}
6584
6585void clang_getDefinitionSpellingAndExtent(CXCursor C,
6586 const char **startBuf,
6587 const char **endBuf,
6588 unsigned *startLine,
6589 unsigned *startColumn,
6590 unsigned *endLine,
6591 unsigned *endColumn) {
6592 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006593 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6595
6596 SourceManager &SM = FD->getASTContext().getSourceManager();
6597 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6598 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6599 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6600 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6601 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6602 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6603}
6604
6605
6606CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6607 unsigned PieceIndex) {
6608 RefNamePieces Pieces;
6609
6610 switch (C.kind) {
6611 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006612 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006613 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6614 E->getQualifierLoc().getSourceRange());
6615 break;
6616
6617 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006618 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6619 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6620 Pieces =
6621 buildPieces(NameFlags, false, E->getNameInfo(),
6622 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6623 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006624 break;
6625
6626 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006627 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006629 const Expr *Callee = OCE->getCallee();
6630 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006631 Callee = ICE->getSubExpr();
6632
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006633 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006634 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6635 DRE->getQualifierLoc().getSourceRange());
6636 }
6637 break;
6638
6639 default:
6640 break;
6641 }
6642
6643 if (Pieces.empty()) {
6644 if (PieceIndex == 0)
6645 return clang_getCursorExtent(C);
6646 } else if (PieceIndex < Pieces.size()) {
6647 SourceRange R = Pieces[PieceIndex];
6648 if (R.isValid())
6649 return cxloc::translateSourceRange(getCursorContext(C), R);
6650 }
6651
6652 return clang_getNullRange();
6653}
6654
6655void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006656 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6657 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006658}
6659
6660void clang_executeOnThread(void (*fn)(void*), void *user_data,
6661 unsigned stack_size) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05006662 llvm::llvm_execute_on_thread(fn, user_data,
6663 stack_size == 0
6664 ? clang::DesiredStackSize
6665 : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006666}
6667
Guy Benyei11169dd2012-12-18 14:30:41 +00006668//===----------------------------------------------------------------------===//
6669// Token-based Operations.
6670//===----------------------------------------------------------------------===//
6671
6672/* CXToken layout:
6673 * int_data[0]: a CXTokenKind
6674 * int_data[1]: starting token location
6675 * int_data[2]: token length
6676 * int_data[3]: reserved
6677 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6678 * otherwise unused.
6679 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006680CXTokenKind clang_getTokenKind(CXToken CXTok) {
6681 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6682}
6683
6684CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6685 switch (clang_getTokenKind(CXTok)) {
6686 case CXToken_Identifier:
6687 case CXToken_Keyword:
6688 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006689 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006690 ->getNameStart());
6691
6692 case CXToken_Literal: {
6693 // We have stashed the starting pointer in the ptr_data field. Use it.
6694 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006695 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006696 }
6697
6698 case CXToken_Punctuation:
6699 case CXToken_Comment:
6700 break;
6701 }
6702
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006703 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006704 LOG_BAD_TU(TU);
6705 return cxstring::createEmpty();
6706 }
6707
Guy Benyei11169dd2012-12-18 14:30:41 +00006708 // We have to find the starting buffer pointer the hard way, by
6709 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006710 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006711 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006712 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006713
6714 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6715 std::pair<FileID, unsigned> LocInfo
6716 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6717 bool Invalid = false;
6718 StringRef Buffer
6719 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6720 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006721 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006722
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006723 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006724}
6725
6726CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006727 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006728 LOG_BAD_TU(TU);
6729 return clang_getNullLocation();
6730 }
6731
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006732 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006733 if (!CXXUnit)
6734 return clang_getNullLocation();
6735
6736 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6737 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6738}
6739
6740CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006741 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006742 LOG_BAD_TU(TU);
6743 return clang_getNullRange();
6744 }
6745
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006746 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006747 if (!CXXUnit)
6748 return clang_getNullRange();
6749
6750 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6751 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6752}
6753
6754static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6755 SmallVectorImpl<CXToken> &CXTokens) {
6756 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6757 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006758 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006759 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006760 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006761
6762 // Cannot tokenize across files.
6763 if (BeginLocInfo.first != EndLocInfo.first)
6764 return;
6765
6766 // Create a lexer
6767 bool Invalid = false;
6768 StringRef Buffer
6769 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6770 if (Invalid)
6771 return;
6772
6773 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6774 CXXUnit->getASTContext().getLangOpts(),
6775 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6776 Lex.SetCommentRetentionState(true);
6777
6778 // Lex tokens until we hit the end of the range.
6779 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6780 Token Tok;
6781 bool previousWasAt = false;
6782 do {
6783 // Lex the next token
6784 Lex.LexFromRawLexer(Tok);
6785 if (Tok.is(tok::eof))
6786 break;
6787
6788 // Initialize the CXToken.
6789 CXToken CXTok;
6790
6791 // - Common fields
6792 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6793 CXTok.int_data[2] = Tok.getLength();
6794 CXTok.int_data[3] = 0;
6795
6796 // - Kind-specific fields
6797 if (Tok.isLiteral()) {
6798 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006799 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006800 } else if (Tok.is(tok::raw_identifier)) {
6801 // Lookup the identifier to determine whether we have a keyword.
6802 IdentifierInfo *II
6803 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6804
6805 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6806 CXTok.int_data[0] = CXToken_Keyword;
6807 }
6808 else {
6809 CXTok.int_data[0] = Tok.is(tok::identifier)
6810 ? CXToken_Identifier
6811 : CXToken_Keyword;
6812 }
6813 CXTok.ptr_data = II;
6814 } else if (Tok.is(tok::comment)) {
6815 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006816 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006817 } else {
6818 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006819 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006820 }
6821 CXTokens.push_back(CXTok);
6822 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006823 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006824}
6825
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006826CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6827 LOG_FUNC_SECTION {
6828 *Log << TU << ' ' << Location;
6829 }
6830
6831 if (isNotUsableTU(TU)) {
6832 LOG_BAD_TU(TU);
6833 return NULL;
6834 }
6835
6836 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6837 if (!CXXUnit)
6838 return NULL;
6839
6840 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6841 if (Begin.isInvalid())
6842 return NULL;
6843 SourceManager &SM = CXXUnit->getSourceManager();
6844 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6845 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6846
6847 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6848
6849 SmallVector<CXToken, 32> CXTokens;
6850 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6851
6852 if (CXTokens.empty())
6853 return NULL;
6854
6855 CXTokens.resize(1);
6856 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6857
6858 memmove(Token, CXTokens.data(), sizeof(CXToken));
6859 return Token;
6860}
6861
Guy Benyei11169dd2012-12-18 14:30:41 +00006862void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6863 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006864 LOG_FUNC_SECTION {
6865 *Log << TU << ' ' << Range;
6866 }
6867
Guy Benyei11169dd2012-12-18 14:30:41 +00006868 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006869 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006870 if (NumTokens)
6871 *NumTokens = 0;
6872
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006873 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006874 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006875 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006876 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006877
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006878 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 if (!CXXUnit || !Tokens || !NumTokens)
6880 return;
6881
6882 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6883
6884 SourceRange R = cxloc::translateCXSourceRange(Range);
6885 if (R.isInvalid())
6886 return;
6887
6888 SmallVector<CXToken, 32> CXTokens;
6889 getTokens(CXXUnit, R, CXTokens);
6890
6891 if (CXTokens.empty())
6892 return;
6893
Serge Pavlov52525732018-02-21 02:02:39 +00006894 *Tokens = static_cast<CXToken *>(
6895 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006896 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6897 *NumTokens = CXTokens.size();
6898}
6899
6900void clang_disposeTokens(CXTranslationUnit TU,
6901 CXToken *Tokens, unsigned NumTokens) {
6902 free(Tokens);
6903}
6904
Guy Benyei11169dd2012-12-18 14:30:41 +00006905//===----------------------------------------------------------------------===//
6906// Token annotation APIs.
6907//===----------------------------------------------------------------------===//
6908
Guy Benyei11169dd2012-12-18 14:30:41 +00006909static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6910 CXCursor parent,
6911 CXClientData client_data);
6912static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6913 CXClientData client_data);
6914
6915namespace {
6916class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006917 CXToken *Tokens;
6918 CXCursor *Cursors;
6919 unsigned NumTokens;
6920 unsigned TokIdx;
6921 unsigned PreprocessingTokIdx;
6922 CursorVisitor AnnotateVis;
6923 SourceManager &SrcMgr;
6924 bool HasContextSensitiveKeywords;
6925
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006926 struct PostChildrenAction {
6927 CXCursor cursor;
6928 enum Action { Invalid, Ignore, Postpone } action;
6929 };
6930 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6931
Guy Benyei11169dd2012-12-18 14:30:41 +00006932 struct PostChildrenInfo {
6933 CXCursor Cursor;
6934 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006935 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006937 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006938 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006939 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006940
6941 CXToken &getTok(unsigned Idx) {
6942 assert(Idx < NumTokens);
6943 return Tokens[Idx];
6944 }
6945 const CXToken &getTok(unsigned Idx) const {
6946 assert(Idx < NumTokens);
6947 return Tokens[Idx];
6948 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 bool MoreTokens() const { return TokIdx < NumTokens; }
6950 unsigned NextToken() const { return TokIdx; }
6951 void AdvanceToken() { ++TokIdx; }
6952 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006953 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006954 }
6955 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006956 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006957 }
6958 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006959 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006960 }
6961
6962 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006963 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006964 SourceRange);
6965
6966public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006967 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006968 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006969 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006970 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006971 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006972 AnnotateTokensVisitor, this,
6973 /*VisitPreprocessorLast=*/true,
6974 /*VisitIncludedEntities=*/false,
6975 RegionOfInterest,
6976 /*VisitDeclsOnly=*/false,
6977 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006978 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006979 HasContextSensitiveKeywords(false) { }
6980
6981 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6982 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006983 bool IsIgnoredChildCursor(CXCursor cursor) const;
6984 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6985
Guy Benyei11169dd2012-12-18 14:30:41 +00006986 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006987 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6988 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6989
Guy Benyei11169dd2012-12-18 14:30:41 +00006990 void AnnotateTokens();
6991
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006992 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006993 /// context-sensitive keywords.
6994 bool hasContextSensitiveKeywords() const {
6995 return HasContextSensitiveKeywords;
6996 }
6997
6998 ~AnnotateTokensWorker() {
6999 assert(PostChildrenInfos.empty());
7000 }
7001};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007002}
Guy Benyei11169dd2012-12-18 14:30:41 +00007003
7004void AnnotateTokensWorker::AnnotateTokens() {
7005 // Walk the AST within the region of interest, annotating tokens
7006 // along the way.
7007 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007008}
Guy Benyei11169dd2012-12-18 14:30:41 +00007009
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007010bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
7011 if (PostChildrenInfos.empty())
7012 return false;
7013
7014 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
7015 if (ChildAction.cursor == cursor &&
7016 ChildAction.action == PostChildrenAction::Ignore) {
7017 return true;
7018 }
7019 }
7020
7021 return false;
7022}
7023
7024const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
7025 if (!clang_isExpression(Cursor.kind))
7026 return nullptr;
7027
7028 const Expr *E = getCursorExpr(Cursor);
7029 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7030 const OverloadedOperatorKind Kind = OCE->getOperator();
7031 if (Kind == OO_Call || Kind == OO_Subscript)
7032 return OCE;
7033 }
7034
7035 return nullptr;
7036}
7037
7038AnnotateTokensWorker::PostChildrenActions
7039AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7040 PostChildrenActions actions;
7041
7042 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
7043 // visited before the arguments to the operator call. For the Call and
7044 // Subscript operator the range of this DeclRefExpr includes the whole call
7045 // expression, so that all tokens in that range would be mapped to the
7046 // operator function, including the tokens of the arguments. To avoid that,
7047 // ensure to visit this DeclRefExpr as last node.
7048 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7049 const Expr *Callee = OCE->getCallee();
7050 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7051 const Expr *SubExpr = ICE->getSubExpr();
7052 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007053 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007054 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7055
7056 // Visit the DeclRefExpr as last.
7057 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7058 actions.push_back({cxChild, PostChildrenAction::Postpone});
7059
7060 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7061 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7062 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7063 actions.push_back({cxChild, PostChildrenAction::Ignore});
7064 }
7065 }
7066 }
7067
7068 return actions;
7069}
7070
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007071static inline void updateCursorAnnotation(CXCursor &Cursor,
7072 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007073 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007074 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007075 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007076}
7077
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007078/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007079//// between the cursor location and the source range is the same as
7080/// \arg compResult.
7081///
7082/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7083/// Pass RangeOverlap to annotate tokens inside a range.
7084void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7085 RangeComparisonResult compResult,
7086 SourceRange range) {
7087 while (MoreTokens()) {
7088 const unsigned I = NextToken();
7089 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007090 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7091 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007092
7093 SourceLocation TokLoc = GetTokenLoc(I);
7094 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007095 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007096 AdvanceToken();
7097 continue;
7098 }
7099 break;
7100 }
7101}
7102
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007103/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007104/// \returns true if it advanced beyond all macro tokens, false otherwise.
7105bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007106 CXCursor updateC,
7107 RangeComparisonResult compResult,
7108 SourceRange range) {
7109 assert(MoreTokens());
7110 assert(isFunctionMacroToken(NextToken()) &&
7111 "Should be called only for macro arg tokens");
7112
7113 // This works differently than annotateAndAdvanceTokens; because expanded
7114 // macro arguments can have arbitrary translation-unit source order, we do not
7115 // advance the token index one by one until a token fails the range test.
7116 // We only advance once past all of the macro arg tokens if all of them
7117 // pass the range test. If one of them fails we keep the token index pointing
7118 // at the start of the macro arg tokens so that the failing token will be
7119 // annotated by a subsequent annotation try.
7120
7121 bool atLeastOneCompFail = false;
7122
7123 unsigned I = NextToken();
7124 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7125 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7126 if (TokLoc.isFileID())
7127 continue; // not macro arg token, it's parens or comma.
7128 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7129 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7130 Cursors[I] = updateC;
7131 } else
7132 atLeastOneCompFail = true;
7133 }
7134
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007135 if (atLeastOneCompFail)
7136 return false;
7137
7138 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7139 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007140}
7141
7142enum CXChildVisitResult
7143AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007144 SourceRange cursorRange = getRawCursorExtent(cursor);
7145 if (cursorRange.isInvalid())
7146 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007147
7148 if (IsIgnoredChildCursor(cursor))
7149 return CXChildVisit_Continue;
7150
Guy Benyei11169dd2012-12-18 14:30:41 +00007151 if (!HasContextSensitiveKeywords) {
7152 // Objective-C properties can have context-sensitive keywords.
7153 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007154 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007155 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7156 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7157 }
7158 // Objective-C methods can have context-sensitive keywords.
7159 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7160 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007161 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007162 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7163 if (Method->getObjCDeclQualifier())
7164 HasContextSensitiveKeywords = true;
7165 else {
David Majnemer59f77922016-06-24 04:05:48 +00007166 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007167 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007168 HasContextSensitiveKeywords = true;
7169 break;
7170 }
7171 }
7172 }
7173 }
7174 }
7175 // C++ methods can have context-sensitive keywords.
7176 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007177 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007178 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7179 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7180 HasContextSensitiveKeywords = true;
7181 }
7182 }
7183 // C++ classes can have context-sensitive keywords.
7184 else if (cursor.kind == CXCursor_StructDecl ||
7185 cursor.kind == CXCursor_ClassDecl ||
7186 cursor.kind == CXCursor_ClassTemplate ||
7187 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007188 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007189 if (D->hasAttr<FinalAttr>())
7190 HasContextSensitiveKeywords = true;
7191 }
7192 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007193
7194 // Don't override a property annotation with its getter/setter method.
7195 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7196 parent.kind == CXCursor_ObjCPropertyDecl)
7197 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007198
7199 if (clang_isPreprocessing(cursor.kind)) {
7200 // Items in the preprocessing record are kept separate from items in
7201 // declarations, so we keep a separate token index.
7202 unsigned SavedTokIdx = TokIdx;
7203 TokIdx = PreprocessingTokIdx;
7204
7205 // Skip tokens up until we catch up to the beginning of the preprocessing
7206 // entry.
7207 while (MoreTokens()) {
7208 const unsigned I = NextToken();
7209 SourceLocation TokLoc = GetTokenLoc(I);
7210 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7211 case RangeBefore:
7212 AdvanceToken();
7213 continue;
7214 case RangeAfter:
7215 case RangeOverlap:
7216 break;
7217 }
7218 break;
7219 }
7220
7221 // Look at all of the tokens within this range.
7222 while (MoreTokens()) {
7223 const unsigned I = NextToken();
7224 SourceLocation TokLoc = GetTokenLoc(I);
7225 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7226 case RangeBefore:
7227 llvm_unreachable("Infeasible");
7228 case RangeAfter:
7229 break;
7230 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007231 // For macro expansions, just note where the beginning of the macro
7232 // expansion occurs.
7233 if (cursor.kind == CXCursor_MacroExpansion) {
7234 if (TokLoc == cursorRange.getBegin())
7235 Cursors[I] = cursor;
7236 AdvanceToken();
7237 break;
7238 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007239 // We may have already annotated macro names inside macro definitions.
7240 if (Cursors[I].kind != CXCursor_MacroExpansion)
7241 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007242 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007243 continue;
7244 }
7245 break;
7246 }
7247
7248 // Save the preprocessing token index; restore the non-preprocessing
7249 // token index.
7250 PreprocessingTokIdx = TokIdx;
7251 TokIdx = SavedTokIdx;
7252 return CXChildVisit_Recurse;
7253 }
7254
7255 if (cursorRange.isInvalid())
7256 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007257
7258 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007259 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 const enum CXCursorKind K = clang_getCursorKind(parent);
7261 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007262 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7263 // Attributes are annotated out-of-order, skip tokens until we reach it.
7264 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007265 ? clang_getNullCursor() : parent;
7266
7267 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7268
7269 // Avoid having the cursor of an expression "overwrite" the annotation of the
7270 // variable declaration that it belongs to.
7271 // This can happen for C++ constructor expressions whose range generally
7272 // include the variable declaration, e.g.:
7273 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007274 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007275 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007276 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007277 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007278 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7279 E->getBeginLoc() == D->getLocation() &&
7280 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007281 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007282 AdvanceToken();
7283 }
7284 }
7285 }
7286
7287 // Before recursing into the children keep some state that we are going
7288 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7289 // extra work after the child nodes are visited.
7290 // Note that we don't call VisitChildren here to avoid traversing statements
7291 // code-recursively which can blow the stack.
7292
7293 PostChildrenInfo Info;
7294 Info.Cursor = cursor;
7295 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007296 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007297 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007298 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007299 PostChildrenInfos.push_back(Info);
7300
7301 return CXChildVisit_Recurse;
7302}
7303
7304bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7305 if (PostChildrenInfos.empty())
7306 return false;
7307 const PostChildrenInfo &Info = PostChildrenInfos.back();
7308 if (!clang_equalCursors(Info.Cursor, cursor))
7309 return false;
7310
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007311 HandlePostPonedChildCursors(Info);
7312
Guy Benyei11169dd2012-12-18 14:30:41 +00007313 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7314 const unsigned AfterChildren = NextToken();
7315 SourceRange cursorRange = Info.CursorRange;
7316
7317 // Scan the tokens that are at the end of the cursor, but are not captured
7318 // but the child cursors.
7319 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7320
7321 // Scan the tokens that are at the beginning of the cursor, but are not
7322 // capture by the child cursors.
7323 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7324 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7325 break;
7326
7327 Cursors[I] = cursor;
7328 }
7329
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007330 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7331 // encountered the attribute cursor.
7332 if (clang_isAttribute(cursor.kind))
7333 TokIdx = Info.BeforeReachingCursorIdx;
7334
Guy Benyei11169dd2012-12-18 14:30:41 +00007335 PostChildrenInfos.pop_back();
7336 return false;
7337}
7338
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007339void AnnotateTokensWorker::HandlePostPonedChildCursors(
7340 const PostChildrenInfo &Info) {
7341 for (const auto &ChildAction : Info.ChildActions) {
7342 if (ChildAction.action == PostChildrenAction::Postpone) {
7343 HandlePostPonedChildCursor(ChildAction.cursor,
7344 Info.BeforeChildrenTokenIdx);
7345 }
7346 }
7347}
7348
7349void AnnotateTokensWorker::HandlePostPonedChildCursor(
7350 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007351 unsigned I = StartTokenIndex;
7352
7353 // The bracket tokens of a Call or Subscript operator are mapped to
7354 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7355 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7356 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007357 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7358 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007359 if (clang_Range_isNull(CXRefNameRange))
7360 break; // All ranges handled.
7361
7362 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7363 while (I < NumTokens) {
7364 const SourceLocation TokenLocation = GetTokenLoc(I);
7365 if (!TokenLocation.isValid())
7366 break;
7367
7368 // Adapt the end range, because LocationCompare() reports
7369 // RangeOverlap even for the not-inclusive end location.
7370 const SourceLocation fixedEnd =
7371 RefNameRange.getEnd().getLocWithOffset(-1);
7372 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7373
7374 const RangeComparisonResult ComparisonResult =
7375 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7376
7377 if (ComparisonResult == RangeOverlap) {
7378 Cursors[I++] = Cursor;
7379 } else if (ComparisonResult == RangeBefore) {
7380 ++I; // Not relevant token, check next one.
7381 } else if (ComparisonResult == RangeAfter) {
7382 break; // All tokens updated for current range, check next.
7383 }
7384 }
7385 }
7386}
7387
Guy Benyei11169dd2012-12-18 14:30:41 +00007388static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7389 CXCursor parent,
7390 CXClientData client_data) {
7391 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7392}
7393
7394static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7395 CXClientData client_data) {
7396 return static_cast<AnnotateTokensWorker*>(client_data)->
7397 postVisitChildren(cursor);
7398}
7399
7400namespace {
7401
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007402/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007403/// and mark tokens that are macro arguments. This info is used by the
7404/// AnnotateTokensWorker.
7405class MarkMacroArgTokensVisitor {
7406 SourceManager &SM;
7407 CXToken *Tokens;
7408 unsigned NumTokens;
7409 unsigned CurIdx;
7410
7411public:
7412 MarkMacroArgTokensVisitor(SourceManager &SM,
7413 CXToken *tokens, unsigned numTokens)
7414 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7415
7416 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7417 if (cursor.kind != CXCursor_MacroExpansion)
7418 return CXChildVisit_Continue;
7419
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007420 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007421 if (macroRange.getBegin() == macroRange.getEnd())
7422 return CXChildVisit_Continue; // it's not a function macro.
7423
7424 for (; CurIdx < NumTokens; ++CurIdx) {
7425 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7426 macroRange.getBegin()))
7427 break;
7428 }
7429
7430 if (CurIdx == NumTokens)
7431 return CXChildVisit_Break;
7432
7433 for (; CurIdx < NumTokens; ++CurIdx) {
7434 SourceLocation tokLoc = getTokenLoc(CurIdx);
7435 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7436 break;
7437
7438 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7439 }
7440
7441 if (CurIdx == NumTokens)
7442 return CXChildVisit_Break;
7443
7444 return CXChildVisit_Continue;
7445 }
7446
7447private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007448 CXToken &getTok(unsigned Idx) {
7449 assert(Idx < NumTokens);
7450 return Tokens[Idx];
7451 }
7452 const CXToken &getTok(unsigned Idx) const {
7453 assert(Idx < NumTokens);
7454 return Tokens[Idx];
7455 }
7456
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007458 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007459 }
7460
7461 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7462 // The third field is reserved and currently not used. Use it here
7463 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007464 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007465 }
7466};
7467
7468} // end anonymous namespace
7469
7470static CXChildVisitResult
7471MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7472 CXClientData client_data) {
7473 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7474 parent);
7475}
7476
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007477/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007478/// \returns true if lexing was finished, false otherwise.
7479static bool lexNext(Lexer &Lex, Token &Tok,
7480 unsigned &NextIdx, unsigned NumTokens) {
7481 if (NextIdx >= NumTokens)
7482 return true;
7483
7484 ++NextIdx;
7485 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007486 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007487}
7488
Guy Benyei11169dd2012-12-18 14:30:41 +00007489static void annotatePreprocessorTokens(CXTranslationUnit TU,
7490 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007491 CXCursor *Cursors,
7492 CXToken *Tokens,
7493 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007494 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007495
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007496 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007497 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7498 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007499 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007500 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007501 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007502
7503 if (BeginLocInfo.first != EndLocInfo.first)
7504 return;
7505
7506 StringRef Buffer;
7507 bool Invalid = false;
7508 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7509 if (Buffer.empty() || Invalid)
7510 return;
7511
7512 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7513 CXXUnit->getASTContext().getLangOpts(),
7514 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7515 Buffer.end());
7516 Lex.SetCommentRetentionState(true);
7517
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007518 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007519 // Lex tokens in raw mode until we hit the end of the range, to avoid
7520 // entering #includes or expanding macros.
7521 while (true) {
7522 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007523 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7524 break;
7525 unsigned TokIdx = NextIdx-1;
7526 assert(Tok.getLocation() ==
7527 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007528
7529 reprocess:
7530 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007531 // We have found a preprocessing directive. Annotate the tokens
7532 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007533 //
7534 // FIXME: Some simple tests here could identify macro definitions and
7535 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007536
7537 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007538 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7539 break;
7540
Craig Topper69186e72014-06-08 08:38:04 +00007541 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007542 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007543 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7544 break;
7545
7546 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007547 IdentifierInfo &II =
7548 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007549 SourceLocation MappedTokLoc =
7550 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7551 MI = getMacroInfo(II, MappedTokLoc, TU);
7552 }
7553 }
7554
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007555 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007556 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007557 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7558 finished = true;
7559 break;
7560 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007561 // If we are in a macro definition, check if the token was ever a
7562 // macro name and annotate it if that's the case.
7563 if (MI) {
7564 SourceLocation SaveLoc = Tok.getLocation();
7565 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007566 MacroDefinitionRecord *MacroDef =
7567 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007568 Tok.setLocation(SaveLoc);
7569 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007570 Cursors[NextIdx - 1] =
7571 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007572 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007573 } while (!Tok.isAtStartOfLine());
7574
7575 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7576 assert(TokIdx <= LastIdx);
7577 SourceLocation EndLoc =
7578 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7579 CXCursor Cursor =
7580 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7581
7582 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007583 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007584
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007585 if (finished)
7586 break;
7587 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007588 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007589 }
7590}
7591
7592// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007593static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7594 CXToken *Tokens, unsigned NumTokens,
7595 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007596 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007597 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7598 setThreadBackgroundPriority();
7599
7600 // Determine the region of interest, which contains all of the tokens.
7601 SourceRange RegionOfInterest;
7602 RegionOfInterest.setBegin(
7603 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7604 RegionOfInterest.setEnd(
7605 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7606 Tokens[NumTokens-1])));
7607
Guy Benyei11169dd2012-12-18 14:30:41 +00007608 // Relex the tokens within the source range to look for preprocessing
7609 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007610 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007611
7612 // If begin location points inside a macro argument, set it to the expansion
7613 // location so we can have the full context when annotating semantically.
7614 {
7615 SourceManager &SM = CXXUnit->getSourceManager();
7616 SourceLocation Loc =
7617 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7618 if (Loc.isMacroID())
7619 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7620 }
7621
Guy Benyei11169dd2012-12-18 14:30:41 +00007622 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7623 // Search and mark tokens that are macro argument expansions.
7624 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7625 Tokens, NumTokens);
7626 CursorVisitor MacroArgMarker(TU,
7627 MarkMacroArgTokensVisitorDelegate, &Visitor,
7628 /*VisitPreprocessorLast=*/true,
7629 /*VisitIncludedEntities=*/false,
7630 RegionOfInterest);
7631 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7632 }
7633
7634 // Annotate all of the source locations in the region of interest that map to
7635 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007636 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007637
7638 // FIXME: We use a ridiculous stack size here because the data-recursion
7639 // algorithm uses a large stack frame than the non-data recursive version,
7640 // and AnnotationTokensWorker currently transforms the data-recursion
7641 // algorithm back into a traditional recursion by explicitly calling
7642 // VisitChildren(). We will need to remove this explicit recursive call.
7643 W.AnnotateTokens();
7644
7645 // If we ran into any entities that involve context-sensitive keywords,
7646 // take another pass through the tokens to mark them as such.
7647 if (W.hasContextSensitiveKeywords()) {
7648 for (unsigned I = 0; I != NumTokens; ++I) {
7649 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7650 continue;
7651
7652 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7653 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007654 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007655 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7656 if (Property->getPropertyAttributesAsWritten() != 0 &&
7657 llvm::StringSwitch<bool>(II->getName())
7658 .Case("readonly", true)
7659 .Case("assign", true)
7660 .Case("unsafe_unretained", true)
7661 .Case("readwrite", true)
7662 .Case("retain", true)
7663 .Case("copy", true)
7664 .Case("nonatomic", true)
7665 .Case("atomic", true)
7666 .Case("getter", true)
7667 .Case("setter", true)
7668 .Case("strong", true)
7669 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007670 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007671 .Default(false))
7672 Tokens[I].int_data[0] = CXToken_Keyword;
7673 }
7674 continue;
7675 }
7676
7677 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7678 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7679 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7680 if (llvm::StringSwitch<bool>(II->getName())
7681 .Case("in", true)
7682 .Case("out", true)
7683 .Case("inout", true)
7684 .Case("oneway", true)
7685 .Case("bycopy", true)
7686 .Case("byref", true)
7687 .Default(false))
7688 Tokens[I].int_data[0] = CXToken_Keyword;
7689 continue;
7690 }
7691
7692 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7693 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7694 Tokens[I].int_data[0] = CXToken_Keyword;
7695 continue;
7696 }
7697 }
7698 }
7699}
7700
Guy Benyei11169dd2012-12-18 14:30:41 +00007701void clang_annotateTokens(CXTranslationUnit TU,
7702 CXToken *Tokens, unsigned NumTokens,
7703 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007704 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007705 LOG_BAD_TU(TU);
7706 return;
7707 }
7708 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007709 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007710 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007711 }
7712
7713 LOG_FUNC_SECTION {
7714 *Log << TU << ' ';
7715 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7716 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7717 *Log << clang_getRange(bloc, eloc);
7718 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007719
7720 // Any token we don't specifically annotate will have a NULL cursor.
7721 CXCursor C = clang_getNullCursor();
7722 for (unsigned I = 0; I != NumTokens; ++I)
7723 Cursors[I] = C;
7724
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007725 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007726 if (!CXXUnit)
7727 return;
7728
7729 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007730
7731 auto AnnotateTokensImpl = [=]() {
7732 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7733 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007734 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007735 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007736 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7737 }
7738}
7739
Guy Benyei11169dd2012-12-18 14:30:41 +00007740//===----------------------------------------------------------------------===//
7741// Operations for querying linkage of a cursor.
7742//===----------------------------------------------------------------------===//
7743
Guy Benyei11169dd2012-12-18 14:30:41 +00007744CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7745 if (!clang_isDeclaration(cursor.kind))
7746 return CXLinkage_Invalid;
7747
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007748 const Decl *D = cxcursor::getCursorDecl(cursor);
7749 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007750 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007751 case NoLinkage:
7752 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007753 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007754 case InternalLinkage: return CXLinkage_Internal;
7755 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007756 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 case ExternalLinkage: return CXLinkage_External;
7758 };
7759
7760 return CXLinkage_Invalid;
7761}
Guy Benyei11169dd2012-12-18 14:30:41 +00007762
7763//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007764// Operations for querying visibility of a cursor.
7765//===----------------------------------------------------------------------===//
7766
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007767CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7768 if (!clang_isDeclaration(cursor.kind))
7769 return CXVisibility_Invalid;
7770
7771 const Decl *D = cxcursor::getCursorDecl(cursor);
7772 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7773 switch (ND->getVisibility()) {
7774 case HiddenVisibility: return CXVisibility_Hidden;
7775 case ProtectedVisibility: return CXVisibility_Protected;
7776 case DefaultVisibility: return CXVisibility_Default;
7777 };
7778
7779 return CXVisibility_Invalid;
7780}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007781
7782//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007783// Operations for querying language of a cursor.
7784//===----------------------------------------------------------------------===//
7785
7786static CXLanguageKind getDeclLanguage(const Decl *D) {
7787 if (!D)
7788 return CXLanguage_C;
7789
7790 switch (D->getKind()) {
7791 default:
7792 break;
7793 case Decl::ImplicitParam:
7794 case Decl::ObjCAtDefsField:
7795 case Decl::ObjCCategory:
7796 case Decl::ObjCCategoryImpl:
7797 case Decl::ObjCCompatibleAlias:
7798 case Decl::ObjCImplementation:
7799 case Decl::ObjCInterface:
7800 case Decl::ObjCIvar:
7801 case Decl::ObjCMethod:
7802 case Decl::ObjCProperty:
7803 case Decl::ObjCPropertyImpl:
7804 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007805 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007806 return CXLanguage_ObjC;
7807 case Decl::CXXConstructor:
7808 case Decl::CXXConversion:
7809 case Decl::CXXDestructor:
7810 case Decl::CXXMethod:
7811 case Decl::CXXRecord:
7812 case Decl::ClassTemplate:
7813 case Decl::ClassTemplatePartialSpecialization:
7814 case Decl::ClassTemplateSpecialization:
7815 case Decl::Friend:
7816 case Decl::FriendTemplate:
7817 case Decl::FunctionTemplate:
7818 case Decl::LinkageSpec:
7819 case Decl::Namespace:
7820 case Decl::NamespaceAlias:
7821 case Decl::NonTypeTemplateParm:
7822 case Decl::StaticAssert:
7823 case Decl::TemplateTemplateParm:
7824 case Decl::TemplateTypeParm:
7825 case Decl::UnresolvedUsingTypename:
7826 case Decl::UnresolvedUsingValue:
7827 case Decl::Using:
7828 case Decl::UsingDirective:
7829 case Decl::UsingShadow:
7830 return CXLanguage_CPlusPlus;
7831 }
7832
7833 return CXLanguage_C;
7834}
7835
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007836static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7837 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007838 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007839
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007840 switch (D->getAvailability()) {
7841 case AR_Available:
7842 case AR_NotYetIntroduced:
7843 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007844 return getCursorAvailabilityForDecl(
7845 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007846 return CXAvailability_Available;
7847
7848 case AR_Deprecated:
7849 return CXAvailability_Deprecated;
7850
7851 case AR_Unavailable:
7852 return CXAvailability_NotAvailable;
7853 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007854
7855 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007856}
7857
Guy Benyei11169dd2012-12-18 14:30:41 +00007858enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7859 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007860 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7861 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007862
7863 return CXAvailability_Available;
7864}
7865
7866static CXVersion convertVersion(VersionTuple In) {
7867 CXVersion Out = { -1, -1, -1 };
7868 if (In.empty())
7869 return Out;
7870
7871 Out.Major = In.getMajor();
7872
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007873 Optional<unsigned> Minor = In.getMinor();
7874 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007875 Out.Minor = *Minor;
7876 else
7877 return Out;
7878
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007879 Optional<unsigned> Subminor = In.getSubminor();
7880 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007881 Out.Subminor = *Subminor;
7882
7883 return Out;
7884}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007885
Alex Lorenz1345ea22017-06-12 19:06:30 +00007886static void getCursorPlatformAvailabilityForDecl(
7887 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7888 int *always_unavailable, CXString *unavailable_message,
7889 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007890 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007891 for (auto A : D->attrs()) {
7892 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007893 HadAvailAttr = true;
7894 if (always_deprecated)
7895 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007896 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007897 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007898 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007899 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007900 continue;
7901 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007902
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007903 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007904 HadAvailAttr = true;
7905 if (always_unavailable)
7906 *always_unavailable = 1;
7907 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007908 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007909 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7910 }
7911 continue;
7912 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007913
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007914 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007915 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007916 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007917 }
7918 }
7919
7920 if (!HadAvailAttr)
7921 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7922 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007923 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7924 deprecated_message, always_unavailable, unavailable_message,
7925 AvailabilityAttrs);
7926
7927 if (AvailabilityAttrs.empty())
7928 return;
7929
Fangrui Song55fab262018-09-26 22:16:28 +00007930 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007931 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7932 return LHS->getPlatform()->getName() <
7933 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007934 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007935 ASTContext &Ctx = D->getASTContext();
7936 auto It = std::unique(
7937 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7938 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7939 if (LHS->getPlatform() != RHS->getPlatform())
7940 return false;
7941
7942 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7943 LHS->getDeprecated() == RHS->getDeprecated() &&
7944 LHS->getObsoleted() == RHS->getObsoleted() &&
7945 LHS->getMessage() == RHS->getMessage() &&
7946 LHS->getReplacement() == RHS->getReplacement())
7947 return true;
7948
7949 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7950 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7951 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7952 return false;
7953
7954 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7955 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7956
7957 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7958 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7959 if (LHS->getMessage().empty())
7960 LHS->setMessage(Ctx, RHS->getMessage());
7961 if (LHS->getReplacement().empty())
7962 LHS->setReplacement(Ctx, RHS->getReplacement());
7963 }
7964
7965 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7966 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7967 if (LHS->getMessage().empty())
7968 LHS->setMessage(Ctx, RHS->getMessage());
7969 if (LHS->getReplacement().empty())
7970 LHS->setReplacement(Ctx, RHS->getReplacement());
7971 }
7972
7973 return true;
7974 });
7975 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007976}
7977
Alex Lorenz1345ea22017-06-12 19:06:30 +00007978int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007979 CXString *deprecated_message,
7980 int *always_unavailable,
7981 CXString *unavailable_message,
7982 CXPlatformAvailability *availability,
7983 int availability_size) {
7984 if (always_deprecated)
7985 *always_deprecated = 0;
7986 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007987 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007988 if (always_unavailable)
7989 *always_unavailable = 0;
7990 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007991 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007992
Guy Benyei11169dd2012-12-18 14:30:41 +00007993 if (!clang_isDeclaration(cursor.kind))
7994 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007995
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007996 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007997 if (!D)
7998 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007999
Alex Lorenz1345ea22017-06-12 19:06:30 +00008000 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
8001 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
8002 always_unavailable, unavailable_message,
8003 AvailabilityAttrs);
8004 for (const auto &Avail :
8005 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
8006 .take_front(availability_size))) {
8007 availability[Avail.index()].Platform =
8008 cxstring::createDup(Avail.value()->getPlatform()->getName());
8009 availability[Avail.index()].Introduced =
8010 convertVersion(Avail.value()->getIntroduced());
8011 availability[Avail.index()].Deprecated =
8012 convertVersion(Avail.value()->getDeprecated());
8013 availability[Avail.index()].Obsoleted =
8014 convertVersion(Avail.value()->getObsoleted());
8015 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
8016 availability[Avail.index()].Message =
8017 cxstring::createDup(Avail.value()->getMessage());
8018 }
8019
8020 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008021}
Alex Lorenz1345ea22017-06-12 19:06:30 +00008022
Guy Benyei11169dd2012-12-18 14:30:41 +00008023void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
8024 clang_disposeString(availability->Platform);
8025 clang_disposeString(availability->Message);
8026}
8027
8028CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
8029 if (clang_isDeclaration(cursor.kind))
8030 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
8031
8032 return CXLanguage_Invalid;
8033}
8034
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00008035CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
8036 const Decl *D = cxcursor::getCursorDecl(cursor);
8037 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8038 switch (VD->getTLSKind()) {
8039 case VarDecl::TLS_None:
8040 return CXTLS_None;
8041 case VarDecl::TLS_Dynamic:
8042 return CXTLS_Dynamic;
8043 case VarDecl::TLS_Static:
8044 return CXTLS_Static;
8045 }
8046 }
8047
8048 return CXTLS_None;
8049}
8050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008051 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008052 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008053 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008054static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008055 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008056 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008057
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008058 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008059 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8060 return FunTmpl;
8061
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008062 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008063 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8064 return ClassTmpl;
8065
8066 return D;
8067}
8068
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008069
8070enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8071 StorageClass sc = SC_None;
8072 const Decl *D = getCursorDecl(C);
8073 if (D) {
8074 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8075 sc = FD->getStorageClass();
8076 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8077 sc = VD->getStorageClass();
8078 } else {
8079 return CX_SC_Invalid;
8080 }
8081 } else {
8082 return CX_SC_Invalid;
8083 }
8084 switch (sc) {
8085 case SC_None:
8086 return CX_SC_None;
8087 case SC_Extern:
8088 return CX_SC_Extern;
8089 case SC_Static:
8090 return CX_SC_Static;
8091 case SC_PrivateExtern:
8092 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008093 case SC_Auto:
8094 return CX_SC_Auto;
8095 case SC_Register:
8096 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008097 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008098 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008099}
8100
Guy Benyei11169dd2012-12-18 14:30:41 +00008101CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8102 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008103 if (const Decl *D = getCursorDecl(cursor)) {
8104 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008105 if (!DC)
8106 return clang_getNullCursor();
8107
8108 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8109 getCursorTU(cursor));
8110 }
8111 }
8112
8113 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008114 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008115 return MakeCXCursor(D, getCursorTU(cursor));
8116 }
8117
8118 return clang_getNullCursor();
8119}
8120
8121CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8122 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008123 if (const Decl *D = getCursorDecl(cursor)) {
8124 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008125 if (!DC)
8126 return clang_getNullCursor();
8127
8128 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8129 getCursorTU(cursor));
8130 }
8131 }
8132
8133 // FIXME: Note that we can't easily compute the lexical context of a
8134 // statement or expression, so we return nothing.
8135 return clang_getNullCursor();
8136}
8137
8138CXFile clang_getIncludedFile(CXCursor cursor) {
8139 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008140 return nullptr;
8141
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008142 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008143 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008144}
8145
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008146unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8147 if (C.kind != CXCursor_ObjCPropertyDecl)
8148 return CXObjCPropertyAttr_noattr;
8149
8150 unsigned Result = CXObjCPropertyAttr_noattr;
8151 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8152 ObjCPropertyDecl::PropertyAttributeKind Attr =
8153 PD->getPropertyAttributesAsWritten();
8154
8155#define SET_CXOBJCPROP_ATTR(A) \
8156 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8157 Result |= CXObjCPropertyAttr_##A
8158 SET_CXOBJCPROP_ATTR(readonly);
8159 SET_CXOBJCPROP_ATTR(getter);
8160 SET_CXOBJCPROP_ATTR(assign);
8161 SET_CXOBJCPROP_ATTR(readwrite);
8162 SET_CXOBJCPROP_ATTR(retain);
8163 SET_CXOBJCPROP_ATTR(copy);
8164 SET_CXOBJCPROP_ATTR(nonatomic);
8165 SET_CXOBJCPROP_ATTR(setter);
8166 SET_CXOBJCPROP_ATTR(atomic);
8167 SET_CXOBJCPROP_ATTR(weak);
8168 SET_CXOBJCPROP_ATTR(strong);
8169 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008170 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008171#undef SET_CXOBJCPROP_ATTR
8172
8173 return Result;
8174}
8175
Michael Wu6e88f532018-08-03 05:38:29 +00008176CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8177 if (C.kind != CXCursor_ObjCPropertyDecl)
8178 return cxstring::createNull();
8179
8180 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8181 Selector sel = PD->getGetterName();
8182 if (sel.isNull())
8183 return cxstring::createNull();
8184
8185 return cxstring::createDup(sel.getAsString());
8186}
8187
8188CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8189 if (C.kind != CXCursor_ObjCPropertyDecl)
8190 return cxstring::createNull();
8191
8192 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8193 Selector sel = PD->getSetterName();
8194 if (sel.isNull())
8195 return cxstring::createNull();
8196
8197 return cxstring::createDup(sel.getAsString());
8198}
8199
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008200unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8201 if (!clang_isDeclaration(C.kind))
8202 return CXObjCDeclQualifier_None;
8203
8204 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8205 const Decl *D = getCursorDecl(C);
8206 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8207 QT = MD->getObjCDeclQualifier();
8208 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8209 QT = PD->getObjCDeclQualifier();
8210 if (QT == Decl::OBJC_TQ_None)
8211 return CXObjCDeclQualifier_None;
8212
8213 unsigned Result = CXObjCDeclQualifier_None;
8214 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8215 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8216 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8217 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8218 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8219 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8220
8221 return Result;
8222}
8223
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008224unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8225 if (!clang_isDeclaration(C.kind))
8226 return 0;
8227
8228 const Decl *D = getCursorDecl(C);
8229 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8230 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8231 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8232 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8233
8234 return 0;
8235}
8236
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008237unsigned clang_Cursor_isVariadic(CXCursor C) {
8238 if (!clang_isDeclaration(C.kind))
8239 return 0;
8240
8241 const Decl *D = getCursorDecl(C);
8242 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8243 return FD->isVariadic();
8244 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8245 return MD->isVariadic();
8246
8247 return 0;
8248}
8249
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008250unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8251 CXString *language, CXString *definedIn,
8252 unsigned *isGenerated) {
8253 if (!clang_isDeclaration(C.kind))
8254 return 0;
8255
8256 const Decl *D = getCursorDecl(C);
8257
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008258 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008259 if (language)
8260 *language = cxstring::createDup(attr->getLanguage());
8261 if (definedIn)
8262 *definedIn = cxstring::createDup(attr->getDefinedIn());
8263 if (isGenerated)
8264 *isGenerated = attr->getGeneratedDeclaration();
8265 return 1;
8266 }
8267 return 0;
8268}
8269
Guy Benyei11169dd2012-12-18 14:30:41 +00008270CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8271 if (!clang_isDeclaration(C.kind))
8272 return clang_getNullRange();
8273
8274 const Decl *D = getCursorDecl(C);
8275 ASTContext &Context = getCursorContext(C);
8276 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8277 if (!RC)
8278 return clang_getNullRange();
8279
8280 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8281}
8282
8283CXString clang_Cursor_getRawCommentText(CXCursor C) {
8284 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008285 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008286
8287 const Decl *D = getCursorDecl(C);
8288 ASTContext &Context = getCursorContext(C);
8289 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8290 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8291 StringRef();
8292
8293 // Don't duplicate the string because RawText points directly into source
8294 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008295 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008296}
8297
8298CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8299 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008300 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008301
8302 const Decl *D = getCursorDecl(C);
8303 const ASTContext &Context = getCursorContext(C);
8304 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8305
8306 if (RC) {
8307 StringRef BriefText = RC->getBriefText(Context);
8308
8309 // Don't duplicate the string because RawComment ensures that this memory
8310 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008311 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008312 }
8313
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008314 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008315}
8316
Guy Benyei11169dd2012-12-18 14:30:41 +00008317CXModule clang_Cursor_getModule(CXCursor C) {
8318 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008319 if (const ImportDecl *ImportD =
8320 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008321 return ImportD->getImportedModule();
8322 }
8323
Craig Topper69186e72014-06-08 08:38:04 +00008324 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008325}
8326
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008327CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8328 if (isNotUsableTU(TU)) {
8329 LOG_BAD_TU(TU);
8330 return nullptr;
8331 }
8332 if (!File)
8333 return nullptr;
8334 FileEntry *FE = static_cast<FileEntry *>(File);
8335
8336 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8337 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8338 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8339
Richard Smithfeb54b62014-10-23 02:01:19 +00008340 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008341}
8342
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008343CXFile clang_Module_getASTFile(CXModule CXMod) {
8344 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008345 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008346 Module *Mod = static_cast<Module*>(CXMod);
8347 return const_cast<FileEntry *>(Mod->getASTFile());
8348}
8349
Guy Benyei11169dd2012-12-18 14:30:41 +00008350CXModule clang_Module_getParent(CXModule CXMod) {
8351 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008352 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008353 Module *Mod = static_cast<Module*>(CXMod);
8354 return Mod->Parent;
8355}
8356
8357CXString clang_Module_getName(CXModule CXMod) {
8358 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008359 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008360 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008361 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008362}
8363
8364CXString clang_Module_getFullName(CXModule CXMod) {
8365 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008366 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008367 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008368 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008369}
8370
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008371int clang_Module_isSystem(CXModule CXMod) {
8372 if (!CXMod)
8373 return 0;
8374 Module *Mod = static_cast<Module*>(CXMod);
8375 return Mod->IsSystem;
8376}
8377
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008378unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8379 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008380 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008381 LOG_BAD_TU(TU);
8382 return 0;
8383 }
8384 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008385 return 0;
8386 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008387 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8388 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8389 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008390}
8391
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008392CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8393 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008394 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008395 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008396 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008397 }
8398 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008399 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008400 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008401 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008402
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008403 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8404 if (Index < TopHeaders.size())
8405 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008406
Craig Topper69186e72014-06-08 08:38:04 +00008407 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008408}
8409
Guy Benyei11169dd2012-12-18 14:30:41 +00008410//===----------------------------------------------------------------------===//
8411// C++ AST instrospection.
8412//===----------------------------------------------------------------------===//
8413
Jonathan Coe29565352016-04-27 12:48:25 +00008414unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8415 if (!clang_isDeclaration(C.kind))
8416 return 0;
8417
8418 const Decl *D = cxcursor::getCursorDecl(C);
8419 const CXXConstructorDecl *Constructor =
8420 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8421 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8422}
8423
8424unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8425 if (!clang_isDeclaration(C.kind))
8426 return 0;
8427
8428 const Decl *D = cxcursor::getCursorDecl(C);
8429 const CXXConstructorDecl *Constructor =
8430 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8431 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8432}
8433
8434unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8435 if (!clang_isDeclaration(C.kind))
8436 return 0;
8437
8438 const Decl *D = cxcursor::getCursorDecl(C);
8439 const CXXConstructorDecl *Constructor =
8440 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8441 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8442}
8443
8444unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8445 if (!clang_isDeclaration(C.kind))
8446 return 0;
8447
8448 const Decl *D = cxcursor::getCursorDecl(C);
8449 const CXXConstructorDecl *Constructor =
8450 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8451 // Passing 'false' excludes constructors marked 'explicit'.
8452 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8453}
8454
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008455unsigned clang_CXXField_isMutable(CXCursor C) {
8456 if (!clang_isDeclaration(C.kind))
8457 return 0;
8458
8459 if (const auto D = cxcursor::getCursorDecl(C))
8460 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8461 return FD->isMutable() ? 1 : 0;
8462 return 0;
8463}
8464
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008465unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8466 if (!clang_isDeclaration(C.kind))
8467 return 0;
8468
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008469 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008470 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008471 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008472 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8473}
8474
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008475unsigned clang_CXXMethod_isConst(CXCursor C) {
8476 if (!clang_isDeclaration(C.kind))
8477 return 0;
8478
8479 const Decl *D = cxcursor::getCursorDecl(C);
8480 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008481 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008482 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008483}
8484
Jonathan Coe29565352016-04-27 12:48:25 +00008485unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8486 if (!clang_isDeclaration(C.kind))
8487 return 0;
8488
8489 const Decl *D = cxcursor::getCursorDecl(C);
8490 const CXXMethodDecl *Method =
8491 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8492 return (Method && Method->isDefaulted()) ? 1 : 0;
8493}
8494
Guy Benyei11169dd2012-12-18 14:30:41 +00008495unsigned clang_CXXMethod_isStatic(CXCursor C) {
8496 if (!clang_isDeclaration(C.kind))
8497 return 0;
8498
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008499 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008500 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008501 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008502 return (Method && Method->isStatic()) ? 1 : 0;
8503}
8504
8505unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8506 if (!clang_isDeclaration(C.kind))
8507 return 0;
8508
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008509 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008510 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008511 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008512 return (Method && Method->isVirtual()) ? 1 : 0;
8513}
Guy Benyei11169dd2012-12-18 14:30:41 +00008514
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008515unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8516 if (!clang_isDeclaration(C.kind))
8517 return 0;
8518
8519 const auto *D = cxcursor::getCursorDecl(C);
8520 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8521 if (RD)
8522 RD = RD->getDefinition();
8523 return (RD && RD->isAbstract()) ? 1 : 0;
8524}
8525
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008526unsigned clang_EnumDecl_isScoped(CXCursor C) {
8527 if (!clang_isDeclaration(C.kind))
8528 return 0;
8529
8530 const Decl *D = cxcursor::getCursorDecl(C);
8531 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8532 return (Enum && Enum->isScoped()) ? 1 : 0;
8533}
8534
Guy Benyei11169dd2012-12-18 14:30:41 +00008535//===----------------------------------------------------------------------===//
8536// Attribute introspection.
8537//===----------------------------------------------------------------------===//
8538
Guy Benyei11169dd2012-12-18 14:30:41 +00008539CXType clang_getIBOutletCollectionType(CXCursor C) {
8540 if (C.kind != CXCursor_IBOutletCollectionAttr)
8541 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8542
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008543 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008544 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8545
8546 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8547}
Guy Benyei11169dd2012-12-18 14:30:41 +00008548
8549//===----------------------------------------------------------------------===//
8550// Inspecting memory usage.
8551//===----------------------------------------------------------------------===//
8552
8553typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8554
8555static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8556 enum CXTUResourceUsageKind k,
8557 unsigned long amount) {
8558 CXTUResourceUsageEntry entry = { k, amount };
8559 entries.push_back(entry);
8560}
8561
Guy Benyei11169dd2012-12-18 14:30:41 +00008562const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8563 const char *str = "";
8564 switch (kind) {
8565 case CXTUResourceUsage_AST:
8566 str = "ASTContext: expressions, declarations, and types";
8567 break;
8568 case CXTUResourceUsage_Identifiers:
8569 str = "ASTContext: identifiers";
8570 break;
8571 case CXTUResourceUsage_Selectors:
8572 str = "ASTContext: selectors";
8573 break;
8574 case CXTUResourceUsage_GlobalCompletionResults:
8575 str = "Code completion: cached global results";
8576 break;
8577 case CXTUResourceUsage_SourceManagerContentCache:
8578 str = "SourceManager: content cache allocator";
8579 break;
8580 case CXTUResourceUsage_AST_SideTables:
8581 str = "ASTContext: side tables";
8582 break;
8583 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8584 str = "SourceManager: malloc'ed memory buffers";
8585 break;
8586 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8587 str = "SourceManager: mmap'ed memory buffers";
8588 break;
8589 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8590 str = "ExternalASTSource: malloc'ed memory buffers";
8591 break;
8592 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8593 str = "ExternalASTSource: mmap'ed memory buffers";
8594 break;
8595 case CXTUResourceUsage_Preprocessor:
8596 str = "Preprocessor: malloc'ed memory";
8597 break;
8598 case CXTUResourceUsage_PreprocessingRecord:
8599 str = "Preprocessor: PreprocessingRecord";
8600 break;
8601 case CXTUResourceUsage_SourceManager_DataStructures:
8602 str = "SourceManager: data structures and tables";
8603 break;
8604 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8605 str = "Preprocessor: header search tables";
8606 break;
8607 }
8608 return str;
8609}
8610
8611CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008612 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008613 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008614 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008615 return usage;
8616 }
8617
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008618 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008619 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008620 ASTContext &astContext = astUnit->getASTContext();
8621
8622 // How much memory is used by AST nodes and types?
8623 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8624 (unsigned long) astContext.getASTAllocatedMemory());
8625
8626 // How much memory is used by identifiers?
8627 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8628 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8629
8630 // How much memory is used for selectors?
8631 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8632 (unsigned long) astContext.Selectors.getTotalMemory());
8633
8634 // How much memory is used by ASTContext's side tables?
8635 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8636 (unsigned long) astContext.getSideTableAllocatedMemory());
8637
8638 // How much memory is used for caching global code completion results?
8639 unsigned long completionBytes = 0;
8640 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008641 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008642 completionBytes = completionAllocator->getTotalMemory();
8643 }
8644 createCXTUResourceUsageEntry(*entries,
8645 CXTUResourceUsage_GlobalCompletionResults,
8646 completionBytes);
8647
8648 // How much memory is being used by SourceManager's content cache?
8649 createCXTUResourceUsageEntry(*entries,
8650 CXTUResourceUsage_SourceManagerContentCache,
8651 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8652
8653 // How much memory is being used by the MemoryBuffer's in SourceManager?
8654 const SourceManager::MemoryBufferSizes &srcBufs =
8655 astUnit->getSourceManager().getMemoryBufferSizes();
8656
8657 createCXTUResourceUsageEntry(*entries,
8658 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8659 (unsigned long) srcBufs.malloc_bytes);
8660 createCXTUResourceUsageEntry(*entries,
8661 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8662 (unsigned long) srcBufs.mmap_bytes);
8663 createCXTUResourceUsageEntry(*entries,
8664 CXTUResourceUsage_SourceManager_DataStructures,
8665 (unsigned long) astContext.getSourceManager()
8666 .getDataStructureSizes());
8667
8668 // How much memory is being used by the ExternalASTSource?
8669 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8670 const ExternalASTSource::MemoryBufferSizes &sizes =
8671 esrc->getMemoryBufferSizes();
8672
8673 createCXTUResourceUsageEntry(*entries,
8674 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8675 (unsigned long) sizes.malloc_bytes);
8676 createCXTUResourceUsageEntry(*entries,
8677 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8678 (unsigned long) sizes.mmap_bytes);
8679 }
8680
8681 // How much memory is being used by the Preprocessor?
8682 Preprocessor &pp = astUnit->getPreprocessor();
8683 createCXTUResourceUsageEntry(*entries,
8684 CXTUResourceUsage_Preprocessor,
8685 pp.getTotalMemory());
8686
8687 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8688 createCXTUResourceUsageEntry(*entries,
8689 CXTUResourceUsage_PreprocessingRecord,
8690 pRec->getTotalMemory());
8691 }
8692
8693 createCXTUResourceUsageEntry(*entries,
8694 CXTUResourceUsage_Preprocessor_HeaderSearch,
8695 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008696
Guy Benyei11169dd2012-12-18 14:30:41 +00008697 CXTUResourceUsage usage = { (void*) entries.get(),
8698 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008699 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008700 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008701 return usage;
8702}
8703
8704void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8705 if (usage.data)
8706 delete (MemUsageEntries*) usage.data;
8707}
8708
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008709CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8710 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008711 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008712 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008713
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008714 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008715 LOG_BAD_TU(TU);
8716 return skipped;
8717 }
8718
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008719 if (!file)
8720 return skipped;
8721
8722 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8723 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8724 if (!ppRec)
8725 return skipped;
8726
8727 ASTContext &Ctx = astUnit->getASTContext();
8728 SourceManager &sm = Ctx.getSourceManager();
8729 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8730 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008731 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008732
8733 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8734 std::vector<SourceRange> wantedRanges;
8735 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8736 i != ei; ++i) {
8737 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8738 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008739 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8740 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008741 }
8742
8743 skipped->count = wantedRanges.size();
8744 skipped->ranges = new CXSourceRange[skipped->count];
8745 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8746 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8747
8748 return skipped;
8749}
8750
Cameron Desrochersd8091282016-08-18 15:43:55 +00008751CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8752 CXSourceRangeList *skipped = new CXSourceRangeList;
8753 skipped->count = 0;
8754 skipped->ranges = nullptr;
8755
8756 if (isNotUsableTU(TU)) {
8757 LOG_BAD_TU(TU);
8758 return skipped;
8759 }
8760
8761 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8762 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8763 if (!ppRec)
8764 return skipped;
8765
8766 ASTContext &Ctx = astUnit->getASTContext();
8767
8768 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8769
8770 skipped->count = SkippedRanges.size();
8771 skipped->ranges = new CXSourceRange[skipped->count];
8772 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8773 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8774
8775 return skipped;
8776}
8777
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008778void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8779 if (ranges) {
8780 delete[] ranges->ranges;
8781 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008782 }
8783}
8784
Guy Benyei11169dd2012-12-18 14:30:41 +00008785void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8786 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8787 for (unsigned I = 0; I != Usage.numEntries; ++I)
8788 fprintf(stderr, " %s: %lu\n",
8789 clang_getTUResourceUsageName(Usage.entries[I].kind),
8790 Usage.entries[I].amount);
8791
8792 clang_disposeCXTUResourceUsage(Usage);
8793}
8794
8795//===----------------------------------------------------------------------===//
8796// Misc. utility functions.
8797//===----------------------------------------------------------------------===//
8798
Richard Smith0a7b2972018-07-03 21:34:13 +00008799/// Default to using our desired 8 MB stack size on "safety" threads.
8800static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008801
8802namespace clang {
8803
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008804bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008805 unsigned Size) {
8806 if (!Size)
8807 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008808 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008809 return CRC.RunSafelyOnThread(Fn, Size);
8810 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008811}
8812
8813unsigned GetSafetyThreadStackSize() {
8814 return SafetyStackThreadSize;
8815}
8816
8817void SetSafetyThreadStackSize(unsigned Value) {
8818 SafetyStackThreadSize = Value;
8819}
8820
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008821}
Guy Benyei11169dd2012-12-18 14:30:41 +00008822
8823void clang::setThreadBackgroundPriority() {
8824 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8825 return;
8826
Nico Weber18cfd9f2019-04-21 19:18:41 +00008827#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008828 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008829#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008830}
8831
8832void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8833 if (!Unit)
8834 return;
8835
8836 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8837 DEnd = Unit->stored_diag_end();
8838 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008839 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008840 CXString Msg = clang_formatDiagnostic(&Diag,
8841 clang_defaultDiagnosticDisplayOptions());
8842 fprintf(stderr, "%s\n", clang_getCString(Msg));
8843 clang_disposeString(Msg);
8844 }
Nico Weber1865df42018-04-27 19:11:14 +00008845#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008846 // On Windows, force a flush, since there may be multiple copies of
8847 // stderr and stdout in the file system, all with different buffers
8848 // but writing to the same device.
8849 fflush(stderr);
8850#endif
8851}
8852
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008853MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8854 SourceLocation MacroDefLoc,
8855 CXTranslationUnit TU){
8856 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008857 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008858 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008859 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008860
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008861 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008862 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008863 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008864 if (MD) {
8865 for (MacroDirective::DefInfo
8866 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8867 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8868 return Def.getMacroInfo();
8869 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008870 }
8871
Craig Topper69186e72014-06-08 08:38:04 +00008872 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008873}
8874
Richard Smith66a81862015-05-04 02:25:31 +00008875const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008876 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008877 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008878 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008879 const IdentifierInfo *II = MacroDef->getName();
8880 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008881 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008882
8883 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8884}
8885
Richard Smith66a81862015-05-04 02:25:31 +00008886MacroDefinitionRecord *
8887cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8888 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008889 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008890 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008891 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008892 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008893
8894 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008895 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008896 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8897 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008898 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008899
8900 // Check that the token is inside the definition and not its argument list.
8901 SourceManager &SM = Unit->getSourceManager();
8902 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008903 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008904 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008905 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008906
8907 Preprocessor &PP = Unit->getPreprocessor();
8908 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8909 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008910 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008911
Alp Toker2d57cea2014-05-17 04:53:25 +00008912 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008913 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008914 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008915
8916 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008917 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008918 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008919
Richard Smith20e883e2015-04-29 23:20:19 +00008920 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008921 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008922 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008923
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008924 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008925}
8926
Richard Smith66a81862015-05-04 02:25:31 +00008927MacroDefinitionRecord *
8928cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8929 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008930 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008931 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008932
8933 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008934 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008935 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008936 Preprocessor &PP = Unit->getPreprocessor();
8937 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008938 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008939 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8940 Token Tok;
8941 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008942 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008943
8944 return checkForMacroInMacroDefinition(MI, Tok, TU);
8945}
8946
Guy Benyei11169dd2012-12-18 14:30:41 +00008947CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008948 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008949}
8950
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008951Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8952 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008953 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008954 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008955 if (Unit->isMainFileAST())
8956 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008957 return *this;
8958 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008959 } else {
8960 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008961 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008962 return *this;
8963}
8964
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008965Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8966 *this << FE->getName();
8967 return *this;
8968}
8969
8970Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8971 CXString cursorName = clang_getCursorDisplayName(cursor);
8972 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8973 clang_disposeString(cursorName);
8974 return *this;
8975}
8976
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008977Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8978 CXFile File;
8979 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008980 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008981 CXString FileName = clang_getFileName(File);
8982 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8983 clang_disposeString(FileName);
8984 return *this;
8985}
8986
8987Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8988 CXSourceLocation BLoc = clang_getRangeStart(range);
8989 CXSourceLocation ELoc = clang_getRangeEnd(range);
8990
8991 CXFile BFile;
8992 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008993 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008994
8995 CXFile EFile;
8996 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008997 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008998
8999 CXString BFileName = clang_getFileName(BFile);
9000 if (BFile == EFile) {
9001 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
9002 BLine, BColumn, ELine, EColumn);
9003 } else {
9004 CXString EFileName = clang_getFileName(EFile);
9005 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
9006 BLine, BColumn)
9007 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
9008 ELine, EColumn);
9009 clang_disposeString(EFileName);
9010 }
9011 clang_disposeString(BFileName);
9012 return *this;
9013}
9014
9015Logger &cxindex::Logger::operator<<(CXString Str) {
9016 *this << clang_getCString(Str);
9017 return *this;
9018}
9019
9020Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
9021 LogOS << Fmt;
9022 return *this;
9023}
9024
Benjamin Kramer762bc332019-08-07 14:44:40 +00009025static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00009026
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009027cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00009028 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009029
9030 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
9031
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009032 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009033 OS << "[libclang:" << Name << ':';
9034
Alp Toker1a86ad22014-07-06 06:24:00 +00009035#ifdef USE_DARWIN_THREADS
9036 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009037 mach_port_t tid = pthread_mach_thread_np(pthread_self());
9038 OS << tid << ':';
9039#endif
9040
9041 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
9042 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00009043 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009044
9045 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00009046 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009047 OS << "--------------------------------------------------\n";
9048 }
9049}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00009050
9051#ifdef CLANG_TOOL_EXTRA_BUILD
9052// This anchor is used to force the linker to link the clang-tidy plugin.
9053extern volatile int ClangTidyPluginAnchorSource;
9054static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9055 ClangTidyPluginAnchorSource;
9056
9057// This anchor is used to force the linker to link the clang-include-fixer
9058// plugin.
9059extern volatile int ClangIncludeFixerPluginAnchorSource;
9060static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9061 ClangIncludeFixerPluginAnchorSource;
9062#endif