blob: 9a09fca5e269e26d3ef1042c498b3b8718307021 [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"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/AST/StmtVisitor.h"
27#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000028#include "clang/Basic/DiagnosticCategories.h"
29#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000030#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000031#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000032#include "clang/Basic/Version.h"
33#include "clang/Frontend/ASTUnit.h"
34#include "clang/Frontend/CompilerInstance.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000035#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000043#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000046#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000047#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/MemoryBuffer.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/Support/Program.h"
50#include "llvm/Support/SaveAndRestore.h"
51#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000052#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000053#include "llvm/Support/Threading.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/raw_ostream.h"
Benjamin Kramer762bc332019-08-07 14:44:40 +000056#include <mutex>
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000057
Alp Toker1a86ad22014-07-06 06:24:00 +000058#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59#define USE_DARWIN_THREADS
60#endif
61
62#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000063#include <pthread.h>
64#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000065
66using namespace clang;
67using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000068using namespace clang::cxtu;
69using namespace clang::cxindex;
70
David Blaikieea4395e2017-01-06 19:49:01 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
72 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000073 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000074 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000075 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000076 CXTranslationUnit D = new CXTranslationUnitImpl();
77 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000078 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000079 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000080 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000081 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000082 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000083 D->ParsingOptions = 0;
84 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000085 return D;
86}
87
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000088bool cxtu::isASTReadError(ASTUnit *AU) {
89 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
90 DEnd = AU->stored_diag_end();
91 D != DEnd; ++D) {
92 if (D->getLevel() >= DiagnosticsEngine::Error &&
93 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
94 diag::DiagCat_AST_Deserialization_Issue)
95 return true;
96 }
97 return false;
98}
99
Guy Benyei11169dd2012-12-18 14:30:41 +0000100cxtu::CXTUOwner::~CXTUOwner() {
101 if (TU)
102 clang_disposeTranslationUnit(TU);
103}
104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000105/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000106/// the translation unit.
107static RangeComparisonResult RangeCompare(SourceManager &SM,
108 SourceRange R1,
109 SourceRange R2) {
110 assert(R1.isValid() && "First range is invalid?");
111 assert(R2.isValid() && "Second range is invalid?");
112 if (R1.getEnd() != R2.getBegin() &&
113 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
114 return RangeBefore;
115 if (R2.getEnd() != R1.getBegin() &&
116 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
117 return RangeAfter;
118 return RangeOverlap;
119}
120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000121/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000122/// a given source range.
123static RangeComparisonResult LocationCompare(SourceManager &SM,
124 SourceLocation L, SourceRange R) {
125 assert(R.isValid() && "First range is invalid?");
126 assert(L.isValid() && "Second range is invalid?");
127 if (L == R.getBegin() || L == R.getEnd())
128 return RangeOverlap;
129 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
130 return RangeBefore;
131 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
132 return RangeAfter;
133 return RangeOverlap;
134}
135
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000136/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000137///
138/// Clang internally represents ranges where the end location points to the
139/// start of the token at the end. However, for external clients it is more
140/// useful to have a CXSourceRange be a proper half-open interval. This routine
141/// does the appropriate translation.
142CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
143 const LangOptions &LangOpts,
144 const CharSourceRange &R) {
145 // We want the last character in this location, so we will adjust the
146 // location accordingly.
147 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000148 bool IsTokenRange = R.isTokenRange();
149 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
150 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
151 EndLoc = Expansion.getEnd();
152 IsTokenRange = Expansion.isTokenRange();
153 }
154 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000155 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
156 SM, LangOpts);
157 EndLoc = EndLoc.getLocWithOffset(Length);
158 }
159
Bill Wendlingeade3622013-01-23 08:25:41 +0000160 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000161 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000162 R.getBegin().getRawEncoding(),
163 EndLoc.getRawEncoding()
164 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000165 return Result;
166}
167
168//===----------------------------------------------------------------------===//
169// Cursor visitor.
170//===----------------------------------------------------------------------===//
171
172static SourceRange getRawCursorExtent(CXCursor C);
173static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
174
Guy Benyei11169dd2012-12-18 14:30:41 +0000175RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
176 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
177}
178
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000179/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000180/// its children.
181///
182/// \param Cursor the cursor to visit.
183///
184/// \param CheckedRegionOfInterest if true, then the caller already checked
185/// that this cursor is within the region of interest.
186///
187/// \returns true if the visitation should be aborted, false if it
188/// should continue.
189bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
190 if (clang_isInvalid(Cursor.kind))
191 return false;
192
193 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000194 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000195 if (!D) {
196 assert(0 && "Invalid declaration cursor");
197 return true; // abort.
198 }
199
200 // Ignore implicit declarations, unless it's an objc method because
201 // currently we should report implicit methods for properties when indexing.
202 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
203 return false;
204 }
205
206 // If we have a range of interest, and this cursor doesn't intersect with it,
207 // we're done.
208 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
209 SourceRange Range = getRawCursorExtent(Cursor);
210 if (Range.isInvalid() || CompareRegionOfInterest(Range))
211 return false;
212 }
213
214 switch (Visitor(Cursor, Parent, ClientData)) {
215 case CXChildVisit_Break:
216 return true;
217
218 case CXChildVisit_Continue:
219 return false;
220
221 case CXChildVisit_Recurse: {
222 bool ret = VisitChildren(Cursor);
223 if (PostChildrenVisitor)
224 if (PostChildrenVisitor(Cursor, ClientData))
225 return true;
226 return ret;
227 }
228 }
229
230 llvm_unreachable("Invalid CXChildVisitResult!");
231}
232
233static bool visitPreprocessedEntitiesInRange(SourceRange R,
234 PreprocessingRecord &PPRec,
235 CursorVisitor &Visitor) {
236 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
237 FileID FID;
238
239 if (!Visitor.shouldVisitIncludedEntities()) {
240 // If the begin/end of the range lie in the same FileID, do the optimization
241 // where we skip preprocessed entities that do not come from the same FileID.
242 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
243 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
244 FID = FileID();
245 }
246
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000247 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
248 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 PPRec, FID);
250}
251
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000252bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000253 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000254 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000255
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000256 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000257 SourceManager &SM = Unit->getSourceManager();
258
259 std::pair<FileID, unsigned>
260 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
261 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
262
263 if (End.first != Begin.first) {
264 // If the end does not reside in the same file, try to recover by
265 // picking the end of the file of begin location.
266 End.first = Begin.first;
267 End.second = SM.getFileIDSize(Begin.first);
268 }
269
270 assert(Begin.first == End.first);
271 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000272 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000273
274 FileID File = Begin.first;
275 unsigned Offset = Begin.second;
276 unsigned Length = End.second - Begin.second;
277
278 if (!VisitDeclsOnly && !VisitPreprocessorLast)
279 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000281
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000282 if (visitDeclsFromFileRegion(File, Offset, Length))
283 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
285 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000286 return visitPreprocessedEntitiesInRegion();
287
288 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000289}
290
291static bool isInLexicalContext(Decl *D, DeclContext *DC) {
292 if (!DC)
293 return false;
294
295 for (DeclContext *DeclDC = D->getLexicalDeclContext();
296 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
297 if (DeclDC == DC)
298 return true;
299 }
300 return false;
301}
302
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000303bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000304 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000305 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 SourceManager &SM = Unit->getSourceManager();
307 SourceRange Range = RegionOfInterest;
308
309 SmallVector<Decl *, 16> Decls;
310 Unit->findFileRegionDecls(File, Offset, Length, Decls);
311
312 // If we didn't find any file level decls for the file, try looking at the
313 // file that it was included from.
314 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
315 bool Invalid = false;
316 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
317 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000318 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000319
320 SourceLocation Outer;
321 if (SLEntry.isFile())
322 Outer = SLEntry.getFile().getIncludeLoc();
323 else
324 Outer = SLEntry.getExpansion().getExpansionLocStart();
325 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000326 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000327
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000328 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000329 Length = 0;
330 Unit->findFileRegionDecls(File, Offset, Length, Decls);
331 }
332
333 assert(!Decls.empty());
334
335 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000336 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000337 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
338 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000339 Decl *D = *DIt;
340 if (D->getSourceRange().isInvalid())
341 continue;
342
343 if (isInLexicalContext(D, CurDC))
344 continue;
345
346 CurDC = dyn_cast<DeclContext>(D);
347
348 if (TagDecl *TD = dyn_cast<TagDecl>(D))
349 if (!TD->isFreeStanding())
350 continue;
351
352 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
353 if (CompRes == RangeBefore)
354 continue;
355 if (CompRes == RangeAfter)
356 break;
357
358 assert(CompRes == RangeOverlap);
359 VisitedAtLeastOnce = true;
360
361 if (isa<ObjCContainerDecl>(D)) {
362 FileDI_current = &DIt;
363 FileDE_current = DE;
364 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000365 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 }
367
368 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000369 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000370 }
371
372 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000373 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000374
375 // No Decls overlapped with the range. Move up the lexical context until there
376 // is a context that contains the range or we reach the translation unit
377 // level.
378 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
379 : (*(DIt-1))->getLexicalDeclContext();
380
381 while (DC && !DC->isTranslationUnit()) {
382 Decl *D = cast<Decl>(DC);
383 SourceRange CurDeclRange = D->getSourceRange();
384 if (CurDeclRange.isInvalid())
385 break;
386
387 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000388 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
389 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000390 }
391
392 DC = D->getLexicalDeclContext();
393 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000394
395 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000396}
397
398bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
399 if (!AU->getPreprocessor().getPreprocessingRecord())
400 return false;
401
402 PreprocessingRecord &PPRec
403 = *AU->getPreprocessor().getPreprocessingRecord();
404 SourceManager &SM = AU->getSourceManager();
405
406 if (RegionOfInterest.isValid()) {
407 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
408 SourceLocation B = MappedRange.getBegin();
409 SourceLocation E = MappedRange.getEnd();
410
411 if (AU->isInPreambleFileID(B)) {
412 if (SM.isLoadedSourceLocation(E))
413 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
414 PPRec, *this);
415
416 // Beginning of range lies in the preamble but it also extends beyond
417 // it into the main file. Split the range into 2 parts, one covering
418 // the preamble and another covering the main file. This allows subsequent
419 // calls to visitPreprocessedEntitiesInRange to accept a source range that
420 // lies in the same FileID, allowing it to skip preprocessed entities that
421 // do not come from the same FileID.
422 bool breaked =
423 visitPreprocessedEntitiesInRange(
424 SourceRange(B, AU->getEndOfPreambleFileID()),
425 PPRec, *this);
426 if (breaked) return true;
427 return visitPreprocessedEntitiesInRange(
428 SourceRange(AU->getStartOfMainFileID(), E),
429 PPRec, *this);
430 }
431
432 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
433 }
434
435 bool OnlyLocalDecls
436 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
437
438 if (OnlyLocalDecls)
439 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
440 PPRec);
441
442 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
443}
444
445template<typename InputIterator>
446bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
447 InputIterator Last,
448 PreprocessingRecord &PPRec,
449 FileID FID) {
450 for (; First != Last; ++First) {
451 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
452 continue;
453
454 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000455 if (!PPE)
456 continue;
457
Guy Benyei11169dd2012-12-18 14:30:41 +0000458 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
459 if (Visit(MakeMacroExpansionCursor(ME, TU)))
460 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000461
Guy Benyei11169dd2012-12-18 14:30:41 +0000462 continue;
463 }
Richard Smith66a81862015-05-04 02:25:31 +0000464
465 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000466 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
467 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000468
Guy Benyei11169dd2012-12-18 14:30:41 +0000469 continue;
470 }
471
472 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
473 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
474 return true;
475
476 continue;
477 }
478 }
479
480 return false;
481}
482
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000483/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000484///
485/// \returns true if the visitation should be aborted, false if it
486/// should continue.
487bool CursorVisitor::VisitChildren(CXCursor Cursor) {
488 if (clang_isReference(Cursor.kind) &&
489 Cursor.kind != CXCursor_CXXBaseSpecifier) {
490 // By definition, references have no children.
491 return false;
492 }
493
494 // Set the Parent field to Cursor, then back to its old value once we're
495 // done.
496 SetParentRAII SetParent(Parent, StmtParent, Cursor);
497
498 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000499 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000500 if (!D)
501 return false;
502
503 return VisitAttributes(D) || Visit(D);
504 }
505
506 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000507 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000508 return Visit(S);
509
510 return false;
511 }
512
513 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000514 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000515 return Visit(E);
516
517 return false;
518 }
519
520 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000521 CXTranslationUnit TU = getCursorTU(Cursor);
522 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000523
524 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
525 for (unsigned I = 0; I != 2; ++I) {
526 if (VisitOrder[I]) {
527 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
528 RegionOfInterest.isInvalid()) {
529 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
530 TLEnd = CXXUnit->top_level_end();
531 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000532 const Optional<bool> V = handleDeclForVisitation(*TL);
533 if (!V.hasValue())
534 continue;
535 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000536 }
537 } else if (VisitDeclContext(
538 CXXUnit->getASTContext().getTranslationUnitDecl()))
539 return true;
540 continue;
541 }
542
543 // Walk the preprocessing record.
544 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
545 visitPreprocessedEntitiesInRegion();
546 }
547
548 return false;
549 }
550
551 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000552 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000553 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
554 return Visit(BaseTSInfo->getTypeLoc());
555 }
556 }
557 }
558
559 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000560 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000562 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000563 return Visit(cxcursor::MakeCursorObjCClassRef(
564 ObjT->getInterface(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000565 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 }
567
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000568 // If pointing inside a macro definition, check if the token is an identifier
569 // that was ever defined as a macro. In such a case, create a "pseudo" macro
570 // expansion cursor for that token.
571 SourceLocation BeginLoc = RegionOfInterest.getBegin();
572 if (Cursor.kind == CXCursor_MacroDefinition &&
573 BeginLoc == RegionOfInterest.getEnd()) {
574 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000575 const MacroInfo *MI =
576 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000577 if (MacroDefinitionRecord *MacroDef =
578 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000579 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
580 }
581
Guy Benyei11169dd2012-12-18 14:30:41 +0000582 // Nothing to visit at the moment.
583 return false;
584}
585
586bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
587 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
588 if (Visit(TSInfo->getTypeLoc()))
589 return true;
590
591 if (Stmt *Body = B->getBody())
592 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
593
594 return false;
595}
596
Ted Kremenek03325582013-02-21 01:29:01 +0000597Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000598 if (RegionOfInterest.isValid()) {
599 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
600 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000601 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000602
603 switch (CompareRegionOfInterest(Range)) {
604 case RangeBefore:
605 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000606 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000607
608 case RangeAfter:
609 // This declaration comes after the region of interest; we're done.
610 return false;
611
612 case RangeOverlap:
613 // This declaration overlaps the region of interest; visit it.
614 break;
615 }
616 }
617 return true;
618}
619
620bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
621 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
622
623 // FIXME: Eventually remove. This part of a hack to support proper
624 // iteration over all Decls contained lexically within an ObjC container.
625 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
626 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
627
628 for ( ; I != E; ++I) {
629 Decl *D = *I;
630 if (D->getLexicalDeclContext() != DC)
631 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -0800632 // Filter out synthesized property accessor redeclarations.
633 if (isa<ObjCImplDecl>(DC))
634 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
635 if (OMD->isSynthesizedAccessorStub())
636 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000637 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 if (!V.hasValue())
639 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000640 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 }
642 return false;
643}
644
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000645Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
646 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
647
648 // Ignore synthesized ivars here, otherwise if we have something like:
649 // @synthesize prop = _prop;
650 // and '_prop' is not declared, we will encounter a '_prop' ivar before
651 // encountering the 'prop' synthesize declaration and we will think that
652 // we passed the region-of-interest.
653 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
654 if (ivarD->getSynthesize())
655 return None;
656 }
657
658 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
659 // declarations is a mismatch with the compiler semantics.
660 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
661 auto *ID = cast<ObjCInterfaceDecl>(D);
662 if (!ID->isThisDeclarationADefinition())
663 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
664
665 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
666 auto *PD = cast<ObjCProtocolDecl>(D);
667 if (!PD->isThisDeclarationADefinition())
668 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
669 }
670
671 const Optional<bool> V = shouldVisitCursor(Cursor);
672 if (!V.hasValue())
673 return None;
674 if (!V.getValue())
675 return false;
676 if (Visit(Cursor, true))
677 return true;
678 return None;
679}
680
Guy Benyei11169dd2012-12-18 14:30:41 +0000681bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
682 llvm_unreachable("Translation units are visited directly by Visit()");
683}
684
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000685bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
686 if (VisitTemplateParameters(D->getTemplateParameters()))
687 return true;
688
689 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
690}
691
Guy Benyei11169dd2012-12-18 14:30:41 +0000692bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
693 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
694 return Visit(TSInfo->getTypeLoc());
695
696 return false;
697}
698
699bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
700 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
701 return Visit(TSInfo->getTypeLoc());
702
703 return false;
704}
705
706bool CursorVisitor::VisitTagDecl(TagDecl *D) {
707 return VisitDeclContext(D);
708}
709
710bool CursorVisitor::VisitClassTemplateSpecializationDecl(
711 ClassTemplateSpecializationDecl *D) {
712 bool ShouldVisitBody = false;
713 switch (D->getSpecializationKind()) {
714 case TSK_Undeclared:
715 case TSK_ImplicitInstantiation:
716 // Nothing to visit
717 return false;
718
719 case TSK_ExplicitInstantiationDeclaration:
720 case TSK_ExplicitInstantiationDefinition:
721 break;
722
723 case TSK_ExplicitSpecialization:
724 ShouldVisitBody = true;
725 break;
726 }
727
728 // Visit the template arguments used in the specialization.
729 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
730 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000731 if (TemplateSpecializationTypeLoc TSTLoc =
732 TL.getAs<TemplateSpecializationTypeLoc>()) {
733 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
734 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 return true;
736 }
737 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000738
739 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000740}
741
742bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
743 ClassTemplatePartialSpecializationDecl *D) {
744 // FIXME: Visit the "outer" template parameter lists on the TagDecl
745 // before visiting these template parameters.
746 if (VisitTemplateParameters(D->getTemplateParameters()))
747 return true;
748
749 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000750 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
751 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
752 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000753 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
754 return true;
755
756 return VisitCXXRecordDecl(D);
757}
758
759bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Saar Razff1e0fc2020-01-15 02:48:42 +0200760 if (const auto *TC = D->getTypeConstraint())
761 if (Visit(MakeCXCursor(TC->getImmediatelyDeclaredConstraint(), StmtParent,
762 TU, RegionOfInterest)))
763 return true;
764
Guy Benyei11169dd2012-12-18 14:30:41 +0000765 // Visit the default argument.
766 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
767 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
768 if (Visit(DefArg->getTypeLoc()))
769 return true;
770
771 return false;
772}
773
774bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
775 if (Expr *Init = D->getInitExpr())
776 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
777 return false;
778}
779
780bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000781 unsigned NumParamList = DD->getNumTemplateParameterLists();
782 for (unsigned i = 0; i < NumParamList; i++) {
783 TemplateParameterList* Params = DD->getTemplateParameterList(i);
784 if (VisitTemplateParameters(Params))
785 return true;
786 }
787
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
789 if (Visit(TSInfo->getTypeLoc()))
790 return true;
791
792 // Visit the nested-name-specifier, if present.
793 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
794 if (VisitNestedNameSpecifierLoc(QualifierLoc))
795 return true;
796
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000797 return false;
798}
799
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000800static bool HasTrailingReturnType(FunctionDecl *ND) {
801 const QualType Ty = ND->getType();
802 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
803 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
804 return FT->hasTrailingReturn();
805 }
806
807 return false;
808}
809
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000810/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000811static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
812 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000813 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
814}
815
Guy Benyei11169dd2012-12-18 14:30:41 +0000816bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000817 unsigned NumParamList = ND->getNumTemplateParameterLists();
818 for (unsigned i = 0; i < NumParamList; i++) {
819 TemplateParameterList* Params = ND->getTemplateParameterList(i);
820 if (VisitTemplateParameters(Params))
821 return true;
822 }
823
Guy Benyei11169dd2012-12-18 14:30:41 +0000824 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
825 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000826 // written. This requires a bit of work.
827 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
828 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000829 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000830
831 // If we have a function declared directly (without the use of a typedef),
832 // visit just the return type. Otherwise, just visit the function's type
833 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000834 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
835 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000836 (!FTL && Visit(TL)))
837 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000838
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000839 // Visit the nested-name-specifier, if present.
840 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
841 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000842 return true;
843
844 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000845 if (!isa<CXXDestructorDecl>(ND))
846 if (VisitDeclarationNameInfo(ND->getNameInfo()))
847 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000848
849 // FIXME: Visit explicitly-specified template arguments!
850
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000851 // Visit the function parameters, if we have a function type.
852 if (FTL && VisitFunctionTypeLoc(FTL, true))
853 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000854
855 // Visit the function's trailing return type.
856 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
857 return true;
858
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000859 // FIXME: Attributes?
860 }
861
Guy Benyei11169dd2012-12-18 14:30:41 +0000862 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
863 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
864 // Find the initializers that were written in the source.
865 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000866 for (auto *I : Constructor->inits()) {
867 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 continue;
869
Aaron Ballman0ad78302014-03-13 17:34:31 +0000870 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000871 }
872
873 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000874 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
875 &CompareCXXCtorInitializers);
876
Guy Benyei11169dd2012-12-18 14:30:41 +0000877 // Visit the initializers in source order
878 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
879 CXXCtorInitializer *Init = WrittenInits[I];
880 if (Init->isAnyMemberInitializer()) {
881 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
882 Init->getMemberLocation(), TU)))
883 return true;
884 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
885 if (Visit(TInfo->getTypeLoc()))
886 return true;
887 }
888
889 // Visit the initializer value.
890 if (Expr *Initializer = Init->getInit())
891 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
892 return true;
893 }
894 }
895
896 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
897 return true;
898 }
899
900 return false;
901}
902
903bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
904 if (VisitDeclaratorDecl(D))
905 return true;
906
907 if (Expr *BitWidth = D->getBitWidth())
908 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
909
Benjamin Kramer99f97592017-11-15 12:20:41 +0000910 if (Expr *Init = D->getInClassInitializer())
911 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
912
Guy Benyei11169dd2012-12-18 14:30:41 +0000913 return false;
914}
915
916bool CursorVisitor::VisitVarDecl(VarDecl *D) {
917 if (VisitDeclaratorDecl(D))
918 return true;
919
920 if (Expr *Init = D->getInit())
921 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
922
923 return false;
924}
925
926bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
927 if (VisitDeclaratorDecl(D))
928 return true;
929
930 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
931 if (Expr *DefArg = D->getDefaultArgument())
932 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
933
934 return false;
935}
936
937bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
938 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
939 // before visiting these template parameters.
940 if (VisitTemplateParameters(D->getTemplateParameters()))
941 return true;
942
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000943 auto* FD = D->getTemplatedDecl();
944 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000945}
946
947bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
948 // FIXME: Visit the "outer" template parameter lists on the TagDecl
949 // before visiting these template parameters.
950 if (VisitTemplateParameters(D->getTemplateParameters()))
951 return true;
952
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000953 auto* CD = D->getTemplatedDecl();
954 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000955}
956
957bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
958 if (VisitTemplateParameters(D->getTemplateParameters()))
959 return true;
960
961 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
962 VisitTemplateArgumentLoc(D->getDefaultArgument()))
963 return true;
964
965 return false;
966}
967
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000968bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
969 // Visit the bound, if it's explicit.
970 if (D->hasExplicitBound()) {
971 if (auto TInfo = D->getTypeSourceInfo()) {
972 if (Visit(TInfo->getTypeLoc()))
973 return true;
974 }
975 }
976
977 return false;
978}
979
Guy Benyei11169dd2012-12-18 14:30:41 +0000980bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000981 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000982 if (Visit(TSInfo->getTypeLoc()))
983 return true;
984
David Majnemer59f77922016-06-24 04:05:48 +0000985 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000986 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 return true;
988 }
989
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000990 return ND->isThisDeclarationADefinition() &&
991 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000992}
993
994template <typename DeclIt>
995static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
996 SourceManager &SM, SourceLocation EndLoc,
997 SmallVectorImpl<Decl *> &Decls) {
998 DeclIt next = *DI_current;
999 while (++next != DE_current) {
1000 Decl *D_next = *next;
1001 if (!D_next)
1002 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001003 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 if (!L.isValid())
1005 break;
1006 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1007 *DI_current = next;
1008 Decls.push_back(D_next);
1009 continue;
1010 }
1011 break;
1012 }
1013}
1014
Guy Benyei11169dd2012-12-18 14:30:41 +00001015bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1016 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1017 // an @implementation can lexically contain Decls that are not properly
1018 // nested in the AST. When we identify such cases, we need to retrofit
1019 // this nesting here.
1020 if (!DI_current && !FileDI_current)
1021 return VisitDeclContext(D);
1022
1023 // Scan the Decls that immediately come after the container
1024 // in the current DeclContext. If any fall within the
1025 // container's lexical region, stash them into a vector
1026 // for later processing.
1027 SmallVector<Decl *, 24> DeclsInContainer;
1028 SourceLocation EndLoc = D->getSourceRange().getEnd();
1029 SourceManager &SM = AU->getSourceManager();
1030 if (EndLoc.isValid()) {
1031 if (DI_current) {
1032 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1033 DeclsInContainer);
1034 } else {
1035 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1036 DeclsInContainer);
1037 }
1038 }
1039
1040 // The common case.
1041 if (DeclsInContainer.empty())
1042 return VisitDeclContext(D);
1043
1044 // Get all the Decls in the DeclContext, and sort them with the
1045 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001046 for (auto *SubDecl : D->decls()) {
1047 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001048 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001050 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001051 }
1052
1053 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001054 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001055 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001056 SourceLocation L_A = A->getBeginLoc();
1057 SourceLocation L_B = B->getBeginLoc();
1058 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001059 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1060 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001061 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001062
1063 // Now visit the decls.
1064 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1065 E = DeclsInContainer.end(); I != E; ++I) {
1066 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001067 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001068 if (!V.hasValue())
1069 continue;
1070 if (!V.getValue())
1071 return false;
1072 if (Visit(Cursor, true))
1073 return true;
1074 }
1075 return false;
1076}
1077
1078bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1079 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1080 TU)))
1081 return true;
1082
Douglas Gregore9d95f12015-07-07 03:57:35 +00001083 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1084 return true;
1085
Guy Benyei11169dd2012-12-18 14:30:41 +00001086 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1087 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1088 E = ND->protocol_end(); I != E; ++I, ++PL)
1089 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1090 return true;
1091
1092 return VisitObjCContainerDecl(ND);
1093}
1094
1095bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1096 if (!PID->isThisDeclarationADefinition())
1097 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1098
1099 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1100 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1101 E = PID->protocol_end(); I != E; ++I, ++PL)
1102 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1103 return true;
1104
1105 return VisitObjCContainerDecl(PID);
1106}
1107
1108bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1109 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1110 return true;
1111
1112 // FIXME: This implements a workaround with @property declarations also being
1113 // installed in the DeclContext for the @interface. Eventually this code
1114 // should be removed.
1115 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1116 if (!CDecl || !CDecl->IsClassExtension())
1117 return false;
1118
1119 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1120 if (!ID)
1121 return false;
1122
1123 IdentifierInfo *PropertyId = PD->getIdentifier();
1124 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001125 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1126 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001127
1128 if (!prevDecl)
1129 return false;
1130
1131 // Visit synthesized methods since they will be skipped when visiting
1132 // the @interface.
1133 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1134 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1135 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1136 return true;
1137
1138 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1139 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1140 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1141 return true;
1142
1143 return false;
1144}
1145
Douglas Gregore9d95f12015-07-07 03:57:35 +00001146bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1147 if (!typeParamList)
1148 return false;
1149
1150 for (auto *typeParam : *typeParamList) {
1151 // Visit the type parameter.
1152 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1153 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001154 }
1155
1156 return false;
1157}
1158
Guy Benyei11169dd2012-12-18 14:30:41 +00001159bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1160 if (!D->isThisDeclarationADefinition()) {
1161 // Forward declaration is treated like a reference.
1162 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1163 }
1164
Douglas Gregore9d95f12015-07-07 03:57:35 +00001165 // Objective-C type parameters.
1166 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1167 return true;
1168
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 // Issue callbacks for super class.
1170 if (D->getSuperClass() &&
1171 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1172 D->getSuperClassLoc(),
1173 TU)))
1174 return true;
1175
Douglas Gregore9d95f12015-07-07 03:57:35 +00001176 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1177 if (Visit(SuperClassTInfo->getTypeLoc()))
1178 return true;
1179
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1181 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1182 E = D->protocol_end(); I != E; ++I, ++PL)
1183 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1184 return true;
1185
1186 return VisitObjCContainerDecl(D);
1187}
1188
1189bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1190 return VisitObjCContainerDecl(D);
1191}
1192
1193bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1194 // 'ID' could be null when dealing with invalid code.
1195 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1196 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1197 return true;
1198
1199 return VisitObjCImplDecl(D);
1200}
1201
1202bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1203#if 0
1204 // Issue callbacks for super class.
1205 // FIXME: No source location information!
1206 if (D->getSuperClass() &&
1207 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1208 D->getSuperClassLoc(),
1209 TU)))
1210 return true;
1211#endif
1212
1213 return VisitObjCImplDecl(D);
1214}
1215
1216bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1217 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1218 if (PD->isIvarNameSpecified())
1219 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1220
1221 return false;
1222}
1223
1224bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1225 return VisitDeclContext(D);
1226}
1227
1228bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1229 // Visit nested-name-specifier.
1230 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1231 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1232 return true;
1233
1234 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1235 D->getTargetNameLoc(), TU));
1236}
1237
1238bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1239 // Visit nested-name-specifier.
1240 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1241 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1242 return true;
1243 }
1244
1245 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1246 return true;
1247
1248 return VisitDeclarationNameInfo(D->getNameInfo());
1249}
1250
1251bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1252 // Visit nested-name-specifier.
1253 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1254 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1255 return true;
1256
1257 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1258 D->getIdentLocation(), TU));
1259}
1260
1261bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1262 // Visit nested-name-specifier.
1263 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1264 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1265 return true;
1266 }
1267
1268 return VisitDeclarationNameInfo(D->getNameInfo());
1269}
1270
1271bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1272 UnresolvedUsingTypenameDecl *D) {
1273 // Visit nested-name-specifier.
1274 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1275 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1276 return true;
1277
1278 return false;
1279}
1280
Olivier Goffart81978012016-06-09 16:15:55 +00001281bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1282 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1283 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001284 if (StringLiteral *Message = D->getMessage())
1285 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1286 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001287 return false;
1288}
1289
Olivier Goffartd211c642016-11-04 06:29:27 +00001290bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1291 if (NamedDecl *FriendD = D->getFriendDecl()) {
1292 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1293 return true;
1294 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1295 if (Visit(TI->getTypeLoc()))
1296 return true;
1297 }
1298 return false;
1299}
1300
Guy Benyei11169dd2012-12-18 14:30:41 +00001301bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1302 switch (Name.getName().getNameKind()) {
1303 case clang::DeclarationName::Identifier:
1304 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001305 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 case clang::DeclarationName::CXXOperatorName:
1307 case clang::DeclarationName::CXXUsingDirective:
1308 return false;
Richard Smith35845152017-02-07 01:37:30 +00001309
Guy Benyei11169dd2012-12-18 14:30:41 +00001310 case clang::DeclarationName::CXXConstructorName:
1311 case clang::DeclarationName::CXXDestructorName:
1312 case clang::DeclarationName::CXXConversionFunctionName:
1313 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1314 return Visit(TSInfo->getTypeLoc());
1315 return false;
1316
1317 case clang::DeclarationName::ObjCZeroArgSelector:
1318 case clang::DeclarationName::ObjCOneArgSelector:
1319 case clang::DeclarationName::ObjCMultiArgSelector:
1320 // FIXME: Per-identifier location info?
1321 return false;
1322 }
1323
1324 llvm_unreachable("Invalid DeclarationName::Kind!");
1325}
1326
1327bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1328 SourceRange Range) {
1329 // FIXME: This whole routine is a hack to work around the lack of proper
1330 // source information in nested-name-specifiers (PR5791). Since we do have
1331 // a beginning source location, we can visit the first component of the
1332 // nested-name-specifier, if it's a single-token component.
1333 if (!NNS)
1334 return false;
1335
1336 // Get the first component in the nested-name-specifier.
1337 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1338 NNS = Prefix;
1339
1340 switch (NNS->getKind()) {
1341 case NestedNameSpecifier::Namespace:
1342 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1343 TU));
1344
1345 case NestedNameSpecifier::NamespaceAlias:
1346 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1347 Range.getBegin(), TU));
1348
1349 case NestedNameSpecifier::TypeSpec: {
1350 // If the type has a form where we know that the beginning of the source
1351 // range matches up with a reference cursor. Visit the appropriate reference
1352 // cursor.
1353 const Type *T = NNS->getAsType();
1354 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1355 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1356 if (const TagType *Tag = dyn_cast<TagType>(T))
1357 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1358 if (const TemplateSpecializationType *TST
1359 = dyn_cast<TemplateSpecializationType>(T))
1360 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1361 break;
1362 }
1363
1364 case NestedNameSpecifier::TypeSpecWithTemplate:
1365 case NestedNameSpecifier::Global:
1366 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001367 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001368 break;
1369 }
1370
1371 return false;
1372}
1373
1374bool
1375CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1376 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1377 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1378 Qualifiers.push_back(Qualifier);
1379
1380 while (!Qualifiers.empty()) {
1381 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1382 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1383 switch (NNS->getKind()) {
1384 case NestedNameSpecifier::Namespace:
1385 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1386 Q.getLocalBeginLoc(),
1387 TU)))
1388 return true;
1389
1390 break;
1391
1392 case NestedNameSpecifier::NamespaceAlias:
1393 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1394 Q.getLocalBeginLoc(),
1395 TU)))
1396 return true;
1397
1398 break;
1399
1400 case NestedNameSpecifier::TypeSpec:
1401 case NestedNameSpecifier::TypeSpecWithTemplate:
1402 if (Visit(Q.getTypeLoc()))
1403 return true;
1404
1405 break;
1406
1407 case NestedNameSpecifier::Global:
1408 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001409 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 break;
1411 }
1412 }
1413
1414 return false;
1415}
1416
1417bool CursorVisitor::VisitTemplateParameters(
1418 const TemplateParameterList *Params) {
1419 if (!Params)
1420 return false;
1421
1422 for (TemplateParameterList::const_iterator P = Params->begin(),
1423 PEnd = Params->end();
1424 P != PEnd; ++P) {
1425 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1426 return true;
1427 }
1428
1429 return false;
1430}
1431
1432bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1433 switch (Name.getKind()) {
1434 case TemplateName::Template:
1435 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1436
1437 case TemplateName::OverloadedTemplate:
1438 // Visit the overloaded template set.
1439 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1440 return true;
1441
1442 return false;
1443
Richard Smithb23c5e82019-05-09 03:31:27 +00001444 case TemplateName::AssumedTemplate:
1445 // FIXME: Visit DeclarationName?
1446 return false;
1447
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 case TemplateName::DependentTemplate:
1449 // FIXME: Visit nested-name-specifier.
1450 return false;
1451
1452 case TemplateName::QualifiedTemplate:
1453 // FIXME: Visit nested-name-specifier.
1454 return Visit(MakeCursorTemplateRef(
1455 Name.getAsQualifiedTemplateName()->getDecl(),
1456 Loc, TU));
1457
1458 case TemplateName::SubstTemplateTemplateParm:
1459 return Visit(MakeCursorTemplateRef(
1460 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1461 Loc, TU));
1462
1463 case TemplateName::SubstTemplateTemplateParmPack:
1464 return Visit(MakeCursorTemplateRef(
1465 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1466 Loc, TU));
1467 }
1468
1469 llvm_unreachable("Invalid TemplateName::Kind!");
1470}
1471
1472bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1473 switch (TAL.getArgument().getKind()) {
1474 case TemplateArgument::Null:
1475 case TemplateArgument::Integral:
1476 case TemplateArgument::Pack:
1477 return false;
1478
1479 case TemplateArgument::Type:
1480 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1481 return Visit(TSInfo->getTypeLoc());
1482 return false;
1483
1484 case TemplateArgument::Declaration:
1485 if (Expr *E = TAL.getSourceDeclExpression())
1486 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1487 return false;
1488
1489 case TemplateArgument::NullPtr:
1490 if (Expr *E = TAL.getSourceNullPtrExpression())
1491 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1492 return false;
1493
1494 case TemplateArgument::Expression:
1495 if (Expr *E = TAL.getSourceExpression())
1496 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1497 return false;
1498
1499 case TemplateArgument::Template:
1500 case TemplateArgument::TemplateExpansion:
1501 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1502 return true;
1503
1504 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1505 TAL.getTemplateNameLoc());
1506 }
1507
1508 llvm_unreachable("Invalid TemplateArgument::Kind!");
1509}
1510
1511bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1512 return VisitDeclContext(D);
1513}
1514
1515bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1516 return Visit(TL.getUnqualifiedLoc());
1517}
1518
1519bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1520 ASTContext &Context = AU->getASTContext();
1521
1522 // Some builtin types (such as Objective-C's "id", "sel", and
1523 // "Class") have associated declarations. Create cursors for those.
1524 QualType VisitType;
1525 switch (TL.getTypePtr()->getKind()) {
1526
1527 case BuiltinType::Void:
1528 case BuiltinType::NullPtr:
1529 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001530#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1531 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001532#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001533#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1534 case BuiltinType::Id:
1535#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001536 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001537 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001538 case BuiltinType::OCLClkEvent:
1539 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001540 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001541#define SVE_TYPE(Name, Id, SingletonId) \
1542 case BuiltinType::Id:
1543#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00001544#define BUILTIN_TYPE(Id, SingletonId)
1545#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1546#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1547#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1548#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1549#include "clang/AST/BuiltinTypes.def"
1550 break;
1551
1552 case BuiltinType::ObjCId:
1553 VisitType = Context.getObjCIdType();
1554 break;
1555
1556 case BuiltinType::ObjCClass:
1557 VisitType = Context.getObjCClassType();
1558 break;
1559
1560 case BuiltinType::ObjCSel:
1561 VisitType = Context.getObjCSelType();
1562 break;
1563 }
1564
1565 if (!VisitType.isNull()) {
1566 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1567 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1568 TU));
1569 }
1570
1571 return false;
1572}
1573
1574bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1575 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1576}
1577
1578bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1579 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1580}
1581
1582bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1583 if (TL.isDefinition())
1584 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1585
1586 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1587}
1588
1589bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1590 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1591}
1592
1593bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001594 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001595}
1596
Manman Rene6be26c2016-09-13 17:25:08 +00001597bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001598 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001599 return true;
1600 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1601 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1602 TU)))
1603 return true;
1604 }
1605
1606 return false;
1607}
1608
Guy Benyei11169dd2012-12-18 14:30:41 +00001609bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1610 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1611 return true;
1612
Douglas Gregore9d95f12015-07-07 03:57:35 +00001613 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1614 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1615 return true;
1616 }
1617
Guy Benyei11169dd2012-12-18 14:30:41 +00001618 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1619 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1620 TU)))
1621 return true;
1622 }
1623
1624 return false;
1625}
1626
1627bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1628 return Visit(TL.getPointeeLoc());
1629}
1630
1631bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1632 return Visit(TL.getInnerLoc());
1633}
1634
Leonard Chanc72aaf62019-05-07 03:20:17 +00001635bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1636 return Visit(TL.getInnerLoc());
1637}
1638
Guy Benyei11169dd2012-12-18 14:30:41 +00001639bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1640 return Visit(TL.getPointeeLoc());
1641}
1642
1643bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1644 return Visit(TL.getPointeeLoc());
1645}
1646
1647bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1648 return Visit(TL.getPointeeLoc());
1649}
1650
1651bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1652 return Visit(TL.getPointeeLoc());
1653}
1654
1655bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1656 return Visit(TL.getPointeeLoc());
1657}
1658
1659bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1660 return Visit(TL.getModifiedLoc());
1661}
1662
1663bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1664 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001665 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 return true;
1667
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001668 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1669 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001670 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1671 return true;
1672
1673 return false;
1674}
1675
1676bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1677 if (Visit(TL.getElementLoc()))
1678 return true;
1679
1680 if (Expr *Size = TL.getSizeExpr())
1681 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1682
1683 return false;
1684}
1685
Reid Kleckner8a365022013-06-24 17:51:48 +00001686bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1687 return Visit(TL.getOriginalLoc());
1688}
1689
Reid Kleckner0503a872013-12-05 01:23:43 +00001690bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1691 return Visit(TL.getOriginalLoc());
1692}
1693
Richard Smith600b5262017-01-26 20:40:47 +00001694bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1695 DeducedTemplateSpecializationTypeLoc TL) {
1696 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1697 TL.getTemplateNameLoc()))
1698 return true;
1699
1700 return false;
1701}
1702
Guy Benyei11169dd2012-12-18 14:30:41 +00001703bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1704 TemplateSpecializationTypeLoc TL) {
1705 // Visit the template name.
1706 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1707 TL.getTemplateNameLoc()))
1708 return true;
1709
1710 // Visit the template arguments.
1711 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1712 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1713 return true;
1714
1715 return false;
1716}
1717
1718bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1719 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1720}
1721
1722bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1723 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1724 return Visit(TSInfo->getTypeLoc());
1725
1726 return false;
1727}
1728
1729bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1730 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1731 return Visit(TSInfo->getTypeLoc());
1732
1733 return false;
1734}
1735
1736bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001737 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001738}
1739
1740bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1741 DependentTemplateSpecializationTypeLoc TL) {
1742 // Visit the nested-name-specifier, if there is one.
1743 if (TL.getQualifierLoc() &&
1744 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1745 return true;
1746
1747 // Visit the template arguments.
1748 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1749 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1750 return true;
1751
1752 return false;
1753}
1754
1755bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1756 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1757 return true;
1758
1759 return Visit(TL.getNamedTypeLoc());
1760}
1761
1762bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1763 return Visit(TL.getPatternLoc());
1764}
1765
1766bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1767 if (Expr *E = TL.getUnderlyingExpr())
1768 return Visit(MakeCXCursor(E, StmtParent, TU));
1769
1770 return false;
1771}
1772
1773bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1774 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1775}
1776
1777bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1778 return Visit(TL.getValueLoc());
1779}
1780
Xiuli Pan9c14e282016-01-09 12:53:17 +00001781bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1782 return Visit(TL.getValueLoc());
1783}
1784
Guy Benyei11169dd2012-12-18 14:30:41 +00001785#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1786bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1787 return Visit##PARENT##Loc(TL); \
1788}
1789
1790DEFAULT_TYPELOC_IMPL(Complex, Type)
1791DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1792DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1793DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1794DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001795DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001796DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001797DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1798DEFAULT_TYPELOC_IMPL(Vector, Type)
1799DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1800DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1801DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1802DEFAULT_TYPELOC_IMPL(Record, TagType)
1803DEFAULT_TYPELOC_IMPL(Enum, TagType)
1804DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1805DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1806DEFAULT_TYPELOC_IMPL(Auto, Type)
1807
1808bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1809 // Visit the nested-name-specifier, if present.
1810 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1811 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1812 return true;
1813
1814 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001815 for (const auto &I : D->bases()) {
1816 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 return true;
1818 }
1819 }
1820
1821 return VisitTagDecl(D);
1822}
1823
1824bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001825 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001826 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1827 !I->isImplicit()) &&
1828 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 return true;
1830
1831 return false;
1832}
1833
1834//===----------------------------------------------------------------------===//
1835// Data-recursive visitor methods.
1836//===----------------------------------------------------------------------===//
1837
1838namespace {
1839#define DEF_JOB(NAME, DATA, KIND)\
1840class NAME : public VisitorJob {\
1841public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001842 NAME(const DATA *d, CXCursor parent) : \
1843 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001844 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001845 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001846};
1847
1848DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1849DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1850DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1851DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001852DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1853DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1854DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1855#undef DEF_JOB
1856
James Y Knight04ec5bf2015-12-24 02:59:37 +00001857class ExplicitTemplateArgsVisit : public VisitorJob {
1858public:
1859 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1860 const TemplateArgumentLoc *End, CXCursor parent)
1861 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1862 End) {}
1863 static bool classof(const VisitorJob *VJ) {
1864 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1865 }
1866 const TemplateArgumentLoc *begin() const {
1867 return static_cast<const TemplateArgumentLoc *>(data[0]);
1868 }
1869 const TemplateArgumentLoc *end() {
1870 return static_cast<const TemplateArgumentLoc *>(data[1]);
1871 }
1872};
Guy Benyei11169dd2012-12-18 14:30:41 +00001873class DeclVisit : public VisitorJob {
1874public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001875 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001877 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001878 static bool classof(const VisitorJob *VJ) {
1879 return VJ->getKind() == DeclVisitKind;
1880 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001881 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001882 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001883};
1884class TypeLocVisit : public VisitorJob {
1885public:
1886 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1887 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1888 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1889
1890 static bool classof(const VisitorJob *VJ) {
1891 return VJ->getKind() == TypeLocVisitKind;
1892 }
1893
1894 TypeLoc get() const {
1895 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001896 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001897 }
1898};
1899
1900class LabelRefVisit : public VisitorJob {
1901public:
1902 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1903 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1904 labelLoc.getPtrEncoding()) {}
1905
1906 static bool classof(const VisitorJob *VJ) {
1907 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1908 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001909 const LabelDecl *get() const {
1910 return static_cast<const LabelDecl *>(data[0]);
1911 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001912 SourceLocation getLoc() const {
1913 return SourceLocation::getFromPtrEncoding(data[1]); }
1914};
1915
1916class NestedNameSpecifierLocVisit : public VisitorJob {
1917public:
1918 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1919 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1920 Qualifier.getNestedNameSpecifier(),
1921 Qualifier.getOpaqueData()) { }
1922
1923 static bool classof(const VisitorJob *VJ) {
1924 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1925 }
1926
1927 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001928 return NestedNameSpecifierLoc(
1929 const_cast<NestedNameSpecifier *>(
1930 static_cast<const NestedNameSpecifier *>(data[0])),
1931 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001932 }
1933};
1934
1935class DeclarationNameInfoVisit : public VisitorJob {
1936public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001937 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001938 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001939 static bool classof(const VisitorJob *VJ) {
1940 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1941 }
1942 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001943 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001944 switch (S->getStmtClass()) {
1945 default:
1946 llvm_unreachable("Unhandled Stmt");
1947 case clang::Stmt::MSDependentExistsStmtClass:
1948 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1949 case Stmt::CXXDependentScopeMemberExprClass:
1950 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1951 case Stmt::DependentScopeDeclRefExprClass:
1952 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001953 case Stmt::OMPCriticalDirectiveClass:
1954 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001955 }
1956 }
1957};
1958class MemberRefVisit : public VisitorJob {
1959public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001960 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001961 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1962 L.getPtrEncoding()) {}
1963 static bool classof(const VisitorJob *VJ) {
1964 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1965 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001966 const FieldDecl *get() const {
1967 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001968 }
1969 SourceLocation getLoc() const {
1970 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1971 }
1972};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001973class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001974 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001975 VisitorWorkList &WL;
1976 CXCursor Parent;
1977public:
1978 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1979 : WL(wl), Parent(parent) {}
1980
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001981 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1982 void VisitBlockExpr(const BlockExpr *B);
1983 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1984 void VisitCompoundStmt(const CompoundStmt *S);
1985 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1986 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1987 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1988 void VisitCXXNewExpr(const CXXNewExpr *E);
1989 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1990 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1991 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1992 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1993 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1994 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1995 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1996 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001997 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001998 void VisitDeclRefExpr(const DeclRefExpr *D);
1999 void VisitDeclStmt(const DeclStmt *S);
2000 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
2001 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
2002 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
2003 void VisitForStmt(const ForStmt *FS);
2004 void VisitGotoStmt(const GotoStmt *GS);
2005 void VisitIfStmt(const IfStmt *If);
2006 void VisitInitListExpr(const InitListExpr *IE);
2007 void VisitMemberExpr(const MemberExpr *M);
2008 void VisitOffsetOfExpr(const OffsetOfExpr *E);
2009 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2010 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
2011 void VisitOverloadExpr(const OverloadExpr *E);
2012 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2013 void VisitStmt(const Stmt *S);
2014 void VisitSwitchStmt(const SwitchStmt *S);
2015 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002016 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2017 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2018 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2019 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2020 void VisitVAArgExpr(const VAArgExpr *E);
2021 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2022 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2023 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2024 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002025 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002026 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002027 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002028 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002029 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002030 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002031 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002032 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002033 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002034 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002035 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002036 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002037 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
cchen47d60942019-12-05 13:43:48 -05002038 void VisitOMPParallelMasterDirective(const OMPParallelMasterDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002039 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002040 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002041 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002042 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002043 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002044 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002045 void
2046 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002047 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002048 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002049 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002050 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002051 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002052 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002053 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002054 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002055 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002056 void
2057 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002058 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002059 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002060 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Alexey Bataev60e51c42019-10-10 20:13:02 +00002061 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002062 void
2063 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002064 void VisitOMPParallelMasterTaskLoopDirective(
2065 const OMPParallelMasterTaskLoopDirective *D);
Alexey Bataev14a388f2019-10-25 10:27:13 -04002066 void VisitOMPParallelMasterTaskLoopSimdDirective(
2067 const OMPParallelMasterTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002068 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002069 void VisitOMPDistributeParallelForDirective(
2070 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002071 void VisitOMPDistributeParallelForSimdDirective(
2072 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002073 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002074 void VisitOMPTargetParallelForSimdDirective(
2075 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002076 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002077 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002078 void VisitOMPTeamsDistributeSimdDirective(
2079 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002080 void VisitOMPTeamsDistributeParallelForSimdDirective(
2081 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002082 void VisitOMPTeamsDistributeParallelForDirective(
2083 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002084 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002085 void VisitOMPTargetTeamsDistributeDirective(
2086 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002087 void VisitOMPTargetTeamsDistributeParallelForDirective(
2088 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002089 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2090 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002091 void VisitOMPTargetTeamsDistributeSimdDirective(
2092 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002093
Guy Benyei11169dd2012-12-18 14:30:41 +00002094private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002095 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002097 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2098 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002099 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2100 void AddStmt(const Stmt *S);
2101 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002102 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002103 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002104 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002105};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002106} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002107
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002108void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002109 // 'S' should always be non-null, since it comes from the
2110 // statement we are visiting.
2111 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2112}
2113
2114void
2115EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2116 if (Qualifier)
2117 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2118}
2119
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002120void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002121 if (S)
2122 WL.push_back(StmtVisit(S, Parent));
2123}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002124void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002125 if (D)
2126 WL.push_back(DeclVisit(D, Parent, isFirst));
2127}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002128void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2129 unsigned NumTemplateArgs) {
2130 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002131}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002132void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002133 if (D)
2134 WL.push_back(MemberRefVisit(D, L, Parent));
2135}
2136void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2137 if (TI)
2138 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2139 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002140void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002141 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002142 for (const Stmt *SubStmt : S->children()) {
2143 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002144 }
2145 if (size == WL.size())
2146 return;
2147 // Now reverse the entries we just added. This will match the DFS
2148 // ordering performed by the worklist.
2149 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2150 std::reverse(I, E);
2151}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002152namespace {
2153class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2154 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002155 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002156 template <typename T>
2157 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002158public:
2159 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2160#define OPENMP_CLAUSE(Name, Class) \
2161 void Visit##Class(const Class *C);
2162#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002163 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002164 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002165};
2166
Alexey Bataev3392d762016-02-16 11:18:12 +00002167void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2168 const OMPClauseWithPreInit *C) {
2169 Visitor->AddStmt(C->getPreInitStmt());
2170}
2171
Alexey Bataev005248a2016-02-25 05:25:57 +00002172void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2173 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002174 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002175 Visitor->AddStmt(C->getPostUpdateExpr());
2176}
2177
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002178void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002179 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002180 Visitor->AddStmt(C->getCondition());
2181}
2182
Alexey Bataev3778b602014-07-17 07:32:53 +00002183void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2184 Visitor->AddStmt(C->getCondition());
2185}
2186
Alexey Bataev568a8332014-03-06 06:15:19 +00002187void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002188 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002189 Visitor->AddStmt(C->getNumThreads());
2190}
2191
Alexey Bataev62c87d22014-03-21 04:51:18 +00002192void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2193 Visitor->AddStmt(C->getSafelen());
2194}
2195
Alexey Bataev66b15b52015-08-21 11:14:16 +00002196void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2197 Visitor->AddStmt(C->getSimdlen());
2198}
2199
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002200void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2201 Visitor->AddStmt(C->getAllocator());
2202}
2203
Alexander Musman8bd31e62014-05-27 15:12:19 +00002204void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2205 Visitor->AddStmt(C->getNumForLoops());
2206}
2207
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002208void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002209
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002210void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2211
Alexey Bataev56dafe82014-06-20 07:16:17 +00002212void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002213 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002214 Visitor->AddStmt(C->getChunkSize());
2215}
2216
Alexey Bataev10e775f2015-07-30 11:36:16 +00002217void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2218 Visitor->AddStmt(C->getNumForLoops());
2219}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002220
Alexey Bataev236070f2014-06-20 11:19:47 +00002221void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2222
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002223void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2224
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002225void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2226
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002227void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2228
Alexey Bataevdea47612014-07-23 07:46:59 +00002229void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2230
Alexey Bataev67a4f222014-07-23 10:25:33 +00002231void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2232
Alexey Bataev459dec02014-07-24 06:46:57 +00002233void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2234
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002235void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2236
Alexey Bataev346265e2015-09-25 10:37:12 +00002237void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2238
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002239void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2240
Alexey Bataevb825de12015-12-07 10:51:44 +00002241void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2242
Kelvin Li1408f912018-09-26 04:28:39 +00002243void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2244 const OMPUnifiedAddressClause *) {}
2245
Patrick Lyster4a370b92018-10-01 13:47:43 +00002246void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2247 const OMPUnifiedSharedMemoryClause *) {}
2248
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002249void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2250 const OMPReverseOffloadClause *) {}
2251
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002252void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2253 const OMPDynamicAllocatorsClause *) {}
2254
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002255void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2256 const OMPAtomicDefaultMemOrderClause *) {}
2257
Michael Wonge710d542015-08-07 16:16:36 +00002258void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2259 Visitor->AddStmt(C->getDevice());
2260}
2261
Kelvin Li099bb8c2015-11-24 20:50:12 +00002262void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002263 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002264 Visitor->AddStmt(C->getNumTeams());
2265}
2266
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002267void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002268 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002269 Visitor->AddStmt(C->getThreadLimit());
2270}
2271
Alexey Bataeva0569352015-12-01 10:17:31 +00002272void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2273 Visitor->AddStmt(C->getPriority());
2274}
2275
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002276void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2277 Visitor->AddStmt(C->getGrainsize());
2278}
2279
Alexey Bataev382967a2015-12-08 12:06:20 +00002280void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2281 Visitor->AddStmt(C->getNumTasks());
2282}
2283
Alexey Bataev28c75412015-12-15 08:19:24 +00002284void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2285 Visitor->AddStmt(C->getHint());
2286}
2287
Alexey Bataev756c1962013-09-24 03:17:45 +00002288template<typename T>
2289void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002290 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002291 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002292 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002293}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002294
Alexey Bataeve04483e2019-03-27 14:14:31 +00002295void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2296 VisitOMPClauseList(C);
2297 Visitor->AddStmt(C->getAllocator());
2298}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002299void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002300 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002301 for (const auto *E : C->private_copies()) {
2302 Visitor->AddStmt(E);
2303 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002304}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002305void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2306 const OMPFirstprivateClause *C) {
2307 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002308 VisitOMPClauseWithPreInit(C);
2309 for (const auto *E : C->private_copies()) {
2310 Visitor->AddStmt(E);
2311 }
2312 for (const auto *E : C->inits()) {
2313 Visitor->AddStmt(E);
2314 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002315}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002316void OMPClauseEnqueue::VisitOMPLastprivateClause(
2317 const OMPLastprivateClause *C) {
2318 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002319 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002320 for (auto *E : C->private_copies()) {
2321 Visitor->AddStmt(E);
2322 }
2323 for (auto *E : C->source_exprs()) {
2324 Visitor->AddStmt(E);
2325 }
2326 for (auto *E : C->destination_exprs()) {
2327 Visitor->AddStmt(E);
2328 }
2329 for (auto *E : C->assignment_ops()) {
2330 Visitor->AddStmt(E);
2331 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002332}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002333void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002334 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002335}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002336void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2337 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002338 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002339 for (auto *E : C->privates()) {
2340 Visitor->AddStmt(E);
2341 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002342 for (auto *E : C->lhs_exprs()) {
2343 Visitor->AddStmt(E);
2344 }
2345 for (auto *E : C->rhs_exprs()) {
2346 Visitor->AddStmt(E);
2347 }
2348 for (auto *E : C->reduction_ops()) {
2349 Visitor->AddStmt(E);
2350 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002351}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002352void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2353 const OMPTaskReductionClause *C) {
2354 VisitOMPClauseList(C);
2355 VisitOMPClauseWithPostUpdate(C);
2356 for (auto *E : C->privates()) {
2357 Visitor->AddStmt(E);
2358 }
2359 for (auto *E : C->lhs_exprs()) {
2360 Visitor->AddStmt(E);
2361 }
2362 for (auto *E : C->rhs_exprs()) {
2363 Visitor->AddStmt(E);
2364 }
2365 for (auto *E : C->reduction_ops()) {
2366 Visitor->AddStmt(E);
2367 }
2368}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002369void OMPClauseEnqueue::VisitOMPInReductionClause(
2370 const OMPInReductionClause *C) {
2371 VisitOMPClauseList(C);
2372 VisitOMPClauseWithPostUpdate(C);
2373 for (auto *E : C->privates()) {
2374 Visitor->AddStmt(E);
2375 }
2376 for (auto *E : C->lhs_exprs()) {
2377 Visitor->AddStmt(E);
2378 }
2379 for (auto *E : C->rhs_exprs()) {
2380 Visitor->AddStmt(E);
2381 }
2382 for (auto *E : C->reduction_ops()) {
2383 Visitor->AddStmt(E);
2384 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002385 for (auto *E : C->taskgroup_descriptors())
2386 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002387}
Alexander Musman8dba6642014-04-22 13:09:42 +00002388void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2389 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002390 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002391 for (const auto *E : C->privates()) {
2392 Visitor->AddStmt(E);
2393 }
Alexander Musman3276a272015-03-21 10:12:56 +00002394 for (const auto *E : C->inits()) {
2395 Visitor->AddStmt(E);
2396 }
2397 for (const auto *E : C->updates()) {
2398 Visitor->AddStmt(E);
2399 }
2400 for (const auto *E : C->finals()) {
2401 Visitor->AddStmt(E);
2402 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002403 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002404 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002405}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002406void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2407 VisitOMPClauseList(C);
2408 Visitor->AddStmt(C->getAlignment());
2409}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002410void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2411 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002412 for (auto *E : C->source_exprs()) {
2413 Visitor->AddStmt(E);
2414 }
2415 for (auto *E : C->destination_exprs()) {
2416 Visitor->AddStmt(E);
2417 }
2418 for (auto *E : C->assignment_ops()) {
2419 Visitor->AddStmt(E);
2420 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002421}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002422void
2423OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2424 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002425 for (auto *E : C->source_exprs()) {
2426 Visitor->AddStmt(E);
2427 }
2428 for (auto *E : C->destination_exprs()) {
2429 Visitor->AddStmt(E);
2430 }
2431 for (auto *E : C->assignment_ops()) {
2432 Visitor->AddStmt(E);
2433 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002434}
Alexey Bataev6125da92014-07-21 11:26:11 +00002435void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2436 VisitOMPClauseList(C);
2437}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002438void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2439 VisitOMPClauseList(C);
2440}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002441void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2442 VisitOMPClauseList(C);
2443}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002444void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2445 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002446 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002447 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002448}
Alexey Bataev3392d762016-02-16 11:18:12 +00002449void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2450 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002451void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2452 VisitOMPClauseList(C);
2453}
Samuel Antaoec172c62016-05-26 17:49:04 +00002454void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2455 VisitOMPClauseList(C);
2456}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002457void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2458 VisitOMPClauseList(C);
2459}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002460void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2461 VisitOMPClauseList(C);
2462}
Alexey Bataevb6e70842019-12-16 15:54:17 -05002463void OMPClauseEnqueue::VisitOMPNontemporalClause(
2464 const OMPNontemporalClause *C) {
2465 VisitOMPClauseList(C);
Alexey Bataev0860db92019-12-19 10:01:10 -05002466 for (const auto *E : C->private_refs())
2467 Visitor->AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05002468}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002469}
Alexey Bataev756c1962013-09-24 03:17:45 +00002470
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002471void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2472 unsigned size = WL.size();
2473 OMPClauseEnqueue Visitor(this);
2474 Visitor.Visit(S);
2475 if (size == WL.size())
2476 return;
2477 // Now reverse the entries we just added. This will match the DFS
2478 // ordering performed by the worklist.
2479 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2480 std::reverse(I, E);
2481}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002482void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2484}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002485void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 AddDecl(B->getBlockDecl());
2487}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002488void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 EnqueueChildren(E);
2490 AddTypeLoc(E->getTypeSourceInfo());
2491}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002492void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002493 for (auto &I : llvm::reverse(S->body()))
2494 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002495}
2496void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002497VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 AddStmt(S->getSubStmt());
2499 AddDeclarationNameInfo(S);
2500 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2501 AddNestedNameSpecifierLoc(QualifierLoc);
2502}
2503
2504void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002505VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002506 if (E->hasExplicitTemplateArgs())
2507 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 AddDeclarationNameInfo(E);
2509 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2510 AddNestedNameSpecifierLoc(QualifierLoc);
2511 if (!E->isImplicitAccess())
2512 AddStmt(E->getBase());
2513}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002514void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 // Enqueue the initializer , if any.
2516 AddStmt(E->getInitializer());
2517 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002518 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 // Enqueue the allocated type.
2520 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2521 // Enqueue the placement arguments.
2522 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2523 AddStmt(E->getPlacementArg(I-1));
2524}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002525void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2527 AddStmt(CE->getArg(I-1));
2528 AddStmt(CE->getCallee());
2529 AddStmt(CE->getArg(0));
2530}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002531void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2532 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 // Visit the name of the type being destroyed.
2534 AddTypeLoc(E->getDestroyedTypeInfo());
2535 // Visit the scope type that looks disturbingly like the nested-name-specifier
2536 // but isn't.
2537 AddTypeLoc(E->getScopeTypeInfo());
2538 // Visit the nested-name-specifier.
2539 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2540 AddNestedNameSpecifierLoc(QualifierLoc);
2541 // Visit base expression.
2542 AddStmt(E->getBase());
2543}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002544void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2545 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 AddTypeLoc(E->getTypeSourceInfo());
2547}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002548void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2549 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 EnqueueChildren(E);
2551 AddTypeLoc(E->getTypeSourceInfo());
2552}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002553void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 EnqueueChildren(E);
2555 if (E->isTypeOperand())
2556 AddTypeLoc(E->getTypeOperandSourceInfo());
2557}
2558
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002559void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2560 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 EnqueueChildren(E);
2562 AddTypeLoc(E->getTypeSourceInfo());
2563}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002564void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 EnqueueChildren(E);
2566 if (E->isTypeOperand())
2567 AddTypeLoc(E->getTypeOperandSourceInfo());
2568}
2569
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002570void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 EnqueueChildren(S);
2572 AddDecl(S->getExceptionDecl());
2573}
2574
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002575void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002576 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002577 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002578 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002579}
2580
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002581void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002582 if (DR->hasExplicitTemplateArgs())
2583 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 WL.push_back(DeclRefExprParts(DR, Parent));
2585}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002586void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2587 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002588 if (E->hasExplicitTemplateArgs())
2589 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 AddDeclarationNameInfo(E);
2591 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2592}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002593void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 unsigned size = WL.size();
2595 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002596 for (const auto *D : S->decls()) {
2597 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 isFirst = false;
2599 }
2600 if (size == WL.size())
2601 return;
2602 // Now reverse the entries we just added. This will match the DFS
2603 // ordering performed by the worklist.
2604 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2605 std::reverse(I, E);
2606}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002607void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002609 for (const DesignatedInitExpr::Designator &D :
2610 llvm::reverse(E->designators())) {
2611 if (D.isFieldDesignator()) {
2612 if (FieldDecl *Field = D.getField())
2613 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 continue;
2615 }
David Majnemerf7e36092016-06-23 00:15:04 +00002616 if (D.isArrayDesignator()) {
2617 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 continue;
2619 }
David Majnemerf7e36092016-06-23 00:15:04 +00002620 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2621 AddStmt(E->getArrayRangeEnd(D));
2622 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 }
2624}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002625void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 EnqueueChildren(E);
2627 AddTypeLoc(E->getTypeInfoAsWritten());
2628}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002629void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 AddStmt(FS->getBody());
2631 AddStmt(FS->getInc());
2632 AddStmt(FS->getCond());
2633 AddDecl(FS->getConditionVariable());
2634 AddStmt(FS->getInit());
2635}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002636void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2638}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002639void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 AddStmt(If->getElse());
2641 AddStmt(If->getThen());
2642 AddStmt(If->getCond());
2643 AddDecl(If->getConditionVariable());
2644}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002645void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 // We care about the syntactic form of the initializer list, only.
2647 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2648 IE = Syntactic;
2649 EnqueueChildren(IE);
2650}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002651void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 WL.push_back(MemberExprParts(M, Parent));
2653
2654 // If the base of the member access expression is an implicit 'this', don't
2655 // visit it.
2656 // FIXME: If we ever want to show these implicit accesses, this will be
2657 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002658 if (M->isImplicitAccess())
2659 return;
2660
2661 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002662 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002663 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2664 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2665 if (FD->isAnonymousStructOrUnion()) {
2666 AddStmt(SubME->getBase());
2667 return;
2668 }
2669 }
2670 }
2671
2672 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002673}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002674void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 AddTypeLoc(E->getEncodedTypeSourceInfo());
2676}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002677void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 EnqueueChildren(M);
2679 AddTypeLoc(M->getClassReceiverTypeInfo());
2680}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002681void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 // Visit the components of the offsetof expression.
2683 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 const OffsetOfNode &Node = E->getComponent(I-1);
2685 switch (Node.getKind()) {
2686 case OffsetOfNode::Array:
2687 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2688 break;
2689 case OffsetOfNode::Field:
2690 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2691 break;
2692 case OffsetOfNode::Identifier:
2693 case OffsetOfNode::Base:
2694 continue;
2695 }
2696 }
2697 // Visit the type into which we're computing the offset.
2698 AddTypeLoc(E->getTypeSourceInfo());
2699}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002700void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002701 if (E->hasExplicitTemplateArgs())
2702 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 WL.push_back(OverloadExprParts(E, Parent));
2704}
2705void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002706 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 EnqueueChildren(E);
2708 if (E->isArgumentType())
2709 AddTypeLoc(E->getArgumentTypeInfo());
2710}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002711void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 EnqueueChildren(S);
2713}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002714void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 AddStmt(S->getBody());
2716 AddStmt(S->getCond());
2717 AddDecl(S->getConditionVariable());
2718}
2719
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002720void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 AddStmt(W->getBody());
2722 AddStmt(W->getCond());
2723 AddDecl(W->getConditionVariable());
2724}
2725
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002726void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 for (unsigned I = E->getNumArgs(); I > 0; --I)
2728 AddTypeLoc(E->getArg(I-1));
2729}
2730
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002731void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 AddTypeLoc(E->getQueriedTypeSourceInfo());
2733}
2734
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002735void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 EnqueueChildren(E);
2737}
2738
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002739void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 VisitOverloadExpr(U);
2741 if (!U->isImplicitAccess())
2742 AddStmt(U->getBase());
2743}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002744void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 AddStmt(E->getSubExpr());
2746 AddTypeLoc(E->getWrittenTypeInfo());
2747}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002748void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 WL.push_back(SizeOfPackExprParts(E, Parent));
2750}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002751void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 // If the opaque value has a source expression, just transparently
2753 // visit that. This is useful for (e.g.) pseudo-object expressions.
2754 if (Expr *SourceExpr = E->getSourceExpr())
2755 return Visit(SourceExpr);
2756}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002757void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 AddStmt(E->getBody());
2759 WL.push_back(LambdaExprParts(E, Parent));
2760}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002761void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 // Treat the expression like its syntactic form.
2763 Visit(E->getSyntacticForm());
2764}
2765
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002766void EnqueueVisitor::VisitOMPExecutableDirective(
2767 const OMPExecutableDirective *D) {
2768 EnqueueChildren(D);
2769 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2770 E = D->clauses().end();
2771 I != E; ++I)
2772 EnqueueChildren(*I);
2773}
2774
Alexander Musman3aaab662014-08-19 11:27:13 +00002775void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2776 VisitOMPExecutableDirective(D);
2777}
2778
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002779void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2780 VisitOMPExecutableDirective(D);
2781}
2782
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002783void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002784 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002785}
2786
Alexey Bataevf29276e2014-06-18 04:14:57 +00002787void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002788 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002789}
2790
Alexander Musmanf82886e2014-09-18 05:12:34 +00002791void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2792 VisitOMPLoopDirective(D);
2793}
2794
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002795void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2796 VisitOMPExecutableDirective(D);
2797}
2798
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002799void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2800 VisitOMPExecutableDirective(D);
2801}
2802
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002803void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2804 VisitOMPExecutableDirective(D);
2805}
2806
Alexander Musman80c22892014-07-17 08:54:58 +00002807void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2808 VisitOMPExecutableDirective(D);
2809}
2810
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002811void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2812 VisitOMPExecutableDirective(D);
2813 AddDeclarationNameInfo(D);
2814}
2815
Alexey Bataev4acb8592014-07-07 13:01:15 +00002816void
2817EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002818 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002819}
2820
Alexander Musmane4e893b2014-09-23 09:33:00 +00002821void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2822 const OMPParallelForSimdDirective *D) {
2823 VisitOMPLoopDirective(D);
2824}
2825
cchen47d60942019-12-05 13:43:48 -05002826void EnqueueVisitor::VisitOMPParallelMasterDirective(
2827 const OMPParallelMasterDirective *D) {
2828 VisitOMPExecutableDirective(D);
2829}
2830
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002831void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2832 const OMPParallelSectionsDirective *D) {
2833 VisitOMPExecutableDirective(D);
2834}
2835
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002836void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2837 VisitOMPExecutableDirective(D);
2838}
2839
Alexey Bataev68446b72014-07-18 07:47:19 +00002840void
2841EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2842 VisitOMPExecutableDirective(D);
2843}
2844
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002845void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2846 VisitOMPExecutableDirective(D);
2847}
2848
Alexey Bataev2df347a2014-07-18 10:17:07 +00002849void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2850 VisitOMPExecutableDirective(D);
2851}
2852
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002853void EnqueueVisitor::VisitOMPTaskgroupDirective(
2854 const OMPTaskgroupDirective *D) {
2855 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002856 if (const Expr *E = D->getReductionRef())
2857 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002858}
2859
Alexey Bataev6125da92014-07-21 11:26:11 +00002860void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2861 VisitOMPExecutableDirective(D);
2862}
2863
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002864void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2865 VisitOMPExecutableDirective(D);
2866}
2867
Alexey Bataev0162e452014-07-22 10:10:35 +00002868void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2869 VisitOMPExecutableDirective(D);
2870}
2871
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002872void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2873 VisitOMPExecutableDirective(D);
2874}
2875
Michael Wong65f367f2015-07-21 13:44:28 +00002876void EnqueueVisitor::VisitOMPTargetDataDirective(const
2877 OMPTargetDataDirective *D) {
2878 VisitOMPExecutableDirective(D);
2879}
2880
Samuel Antaodf67fc42016-01-19 19:15:56 +00002881void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2882 const OMPTargetEnterDataDirective *D) {
2883 VisitOMPExecutableDirective(D);
2884}
2885
Samuel Antao72590762016-01-19 20:04:50 +00002886void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2887 const OMPTargetExitDataDirective *D) {
2888 VisitOMPExecutableDirective(D);
2889}
2890
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002891void EnqueueVisitor::VisitOMPTargetParallelDirective(
2892 const OMPTargetParallelDirective *D) {
2893 VisitOMPExecutableDirective(D);
2894}
2895
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002896void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2897 const OMPTargetParallelForDirective *D) {
2898 VisitOMPLoopDirective(D);
2899}
2900
Alexey Bataev13314bf2014-10-09 04:18:56 +00002901void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2902 VisitOMPExecutableDirective(D);
2903}
2904
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002905void EnqueueVisitor::VisitOMPCancellationPointDirective(
2906 const OMPCancellationPointDirective *D) {
2907 VisitOMPExecutableDirective(D);
2908}
2909
Alexey Bataev80909872015-07-02 11:25:17 +00002910void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2911 VisitOMPExecutableDirective(D);
2912}
2913
Alexey Bataev49f6e782015-12-01 04:18:41 +00002914void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2915 VisitOMPLoopDirective(D);
2916}
2917
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002918void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2919 const OMPTaskLoopSimdDirective *D) {
2920 VisitOMPLoopDirective(D);
2921}
2922
Alexey Bataev60e51c42019-10-10 20:13:02 +00002923void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2924 const OMPMasterTaskLoopDirective *D) {
2925 VisitOMPLoopDirective(D);
2926}
2927
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002928void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2929 const OMPMasterTaskLoopSimdDirective *D) {
2930 VisitOMPLoopDirective(D);
2931}
2932
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002933void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2934 const OMPParallelMasterTaskLoopDirective *D) {
2935 VisitOMPLoopDirective(D);
2936}
2937
Alexey Bataev14a388f2019-10-25 10:27:13 -04002938void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
2939 const OMPParallelMasterTaskLoopSimdDirective *D) {
2940 VisitOMPLoopDirective(D);
2941}
2942
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002943void EnqueueVisitor::VisitOMPDistributeDirective(
2944 const OMPDistributeDirective *D) {
2945 VisitOMPLoopDirective(D);
2946}
2947
Carlo Bertolli9925f152016-06-27 14:55:37 +00002948void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2949 const OMPDistributeParallelForDirective *D) {
2950 VisitOMPLoopDirective(D);
2951}
2952
Kelvin Li4a39add2016-07-05 05:00:15 +00002953void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2954 const OMPDistributeParallelForSimdDirective *D) {
2955 VisitOMPLoopDirective(D);
2956}
2957
Kelvin Li787f3fc2016-07-06 04:45:38 +00002958void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2959 const OMPDistributeSimdDirective *D) {
2960 VisitOMPLoopDirective(D);
2961}
2962
Kelvin Lia579b912016-07-14 02:54:56 +00002963void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2964 const OMPTargetParallelForSimdDirective *D) {
2965 VisitOMPLoopDirective(D);
2966}
2967
Kelvin Li986330c2016-07-20 22:57:10 +00002968void EnqueueVisitor::VisitOMPTargetSimdDirective(
2969 const OMPTargetSimdDirective *D) {
2970 VisitOMPLoopDirective(D);
2971}
2972
Kelvin Li02532872016-08-05 14:37:37 +00002973void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2974 const OMPTeamsDistributeDirective *D) {
2975 VisitOMPLoopDirective(D);
2976}
2977
Kelvin Li4e325f72016-10-25 12:50:55 +00002978void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2979 const OMPTeamsDistributeSimdDirective *D) {
2980 VisitOMPLoopDirective(D);
2981}
2982
Kelvin Li579e41c2016-11-30 23:51:03 +00002983void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2984 const OMPTeamsDistributeParallelForSimdDirective *D) {
2985 VisitOMPLoopDirective(D);
2986}
2987
Kelvin Li7ade93f2016-12-09 03:24:30 +00002988void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2989 const OMPTeamsDistributeParallelForDirective *D) {
2990 VisitOMPLoopDirective(D);
2991}
2992
Kelvin Libf594a52016-12-17 05:48:59 +00002993void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2994 const OMPTargetTeamsDirective *D) {
2995 VisitOMPExecutableDirective(D);
2996}
2997
Kelvin Li83c451e2016-12-25 04:52:54 +00002998void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2999 const OMPTargetTeamsDistributeDirective *D) {
3000 VisitOMPLoopDirective(D);
3001}
3002
Kelvin Li80e8f562016-12-29 22:16:30 +00003003void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3004 const OMPTargetTeamsDistributeParallelForDirective *D) {
3005 VisitOMPLoopDirective(D);
3006}
3007
Kelvin Li1851df52017-01-03 05:23:48 +00003008void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3009 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3010 VisitOMPLoopDirective(D);
3011}
3012
Kelvin Lida681182017-01-10 18:08:18 +00003013void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3014 const OMPTargetTeamsDistributeSimdDirective *D) {
3015 VisitOMPLoopDirective(D);
3016}
3017
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003018void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
3020}
3021
3022bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3023 if (RegionOfInterest.isValid()) {
3024 SourceRange Range = getRawCursorExtent(C);
3025 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3026 return false;
3027 }
3028 return true;
3029}
3030
3031bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3032 while (!WL.empty()) {
3033 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003034 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003035
3036 // Set the Parent field, then back to its old value once we're done.
3037 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3038
3039 switch (LI.getKind()) {
3040 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003041 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 if (!D)
3043 continue;
3044
3045 // For now, perform default visitation for Decls.
3046 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3047 cast<DeclVisit>(&LI)->isFirst())))
3048 return true;
3049
3050 continue;
3051 }
3052 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003053 for (const TemplateArgumentLoc &Arg :
3054 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3055 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 return true;
3057 }
3058 continue;
3059 }
3060 case VisitorJob::TypeLocVisitKind: {
3061 // Perform default visitation for TypeLocs.
3062 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3063 return true;
3064 continue;
3065 }
3066 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003067 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 if (LabelStmt *stmt = LS->getStmt()) {
3069 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3070 TU))) {
3071 return true;
3072 }
3073 }
3074 continue;
3075 }
3076
3077 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3078 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3079 if (VisitNestedNameSpecifierLoc(V->get()))
3080 return true;
3081 continue;
3082 }
3083
3084 case VisitorJob::DeclarationNameInfoVisitKind: {
3085 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3086 ->get()))
3087 return true;
3088 continue;
3089 }
3090 case VisitorJob::MemberRefVisitKind: {
3091 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3092 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3093 return true;
3094 continue;
3095 }
3096 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003097 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 if (!S)
3099 continue;
3100
3101 // Update the current cursor.
3102 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3103 if (!IsInRegionOfInterest(Cursor))
3104 continue;
3105 switch (Visitor(Cursor, Parent, ClientData)) {
3106 case CXChildVisit_Break: return true;
3107 case CXChildVisit_Continue: break;
3108 case CXChildVisit_Recurse:
3109 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003110 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 EnqueueWorkList(WL, S);
3112 break;
3113 }
3114 continue;
3115 }
3116 case VisitorJob::MemberExprPartsKind: {
3117 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003118 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003119
3120 // Visit the nested-name-specifier
3121 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3122 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3123 return true;
3124
3125 // Visit the declaration name.
3126 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3127 return true;
3128
3129 // Visit the explicitly-specified template arguments, if any.
3130 if (M->hasExplicitTemplateArgs()) {
3131 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3132 *ArgEnd = Arg + M->getNumTemplateArgs();
3133 Arg != ArgEnd; ++Arg) {
3134 if (VisitTemplateArgumentLoc(*Arg))
3135 return true;
3136 }
3137 }
3138 continue;
3139 }
3140 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003141 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 // Visit nested-name-specifier, if present.
3143 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3144 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3145 return true;
3146 // Visit declaration name.
3147 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3148 return true;
3149 continue;
3150 }
3151 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003152 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 // Visit the nested-name-specifier.
3154 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3155 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3156 return true;
3157 // Visit the declaration name.
3158 if (VisitDeclarationNameInfo(O->getNameInfo()))
3159 return true;
3160 // Visit the overloaded declaration reference.
3161 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3162 return true;
3163 continue;
3164 }
3165 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003166 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 NamedDecl *Pack = E->getPack();
3168 if (isa<TemplateTypeParmDecl>(Pack)) {
3169 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3170 E->getPackLoc(), TU)))
3171 return true;
3172
3173 continue;
3174 }
3175
3176 if (isa<TemplateTemplateParmDecl>(Pack)) {
3177 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3178 E->getPackLoc(), TU)))
3179 return true;
3180
3181 continue;
3182 }
3183
3184 // Non-type template parameter packs and function parameter packs are
3185 // treated like DeclRefExpr cursors.
3186 continue;
3187 }
3188
3189 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003190 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003191 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3193 CEnd = E->explicit_capture_end();
3194 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003195 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003197
Guy Benyei11169dd2012-12-18 14:30:41 +00003198 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3199 C->getLocation(),
3200 TU)))
3201 return true;
3202 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003203 // Visit init captures
3204 for (auto InitExpr : E->capture_inits()) {
3205 if (Visit(InitExpr))
3206 return true;
3207 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003208
Haojian Wuef87c262018-12-18 15:29:12 +00003209 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003211 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3212 if (E->hasExplicitParameters()) {
3213 // Visit parameters.
3214 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3215 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003216 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003217 }
3218 if (E->hasExplicitResultType()) {
3219 // Visit result type.
3220 if (Visit(Proto.getReturnLoc()))
3221 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 }
3223 }
3224 break;
3225 }
3226
3227 case VisitorJob::PostChildrenVisitKind:
3228 if (PostChildrenVisitor(Parent, ClientData))
3229 return true;
3230 break;
3231 }
3232 }
3233 return false;
3234}
3235
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003236bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003237 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 if (!WorkListFreeList.empty()) {
3239 WL = WorkListFreeList.back();
3240 WL->clear();
3241 WorkListFreeList.pop_back();
3242 }
3243 else {
3244 WL = new VisitorWorkList();
3245 WorkListCache.push_back(WL);
3246 }
3247 EnqueueWorkList(*WL, S);
3248 bool result = RunVisitorWorkList(*WL);
3249 WorkListFreeList.push_back(WL);
3250 return result;
3251}
3252
3253namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003254typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003255RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3256 const DeclarationNameInfo &NI, SourceRange QLoc,
3257 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3259 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3260 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3261
3262 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3263
3264 RefNamePieces Pieces;
3265
3266 if (WantQualifier && QLoc.isValid())
3267 Pieces.push_back(QLoc);
3268
3269 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3270 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003271
3272 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3273 Pieces.push_back(*TemplateArgsLoc);
3274
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 if (Kind == DeclarationName::CXXOperatorName) {
3276 Pieces.push_back(SourceLocation::getFromRawEncoding(
3277 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3278 Pieces.push_back(SourceLocation::getFromRawEncoding(
3279 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3280 }
3281
3282 if (WantSinglePiece) {
3283 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3284 Pieces.clear();
3285 Pieces.push_back(R);
3286 }
3287
3288 return Pieces;
3289}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003290}
Guy Benyei11169dd2012-12-18 14:30:41 +00003291
3292//===----------------------------------------------------------------------===//
3293// Misc. API hooks.
3294//===----------------------------------------------------------------------===//
3295
Chandler Carruth66660742014-06-27 16:37:27 +00003296namespace {
3297struct RegisterFatalErrorHandler {
3298 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003299 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003300 }
3301};
3302}
3303
3304static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3305
Guy Benyei11169dd2012-12-18 14:30:41 +00003306CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3307 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003308 // We use crash recovery to make some of our APIs more reliable, implicitly
3309 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003310 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3311 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003312
Chandler Carruth66660742014-06-27 16:37:27 +00003313 // Look through the managed static to trigger construction of the managed
3314 // static which registers our fatal error handler. This ensures it is only
3315 // registered once.
3316 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003317
Adrian Prantlbc068582015-07-08 01:00:30 +00003318 // Initialize targets for clang module support.
3319 llvm::InitializeAllTargets();
3320 llvm::InitializeAllTargetMCs();
3321 llvm::InitializeAllAsmPrinters();
3322 llvm::InitializeAllAsmParsers();
3323
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003324 CIndexer *CIdxr = new CIndexer();
3325
Guy Benyei11169dd2012-12-18 14:30:41 +00003326 if (excludeDeclarationsFromPCH)
3327 CIdxr->setOnlyLocalDecls();
3328 if (displayDiagnostics)
3329 CIdxr->setDisplayDiagnostics();
3330
3331 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3332 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3333 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3334 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3335 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3336 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3337
3338 return CIdxr;
3339}
3340
3341void clang_disposeIndex(CXIndex CIdx) {
3342 if (CIdx)
3343 delete static_cast<CIndexer *>(CIdx);
3344}
3345
3346void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3347 if (CIdx)
3348 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3349}
3350
3351unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3352 if (CIdx)
3353 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3354 return 0;
3355}
3356
Alex Lorenz08615792017-12-04 21:56:36 +00003357void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3358 const char *Path) {
3359 if (CIdx)
3360 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3361}
3362
Guy Benyei11169dd2012-12-18 14:30:41 +00003363void clang_toggleCrashRecovery(unsigned isEnabled) {
3364 if (isEnabled)
3365 llvm::CrashRecoveryContext::Enable();
3366 else
3367 llvm::CrashRecoveryContext::Disable();
3368}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003369
Guy Benyei11169dd2012-12-18 14:30:41 +00003370CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3371 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003372 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003373 enum CXErrorCode Result =
3374 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003375 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003376 assert((TU && Result == CXError_Success) ||
3377 (!TU && Result != CXError_Success));
3378 return TU;
3379}
3380
3381enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3382 const char *ast_filename,
3383 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003384 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003385 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003386
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003387 if (!CIdx || !ast_filename || !out_TU)
3388 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003389
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003390 LOG_FUNC_SECTION {
3391 *Log << ast_filename;
3392 }
3393
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3395 FileSystemOptions FileSystemOpts;
3396
Justin Bognerd512c1e2014-10-15 00:33:06 +00003397 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3398 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003399 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003400 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3401 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003402 FileSystemOpts, /*UseDebugInfo=*/false,
3403 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003404 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003405 /*AllowPCHWithCompilerErrors=*/true,
3406 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003407 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003408 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003409}
3410
3411unsigned clang_defaultEditingTranslationUnitOptions() {
3412 return CXTranslationUnit_PrecompiledPreamble |
3413 CXTranslationUnit_CacheCompletionResults;
3414}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003415
Guy Benyei11169dd2012-12-18 14:30:41 +00003416CXTranslationUnit
3417clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3418 const char *source_filename,
3419 int num_command_line_args,
3420 const char * const *command_line_args,
3421 unsigned num_unsaved_files,
3422 struct CXUnsavedFile *unsaved_files) {
3423 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3424 return clang_parseTranslationUnit(CIdx, source_filename,
3425 command_line_args, num_command_line_args,
3426 unsaved_files, num_unsaved_files,
3427 Options);
3428}
3429
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003430static CXErrorCode
3431clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3432 const char *const *command_line_args,
3433 int num_command_line_args,
3434 ArrayRef<CXUnsavedFile> unsaved_files,
3435 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003436 // Set up the initial return values.
3437 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003438 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003439
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003440 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003441 if (!CIdx || !out_TU)
3442 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003443
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3445
3446 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3447 setThreadBackgroundPriority();
3448
3449 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003450 bool CreatePreambleOnFirstParse =
3451 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003452 // FIXME: Add a flag for modules.
3453 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003454 = (options & (CXTranslationUnit_Incomplete |
3455 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003456 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003457 = options & CXTranslationUnit_CacheCompletionResults;
3458 bool IncludeBriefCommentsInCodeCompletion
3459 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003460 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3461 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003462 bool RetainExcludedCB = options &
3463 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003464 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3465 if (options & CXTranslationUnit_SkipFunctionBodies) {
3466 SkipFunctionBodies =
3467 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3468 ? SkipFunctionBodiesScope::Preamble
3469 : SkipFunctionBodiesScope::PreambleAndMainFile;
3470 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003471
3472 // Configure the diagnostics.
3473 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003474 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003475
Manuel Klimek016c0242016-03-01 10:56:19 +00003476 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003477 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003478
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003479 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3480 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3481 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3482
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 // Recover resources if we crash before exiting this function.
3484 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3485 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003486 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003487
Ahmed Charlesb8984322014-03-07 20:03:18 +00003488 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3489 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003490
3491 // Recover resources if we crash before exiting this function.
3492 llvm::CrashRecoveryContextCleanupRegistrar<
3493 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3494
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003495 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003496 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003497 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003498 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003499 }
3500
Ahmed Charlesb8984322014-03-07 20:03:18 +00003501 std::unique_ptr<std::vector<const char *>> Args(
3502 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003503
3504 // Recover resources if we crash before exiting this method.
3505 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3506 ArgsCleanup(Args.get());
3507
3508 // Since the Clang C library is primarily used by batch tools dealing with
3509 // (often very broken) source code, where spell-checking can have a
3510 // significant negative impact on performance (particularly when
3511 // precompiled headers are involved), we disable it by default.
3512 // Only do this if we haven't found a spell-checking-related argument.
3513 bool FoundSpellCheckingArgument = false;
3514 for (int I = 0; I != num_command_line_args; ++I) {
3515 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3516 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3517 FoundSpellCheckingArgument = true;
3518 break;
3519 }
3520 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 Args->insert(Args->end(), command_line_args,
3522 command_line_args + num_command_line_args);
3523
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003524 if (!FoundSpellCheckingArgument)
3525 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3526
Guy Benyei11169dd2012-12-18 14:30:41 +00003527 // The 'source_filename' argument is optional. If the caller does not
3528 // specify it then it is assumed that the source file is specified
3529 // in the actual argument list.
3530 // Put the source file after command_line_args otherwise if '-x' flag is
3531 // present it will be unused.
3532 if (source_filename)
3533 Args->push_back(source_filename);
3534
3535 // Do we need the detailed preprocessing record?
3536 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3537 Args->push_back("-Xclang");
3538 Args->push_back("-detailed-preprocessing-record");
3539 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003540
3541 // Suppress any editor placeholder diagnostics.
3542 Args->push_back("-fallow-editor-placeholders");
3543
Guy Benyei11169dd2012-12-18 14:30:41 +00003544 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003545 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003546 // Unless the user specified that they want the preamble on the first parse
3547 // set it up to be created on the first reparse. This makes the first parse
3548 // faster, trading for a slower (first) reparse.
3549 unsigned PrecompilePreambleAfterNParses =
3550 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003551
Alex Lorenz08615792017-12-04 21:56:36 +00003552 LibclangInvocationReporter InvocationReporter(
3553 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003554 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3555 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003556 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003557 Args->data(), Args->data() + Args->size(),
3558 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003559 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003560 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003561 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3562 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003563 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003564 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003565 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3566 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003567
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003568 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003569 if (!Unit && !ErrUnit)
3570 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003571
Guy Benyei11169dd2012-12-18 14:30:41 +00003572 if (NumErrors != Diags->getClient()->getNumErrors()) {
3573 // Make sure to check that 'Unit' is non-NULL.
3574 if (CXXIdx->getDisplayDiagnostics())
3575 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3576 }
3577
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003578 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3579 return CXError_ASTReadError;
3580
David Blaikieea4395e2017-01-06 19:49:01 +00003581 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003582 if (CXTranslationUnitImpl *TU = *out_TU) {
3583 TU->ParsingOptions = options;
3584 TU->Arguments.reserve(Args->size());
3585 for (const char *Arg : *Args)
3586 TU->Arguments.push_back(Arg);
3587 return CXError_Success;
3588 }
3589 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003590}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003591
3592CXTranslationUnit
3593clang_parseTranslationUnit(CXIndex CIdx,
3594 const char *source_filename,
3595 const char *const *command_line_args,
3596 int num_command_line_args,
3597 struct CXUnsavedFile *unsaved_files,
3598 unsigned num_unsaved_files,
3599 unsigned options) {
3600 CXTranslationUnit TU;
3601 enum CXErrorCode Result = clang_parseTranslationUnit2(
3602 CIdx, source_filename, command_line_args, num_command_line_args,
3603 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003604 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003605 assert((TU && Result == CXError_Success) ||
3606 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003607 return TU;
3608}
3609
3610enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003611 CXIndex CIdx, const char *source_filename,
3612 const char *const *command_line_args, int num_command_line_args,
3613 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3614 unsigned options, CXTranslationUnit *out_TU) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003615 noteBottomOfStack();
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003616 SmallVector<const char *, 4> Args;
3617 Args.push_back("clang");
3618 Args.append(command_line_args, command_line_args + num_command_line_args);
3619 return clang_parseTranslationUnit2FullArgv(
3620 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3621 num_unsaved_files, options, out_TU);
3622}
3623
3624enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3625 CXIndex CIdx, const char *source_filename,
3626 const char *const *command_line_args, int num_command_line_args,
3627 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3628 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003629 LOG_FUNC_SECTION {
3630 *Log << source_filename << ": ";
3631 for (int i = 0; i != num_command_line_args; ++i)
3632 *Log << command_line_args[i] << " ";
3633 }
3634
Alp Toker9d85b182014-07-07 01:23:14 +00003635 if (num_unsaved_files && !unsaved_files)
3636 return CXError_InvalidArguments;
3637
Alp Toker5c532982014-07-07 22:42:03 +00003638 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003639 auto ParseTranslationUnitImpl = [=, &result] {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003640 noteBottomOfStack();
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003641 result = clang_parseTranslationUnit_Impl(
3642 CIdx, source_filename, command_line_args, num_command_line_args,
3643 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3644 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003645
Guy Benyei11169dd2012-12-18 14:30:41 +00003646 llvm::CrashRecoveryContext CRC;
3647
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003648 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3650 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3651 fprintf(stderr, " 'command_line_args' : [");
3652 for (int i = 0; i != num_command_line_args; ++i) {
3653 if (i)
3654 fprintf(stderr, ", ");
3655 fprintf(stderr, "'%s'", command_line_args[i]);
3656 }
3657 fprintf(stderr, "],\n");
3658 fprintf(stderr, " 'unsaved_files' : [");
3659 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3660 if (i)
3661 fprintf(stderr, ", ");
3662 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3663 unsaved_files[i].Length);
3664 }
3665 fprintf(stderr, "],\n");
3666 fprintf(stderr, " 'options' : %d,\n", options);
3667 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003668
3669 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003670 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003671 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003672 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 }
Alp Toker5c532982014-07-07 22:42:03 +00003674
3675 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003676}
3677
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003678CXString clang_Type_getObjCEncoding(CXType CT) {
3679 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3680 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3681 std::string encoding;
3682 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3683 encoding);
3684
3685 return cxstring::createDup(encoding);
3686}
3687
3688static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3689 if (C.kind == CXCursor_MacroDefinition) {
3690 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3691 return MDR->getName();
3692 } else if (C.kind == CXCursor_MacroExpansion) {
3693 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3694 return ME.getName();
3695 }
3696 return nullptr;
3697}
3698
3699unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3700 const IdentifierInfo *II = getMacroIdentifier(C);
3701 if (!II) {
3702 return false;
3703 }
3704 ASTUnit *ASTU = getCursorASTUnit(C);
3705 Preprocessor &PP = ASTU->getPreprocessor();
3706 if (const MacroInfo *MI = PP.getMacroInfo(II))
3707 return MI->isFunctionLike();
3708 return false;
3709}
3710
3711unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3712 const IdentifierInfo *II = getMacroIdentifier(C);
3713 if (!II) {
3714 return false;
3715 }
3716 ASTUnit *ASTU = getCursorASTUnit(C);
3717 Preprocessor &PP = ASTU->getPreprocessor();
3718 if (const MacroInfo *MI = PP.getMacroInfo(II))
3719 return MI->isBuiltinMacro();
3720 return false;
3721}
3722
3723unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3724 const Decl *D = getCursorDecl(C);
3725 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3726 if (!FD) {
3727 return false;
3728 }
3729 return FD->isInlined();
3730}
3731
3732static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3733 if (callExpr->getNumArgs() != 1) {
3734 return nullptr;
3735 }
3736
3737 StringLiteral *S = nullptr;
3738 auto *arg = callExpr->getArg(0);
3739 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3740 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3741 auto *subExpr = I->getSubExprAsWritten();
3742
3743 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3744 return nullptr;
3745 }
3746
3747 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3748 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3749 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3750 } else {
3751 return nullptr;
3752 }
3753 return S;
3754}
3755
David Blaikie59272572016-04-13 18:23:33 +00003756struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003757 CXEvalResultKind EvalType;
3758 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003759 unsigned long long unsignedVal;
3760 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003761 double floatVal;
3762 char *stringVal;
3763 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003764 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003765 ~ExprEvalResult() {
3766 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3767 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003768 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003769 }
3770 }
3771};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003772
3773void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003774 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003775}
3776
3777CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3778 if (!E) {
3779 return CXEval_UnExposed;
3780 }
3781 return ((ExprEvalResult *)E)->EvalType;
3782}
3783
3784int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003785 return clang_EvalResult_getAsLongLong(E);
3786}
3787
3788long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003789 if (!E) {
3790 return 0;
3791 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003792 ExprEvalResult *Result = (ExprEvalResult*)E;
3793 if (Result->IsUnsignedInt)
3794 return Result->EvalData.unsignedVal;
3795 return Result->EvalData.intVal;
3796}
3797
3798unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3799 return ((ExprEvalResult *)E)->IsUnsignedInt;
3800}
3801
3802unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3803 if (!E) {
3804 return 0;
3805 }
3806
3807 ExprEvalResult *Result = (ExprEvalResult*)E;
3808 if (Result->IsUnsignedInt)
3809 return Result->EvalData.unsignedVal;
3810 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003811}
3812
3813double clang_EvalResult_getAsDouble(CXEvalResult E) {
3814 if (!E) {
3815 return 0;
3816 }
3817 return ((ExprEvalResult *)E)->EvalData.floatVal;
3818}
3819
3820const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3821 if (!E) {
3822 return nullptr;
3823 }
3824 return ((ExprEvalResult *)E)->EvalData.stringVal;
3825}
3826
3827static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3828 Expr::EvalResult ER;
3829 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003830 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003831 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003832
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003833 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003834 if (expr->isValueDependent())
3835 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003836 if (!expr->EvaluateAsRValue(ER, ctx))
3837 return nullptr;
3838
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003839 QualType rettype;
3840 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003841 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003842 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003843 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003844
David Blaikiebbc00882016-04-13 18:36:19 +00003845 if (ER.Val.isInt()) {
3846 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003847
3848 auto& val = ER.Val.getInt();
3849 if (val.isUnsigned()) {
3850 result->IsUnsignedInt = true;
3851 result->EvalData.unsignedVal = val.getZExtValue();
3852 } else {
3853 result->EvalData.intVal = val.getExtValue();
3854 }
3855
David Blaikiebbc00882016-04-13 18:36:19 +00003856 return result.release();
3857 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003858
David Blaikiebbc00882016-04-13 18:36:19 +00003859 if (ER.Val.isFloat()) {
3860 llvm::SmallVector<char, 100> Buffer;
3861 ER.Val.getFloat().toString(Buffer);
3862 std::string floatStr(Buffer.data(), Buffer.size());
3863 result->EvalType = CXEval_Float;
3864 bool ignored;
3865 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003866 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003867 llvm::APFloat::rmNearestTiesToEven, &ignored);
3868 result->EvalData.floatVal = apFloat.convertToDouble();
3869 return result.release();
3870 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003871
David Blaikiebbc00882016-04-13 18:36:19 +00003872 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3873 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3874 auto *subExpr = I->getSubExprAsWritten();
3875 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3876 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003877 const StringLiteral *StrE = nullptr;
3878 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003879 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003880
3881 if (ObjCExpr) {
3882 StrE = ObjCExpr->getString();
3883 result->EvalType = CXEval_ObjCStrLiteral;
3884 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003885 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003886 result->EvalType = CXEval_StrLiteral;
3887 }
3888
3889 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003890 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003891 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3892 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003893 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003894 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003895 }
3896 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3897 expr->getStmtClass() == Stmt::StringLiteralClass) {
3898 const StringLiteral *StrE = nullptr;
3899 const ObjCStringLiteral *ObjCExpr;
3900 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003901
David Blaikiebbc00882016-04-13 18:36:19 +00003902 if (ObjCExpr) {
3903 StrE = ObjCExpr->getString();
3904 result->EvalType = CXEval_ObjCStrLiteral;
3905 } else {
3906 StrE = cast<StringLiteral>(expr);
3907 result->EvalType = CXEval_StrLiteral;
3908 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003909
David Blaikiebbc00882016-04-13 18:36:19 +00003910 std::string strRef(StrE->getString().str());
3911 result->EvalData.stringVal = new char[strRef.size() + 1];
3912 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3913 result->EvalData.stringVal[strRef.size()] = '\0';
3914 return result.release();
3915 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003916
David Blaikiebbc00882016-04-13 18:36:19 +00003917 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3918 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003919
David Blaikiebbc00882016-04-13 18:36:19 +00003920 rettype = CC->getType();
3921 if (rettype.getAsString() == "CFStringRef" &&
3922 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003923
David Blaikiebbc00882016-04-13 18:36:19 +00003924 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3925 StringLiteral *S = getCFSTR_value(callExpr);
3926 if (S) {
3927 std::string strLiteral(S->getString().str());
3928 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003929
David Blaikiebbc00882016-04-13 18:36:19 +00003930 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3931 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3932 strLiteral.size());
3933 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003934 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003935 }
3936 }
3937
David Blaikiebbc00882016-04-13 18:36:19 +00003938 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3939 callExpr = static_cast<CallExpr *>(expr);
3940 rettype = callExpr->getCallReturnType(ctx);
3941
3942 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3943 return nullptr;
3944
3945 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3946 if (callExpr->getNumArgs() == 1 &&
3947 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3948 return nullptr;
3949 } else if (rettype.getAsString() == "CFStringRef") {
3950
3951 StringLiteral *S = getCFSTR_value(callExpr);
3952 if (S) {
3953 std::string strLiteral(S->getString().str());
3954 result->EvalType = CXEval_CFStr;
3955 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3956 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3957 strLiteral.size());
3958 result->EvalData.stringVal[strLiteral.size()] = '\0';
3959 return result.release();
3960 }
3961 }
3962 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3963 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3964 ValueDecl *V = D->getDecl();
3965 if (V->getKind() == Decl::Function) {
3966 std::string strName = V->getNameAsString();
3967 result->EvalType = CXEval_Other;
3968 result->EvalData.stringVal = new char[strName.size() + 1];
3969 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3970 result->EvalData.stringVal[strName.size()] = '\0';
3971 return result.release();
3972 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003973 }
3974
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003975 return nullptr;
3976}
3977
Alex Lorenz65317e12019-01-08 22:32:51 +00003978static const Expr *evaluateDeclExpr(const Decl *D) {
3979 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003980 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003981 if (auto *Var = dyn_cast<VarDecl>(D))
3982 return Var->getInit();
3983 else if (auto *Field = dyn_cast<FieldDecl>(D))
3984 return Field->getInClassInitializer();
3985 return nullptr;
3986}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003987
Alex Lorenz65317e12019-01-08 22:32:51 +00003988static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3989 assert(CS && "invalid compound statement");
3990 for (auto *bodyIterator : CS->body()) {
3991 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3992 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003993 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003994 return nullptr;
3995}
3996
Alex Lorenz65317e12019-01-08 22:32:51 +00003997CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3998 if (const Expr *E =
3999 clang_getCursorKind(C) == CXCursor_CompoundStmt
4000 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
4001 : evaluateDeclExpr(getCursorDecl(C)))
4002 return const_cast<CXEvalResult>(
4003 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4004 return nullptr;
4005}
4006
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004007unsigned clang_Cursor_hasAttrs(CXCursor C) {
4008 const Decl *D = getCursorDecl(C);
4009 if (!D) {
4010 return 0;
4011 }
4012
4013 if (D->hasAttrs()) {
4014 return 1;
4015 }
4016
4017 return 0;
4018}
Guy Benyei11169dd2012-12-18 14:30:41 +00004019unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4020 return CXSaveTranslationUnit_None;
4021}
4022
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004023static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4024 const char *FileName,
4025 unsigned options) {
4026 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004027 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4028 setThreadBackgroundPriority();
4029
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004030 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4031 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004032}
4033
4034int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4035 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004036 LOG_FUNC_SECTION {
4037 *Log << TU << ' ' << FileName;
4038 }
4039
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004040 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004041 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004043 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004044
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004045 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4047 if (!CXXUnit->hasSema())
4048 return CXSaveError_InvalidTU;
4049
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004050 CXSaveError result;
4051 auto SaveTranslationUnitImpl = [=, &result]() {
4052 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4053 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004054
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004055 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004056 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004057
4058 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4059 PrintLibclangResourceUsage(TU);
4060
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004061 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 }
4063
4064 // We have an AST that has invalid nodes due to compiler errors.
4065 // Use a crash recovery thread for protection.
4066
4067 llvm::CrashRecoveryContext CRC;
4068
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004069 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4071 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4072 fprintf(stderr, " 'options' : %d,\n", options);
4073 fprintf(stderr, "}\n");
4074
4075 return CXSaveError_Unknown;
4076
4077 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4078 PrintLibclangResourceUsage(TU);
4079 }
4080
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004081 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004082}
4083
4084void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4085 if (CTUnit) {
4086 // If the translation unit has been marked as unsafe to free, just discard
4087 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004088 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4089 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 return;
4091
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004092 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004093 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4095 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004096 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 delete CTUnit;
4098 }
4099}
4100
Erik Verbruggen346066b2017-05-30 14:25:54 +00004101unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4102 if (CTUnit) {
4103 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4104
4105 if (Unit && Unit->isUnsafeToFree())
4106 return false;
4107
4108 Unit->ResetForParse();
4109 return true;
4110 }
4111
4112 return false;
4113}
4114
Guy Benyei11169dd2012-12-18 14:30:41 +00004115unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4116 return CXReparse_None;
4117}
4118
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004119static CXErrorCode
4120clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4121 ArrayRef<CXUnsavedFile> unsaved_files,
4122 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004123 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004124 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004125 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004126 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004127 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004128
4129 // Reset the associated diagnostics.
4130 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004131 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004132
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004133 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4135 setThreadBackgroundPriority();
4136
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004137 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004138 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004139
4140 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4141 new std::vector<ASTUnit::RemappedFile>());
4142
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 // Recover resources if we crash before exiting this function.
4144 llvm::CrashRecoveryContextCleanupRegistrar<
4145 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004146
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004147 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004148 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004149 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004150 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004152
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004153 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4154 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004155 return CXError_Success;
4156 if (isASTReadError(CXXUnit))
4157 return CXError_ASTReadError;
4158 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004159}
4160
4161int clang_reparseTranslationUnit(CXTranslationUnit TU,
4162 unsigned num_unsaved_files,
4163 struct CXUnsavedFile *unsaved_files,
4164 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004165 LOG_FUNC_SECTION {
4166 *Log << TU;
4167 }
4168
Alp Toker9d85b182014-07-07 01:23:14 +00004169 if (num_unsaved_files && !unsaved_files)
4170 return CXError_InvalidArguments;
4171
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004172 CXErrorCode result;
4173 auto ReparseTranslationUnitImpl = [=, &result]() {
4174 result = clang_reparseTranslationUnit_Impl(
4175 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4176 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004177
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 llvm::CrashRecoveryContext CRC;
4179
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004180 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004181 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004182 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004183 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4185 PrintLibclangResourceUsage(TU);
4186
Alp Toker5c532982014-07-07 22:42:03 +00004187 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004188}
4189
4190
4191CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004192 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004193 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004194 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004195 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004196
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004197 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004198 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004199}
4200
4201CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004202 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004203 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004204 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004205 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004206
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004207 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4209}
4210
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004211CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4212 if (isNotUsableTU(CTUnit)) {
4213 LOG_BAD_TU(CTUnit);
4214 return nullptr;
4215 }
4216
4217 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4218 impl->TranslationUnit = CTUnit;
4219 return impl;
4220}
4221
4222CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4223 if (!TargetInfo)
4224 return cxstring::createEmpty();
4225
4226 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4227 assert(!isNotUsableTU(CTUnit) &&
4228 "Unexpected unusable translation unit in TargetInfo");
4229
4230 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4231 std::string Triple =
4232 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4233 return cxstring::createDup(Triple);
4234}
4235
4236int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4237 if (!TargetInfo)
4238 return -1;
4239
4240 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4241 assert(!isNotUsableTU(CTUnit) &&
4242 "Unexpected unusable translation unit in TargetInfo");
4243
4244 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4245 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4246}
4247
4248void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4249 if (!TargetInfo)
4250 return;
4251
4252 delete TargetInfo;
4253}
4254
Guy Benyei11169dd2012-12-18 14:30:41 +00004255//===----------------------------------------------------------------------===//
4256// CXFile Operations.
4257//===----------------------------------------------------------------------===//
4258
Guy Benyei11169dd2012-12-18 14:30:41 +00004259CXString clang_getFileName(CXFile SFile) {
4260 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004261 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004262
4263 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004264 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004265}
4266
4267time_t clang_getFileTime(CXFile SFile) {
4268 if (!SFile)
4269 return 0;
4270
4271 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4272 return FEnt->getModificationTime();
4273}
4274
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004275CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004276 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004277 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004278 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004279 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004280
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004281 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004282
4283 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004284 auto File = FMgr.getFile(file_name);
4285 if (!File)
4286 return nullptr;
4287 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004288}
4289
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004290const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4291 size_t *size) {
4292 if (isNotUsableTU(TU)) {
4293 LOG_BAD_TU(TU);
4294 return nullptr;
4295 }
4296
4297 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4298 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4299 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004300 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004301 if (Invalid) {
4302 if (size)
4303 *size = 0;
4304 return nullptr;
4305 }
4306 if (size)
4307 *size = buf->getBufferSize();
4308 return buf->getBufferStart();
4309}
4310
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004311unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4312 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004313 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004314 LOG_BAD_TU(TU);
4315 return 0;
4316 }
4317
4318 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 return 0;
4320
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004321 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 FileEntry *FEnt = static_cast<FileEntry *>(file);
4323 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4324 .isFileMultipleIncludeGuarded(FEnt);
4325}
4326
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004327int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4328 if (!file || !outID)
4329 return 1;
4330
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004331 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004332 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4333 outID->data[0] = ID.getDevice();
4334 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004335 outID->data[2] = FEnt->getModificationTime();
4336 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004337}
4338
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004339int clang_File_isEqual(CXFile file1, CXFile file2) {
4340 if (file1 == file2)
4341 return true;
4342
4343 if (!file1 || !file2)
4344 return false;
4345
4346 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4347 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4348 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4349}
4350
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004351CXString clang_File_tryGetRealPathName(CXFile SFile) {
4352 if (!SFile)
4353 return cxstring::createNull();
4354
4355 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4356 return cxstring::createRef(FEnt->tryGetRealPathName());
4357}
4358
Guy Benyei11169dd2012-12-18 14:30:41 +00004359//===----------------------------------------------------------------------===//
4360// CXCursor Operations.
4361//===----------------------------------------------------------------------===//
4362
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004363static const Decl *getDeclFromExpr(const Stmt *E) {
4364 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 return getDeclFromExpr(CE->getSubExpr());
4366
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004367 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004369 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004371 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004373 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 if (PRE->isExplicitProperty())
4375 return PRE->getExplicitProperty();
4376 // It could be messaging both getter and setter as in:
4377 // ++myobj.myprop;
4378 // in which case prefer to associate the setter since it is less obvious
4379 // from inspecting the source that the setter is going to get called.
4380 if (PRE->isMessagingSetter())
4381 return PRE->getImplicitPropertySetter();
4382 return PRE->getImplicitPropertyGetter();
4383 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004384 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004386 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 if (Expr *Src = OVE->getSourceExpr())
4388 return getDeclFromExpr(Src);
4389
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004390 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004392 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004393 if (!CE->isElidable())
4394 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004395 if (const CXXInheritedCtorInitExpr *CE =
4396 dyn_cast<CXXInheritedCtorInitExpr>(E))
4397 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004398 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 return OME->getMethodDecl();
4400
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004401 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004403 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4405 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004406 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4408 isa<ParmVarDecl>(SizeOfPack->getPack()))
4409 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004410
4411 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004412}
4413
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004414static SourceLocation getLocationFromExpr(const Expr *E) {
4415 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 return getLocationFromExpr(CE->getSubExpr());
4417
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004418 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004420 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004422 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004424 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004425 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004426 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004428 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004430
4431 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004432}
4433
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004434extern "C" {
4435
Guy Benyei11169dd2012-12-18 14:30:41 +00004436unsigned clang_visitChildren(CXCursor parent,
4437 CXCursorVisitor visitor,
4438 CXClientData client_data) {
4439 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4440 /*VisitPreprocessorLast=*/false);
4441 return CursorVis.VisitChildren(parent);
4442}
4443
4444#ifndef __has_feature
4445#define __has_feature(x) 0
4446#endif
4447#if __has_feature(blocks)
4448typedef enum CXChildVisitResult
4449 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4450
4451static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4452 CXClientData client_data) {
4453 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4454 return block(cursor, parent);
4455}
4456#else
4457// If we are compiled with a compiler that doesn't have native blocks support,
4458// define and call the block manually, so the
4459typedef struct _CXChildVisitResult
4460{
4461 void *isa;
4462 int flags;
4463 int reserved;
4464 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4465 CXCursor);
4466} *CXCursorVisitorBlock;
4467
4468static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4469 CXClientData client_data) {
4470 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4471 return block->invoke(block, cursor, parent);
4472}
4473#endif
4474
4475
4476unsigned clang_visitChildrenWithBlock(CXCursor parent,
4477 CXCursorVisitorBlock block) {
4478 return clang_visitChildren(parent, visitWithBlock, block);
4479}
4480
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004481static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004483 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004484
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004485 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004486 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004487 if (const ObjCPropertyImplDecl *PropImpl =
4488 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004490 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004491
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004492 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004494 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004495
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004496 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 }
4498
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004499 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004500 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004501
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004502 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4504 // and returns different names. NamedDecl returns the class name and
4505 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004506 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004507
4508 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004509 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004510
4511 SmallString<1024> S;
4512 llvm::raw_svector_ostream os(S);
4513 ND->printName(os);
4514
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004515 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004516}
4517
4518CXString clang_getCursorSpelling(CXCursor C) {
4519 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004520 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004521
4522 if (clang_isReference(C.kind)) {
4523 switch (C.kind) {
4524 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004525 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004526 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 }
4528 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004529 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004530 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 }
4532 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004533 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004535 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 }
4537 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004538 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004539 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 }
4541 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004542 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 assert(Type && "Missing type decl");
4544
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004545 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 getAsString());
4547 }
4548 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004549 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 assert(Template && "Missing template decl");
4551
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004552 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 }
4554
4555 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004556 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 assert(NS && "Missing namespace decl");
4558
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004559 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 }
4561
4562 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004563 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 assert(Field && "Missing member decl");
4565
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004566 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 }
4568
4569 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004570 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 assert(Label && "Missing label");
4572
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004573 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 }
4575
4576 case CXCursor_OverloadedDeclRef: {
4577 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004578 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4579 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004580 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004581 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004583 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004584 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 OverloadedTemplateStorage *Ovl
4586 = Storage.get<OverloadedTemplateStorage*>();
4587 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004588 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004589 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 }
4591
4592 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004593 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 assert(Var && "Missing variable decl");
4595
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004596 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 }
4598
4599 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004600 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 }
4602 }
4603
4604 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004605 const Expr *E = getCursorExpr(C);
4606
4607 if (C.kind == CXCursor_ObjCStringLiteral ||
4608 C.kind == CXCursor_StringLiteral) {
4609 const StringLiteral *SLit;
4610 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4611 SLit = OSL->getString();
4612 } else {
4613 SLit = cast<StringLiteral>(E);
4614 }
4615 SmallString<256> Buf;
4616 llvm::raw_svector_ostream OS(Buf);
4617 SLit->outputString(OS);
4618 return cxstring::createDup(OS.str());
4619 }
4620
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004621 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 if (D)
4623 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004624 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 }
4626
4627 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004628 const Stmt *S = getCursorStmt(C);
4629 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004630 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004631
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004632 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 }
4634
4635 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004636 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 ->getNameStart());
4638
4639 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004640 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 ->getNameStart());
4642
4643 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004644 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004645
4646 if (clang_isDeclaration(C.kind))
4647 return getDeclSpelling(getCursorDecl(C));
4648
4649 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004650 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004651 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 }
4653
4654 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004655 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004656 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 }
4658
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004659 if (C.kind == CXCursor_PackedAttr) {
4660 return cxstring::createRef("packed");
4661 }
4662
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004663 if (C.kind == CXCursor_VisibilityAttr) {
4664 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4665 switch (AA->getVisibility()) {
4666 case VisibilityAttr::VisibilityType::Default:
4667 return cxstring::createRef("default");
4668 case VisibilityAttr::VisibilityType::Hidden:
4669 return cxstring::createRef("hidden");
4670 case VisibilityAttr::VisibilityType::Protected:
4671 return cxstring::createRef("protected");
4672 }
4673 llvm_unreachable("unknown visibility type");
4674 }
4675
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004676 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004677}
4678
4679CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4680 unsigned pieceIndex,
4681 unsigned options) {
4682 if (clang_Cursor_isNull(C))
4683 return clang_getNullRange();
4684
4685 ASTContext &Ctx = getCursorContext(C);
4686
4687 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004688 const Stmt *S = getCursorStmt(C);
4689 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 if (pieceIndex > 0)
4691 return clang_getNullRange();
4692 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4693 }
4694
4695 return clang_getNullRange();
4696 }
4697
4698 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004699 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4701 if (pieceIndex >= ME->getNumSelectorLocs())
4702 return clang_getNullRange();
4703 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4704 }
4705 }
4706
4707 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4708 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004709 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4711 if (pieceIndex >= MD->getNumSelectorLocs())
4712 return clang_getNullRange();
4713 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4714 }
4715 }
4716
4717 if (C.kind == CXCursor_ObjCCategoryDecl ||
4718 C.kind == CXCursor_ObjCCategoryImplDecl) {
4719 if (pieceIndex > 0)
4720 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004721 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004722 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4723 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004724 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4726 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4727 }
4728
4729 if (C.kind == CXCursor_ModuleImportDecl) {
4730 if (pieceIndex > 0)
4731 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004732 if (const ImportDecl *ImportD =
4733 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4735 if (!Locs.empty())
4736 return cxloc::translateSourceRange(Ctx,
4737 SourceRange(Locs.front(), Locs.back()));
4738 }
4739 return clang_getNullRange();
4740 }
4741
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004742 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004743 C.kind == CXCursor_ConversionFunction ||
4744 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004745 if (pieceIndex > 0)
4746 return clang_getNullRange();
4747 if (const FunctionDecl *FD =
4748 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4749 DeclarationNameInfo FunctionName = FD->getNameInfo();
4750 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4751 }
4752 return clang_getNullRange();
4753 }
4754
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 // FIXME: A CXCursor_InclusionDirective should give the location of the
4756 // filename, but we don't keep track of this.
4757
4758 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4759 // but we don't keep track of this.
4760
4761 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4762 // but we don't keep track of this.
4763
4764 // Default handling, give the location of the cursor.
4765
4766 if (pieceIndex > 0)
4767 return clang_getNullRange();
4768
4769 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4770 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4771 return cxloc::translateSourceRange(Ctx, Loc);
4772}
4773
Eli Bendersky44a206f2014-07-31 18:04:56 +00004774CXString clang_Cursor_getMangling(CXCursor C) {
4775 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4776 return cxstring::createEmpty();
4777
Eli Bendersky44a206f2014-07-31 18:04:56 +00004778 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004779 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004780 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4781 return cxstring::createEmpty();
4782
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004783 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004784 ASTNameGenerator ASTNameGen(Ctx);
4785 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004786}
4787
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004788CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4789 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4790 return nullptr;
4791
4792 const Decl *D = getCursorDecl(C);
4793 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4794 return nullptr;
4795
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004796 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004797 ASTNameGenerator ASTNameGen(Ctx);
4798 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004799 return cxstring::createSet(Manglings);
4800}
4801
Dave Lee1a532c92017-09-22 16:58:57 +00004802CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4803 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4804 return nullptr;
4805
4806 const Decl *D = getCursorDecl(C);
4807 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4808 return nullptr;
4809
4810 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004811 ASTNameGenerator ASTNameGen(Ctx);
4812 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004813 return cxstring::createSet(Manglings);
4814}
4815
Jonathan Coe45ef5032018-01-16 10:19:56 +00004816CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4817 if (clang_Cursor_isNull(C))
4818 return 0;
4819 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4820}
4821
4822void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4823 if (Policy)
4824 delete static_cast<PrintingPolicy *>(Policy);
4825}
4826
4827unsigned
4828clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4829 enum CXPrintingPolicyProperty Property) {
4830 if (!Policy)
4831 return 0;
4832
4833 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4834 switch (Property) {
4835 case CXPrintingPolicy_Indentation:
4836 return P->Indentation;
4837 case CXPrintingPolicy_SuppressSpecifiers:
4838 return P->SuppressSpecifiers;
4839 case CXPrintingPolicy_SuppressTagKeyword:
4840 return P->SuppressTagKeyword;
4841 case CXPrintingPolicy_IncludeTagDefinition:
4842 return P->IncludeTagDefinition;
4843 case CXPrintingPolicy_SuppressScope:
4844 return P->SuppressScope;
4845 case CXPrintingPolicy_SuppressUnwrittenScope:
4846 return P->SuppressUnwrittenScope;
4847 case CXPrintingPolicy_SuppressInitializers:
4848 return P->SuppressInitializers;
4849 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4850 return P->ConstantArraySizeAsWritten;
4851 case CXPrintingPolicy_AnonymousTagLocations:
4852 return P->AnonymousTagLocations;
4853 case CXPrintingPolicy_SuppressStrongLifetime:
4854 return P->SuppressStrongLifetime;
4855 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4856 return P->SuppressLifetimeQualifiers;
4857 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4858 return P->SuppressTemplateArgsInCXXConstructors;
4859 case CXPrintingPolicy_Bool:
4860 return P->Bool;
4861 case CXPrintingPolicy_Restrict:
4862 return P->Restrict;
4863 case CXPrintingPolicy_Alignof:
4864 return P->Alignof;
4865 case CXPrintingPolicy_UnderscoreAlignof:
4866 return P->UnderscoreAlignof;
4867 case CXPrintingPolicy_UseVoidForZeroParams:
4868 return P->UseVoidForZeroParams;
4869 case CXPrintingPolicy_TerseOutput:
4870 return P->TerseOutput;
4871 case CXPrintingPolicy_PolishForDeclaration:
4872 return P->PolishForDeclaration;
4873 case CXPrintingPolicy_Half:
4874 return P->Half;
4875 case CXPrintingPolicy_MSWChar:
4876 return P->MSWChar;
4877 case CXPrintingPolicy_IncludeNewlines:
4878 return P->IncludeNewlines;
4879 case CXPrintingPolicy_MSVCFormatting:
4880 return P->MSVCFormatting;
4881 case CXPrintingPolicy_ConstantsAsWritten:
4882 return P->ConstantsAsWritten;
4883 case CXPrintingPolicy_SuppressImplicitBase:
4884 return P->SuppressImplicitBase;
4885 case CXPrintingPolicy_FullyQualifiedName:
4886 return P->FullyQualifiedName;
4887 }
4888
4889 assert(false && "Invalid CXPrintingPolicyProperty");
4890 return 0;
4891}
4892
4893void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4894 enum CXPrintingPolicyProperty Property,
4895 unsigned Value) {
4896 if (!Policy)
4897 return;
4898
4899 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4900 switch (Property) {
4901 case CXPrintingPolicy_Indentation:
4902 P->Indentation = Value;
4903 return;
4904 case CXPrintingPolicy_SuppressSpecifiers:
4905 P->SuppressSpecifiers = Value;
4906 return;
4907 case CXPrintingPolicy_SuppressTagKeyword:
4908 P->SuppressTagKeyword = Value;
4909 return;
4910 case CXPrintingPolicy_IncludeTagDefinition:
4911 P->IncludeTagDefinition = Value;
4912 return;
4913 case CXPrintingPolicy_SuppressScope:
4914 P->SuppressScope = Value;
4915 return;
4916 case CXPrintingPolicy_SuppressUnwrittenScope:
4917 P->SuppressUnwrittenScope = Value;
4918 return;
4919 case CXPrintingPolicy_SuppressInitializers:
4920 P->SuppressInitializers = Value;
4921 return;
4922 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4923 P->ConstantArraySizeAsWritten = Value;
4924 return;
4925 case CXPrintingPolicy_AnonymousTagLocations:
4926 P->AnonymousTagLocations = Value;
4927 return;
4928 case CXPrintingPolicy_SuppressStrongLifetime:
4929 P->SuppressStrongLifetime = Value;
4930 return;
4931 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4932 P->SuppressLifetimeQualifiers = Value;
4933 return;
4934 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4935 P->SuppressTemplateArgsInCXXConstructors = Value;
4936 return;
4937 case CXPrintingPolicy_Bool:
4938 P->Bool = Value;
4939 return;
4940 case CXPrintingPolicy_Restrict:
4941 P->Restrict = Value;
4942 return;
4943 case CXPrintingPolicy_Alignof:
4944 P->Alignof = Value;
4945 return;
4946 case CXPrintingPolicy_UnderscoreAlignof:
4947 P->UnderscoreAlignof = Value;
4948 return;
4949 case CXPrintingPolicy_UseVoidForZeroParams:
4950 P->UseVoidForZeroParams = Value;
4951 return;
4952 case CXPrintingPolicy_TerseOutput:
4953 P->TerseOutput = Value;
4954 return;
4955 case CXPrintingPolicy_PolishForDeclaration:
4956 P->PolishForDeclaration = Value;
4957 return;
4958 case CXPrintingPolicy_Half:
4959 P->Half = Value;
4960 return;
4961 case CXPrintingPolicy_MSWChar:
4962 P->MSWChar = Value;
4963 return;
4964 case CXPrintingPolicy_IncludeNewlines:
4965 P->IncludeNewlines = Value;
4966 return;
4967 case CXPrintingPolicy_MSVCFormatting:
4968 P->MSVCFormatting = Value;
4969 return;
4970 case CXPrintingPolicy_ConstantsAsWritten:
4971 P->ConstantsAsWritten = Value;
4972 return;
4973 case CXPrintingPolicy_SuppressImplicitBase:
4974 P->SuppressImplicitBase = Value;
4975 return;
4976 case CXPrintingPolicy_FullyQualifiedName:
4977 P->FullyQualifiedName = Value;
4978 return;
4979 }
4980
4981 assert(false && "Invalid CXPrintingPolicyProperty");
4982}
4983
4984CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4985 if (clang_Cursor_isNull(C))
4986 return cxstring::createEmpty();
4987
4988 if (clang_isDeclaration(C.kind)) {
4989 const Decl *D = getCursorDecl(C);
4990 if (!D)
4991 return cxstring::createEmpty();
4992
4993 SmallString<128> Str;
4994 llvm::raw_svector_ostream OS(Str);
4995 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4996 D->print(OS, UserPolicy ? *UserPolicy
4997 : getCursorContext(C).getPrintingPolicy());
4998
4999 return cxstring::createDup(OS.str());
5000 }
5001
5002 return cxstring::createEmpty();
5003}
5004
Guy Benyei11169dd2012-12-18 14:30:41 +00005005CXString clang_getCursorDisplayName(CXCursor C) {
5006 if (!clang_isDeclaration(C.kind))
5007 return clang_getCursorSpelling(C);
5008
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005009 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005011 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005012
5013 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005014 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 D = FunTmpl->getTemplatedDecl();
5016
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005017 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 SmallString<64> Str;
5019 llvm::raw_svector_ostream OS(Str);
5020 OS << *Function;
5021 if (Function->getPrimaryTemplate())
5022 OS << "<>";
5023 OS << "(";
5024 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5025 if (I)
5026 OS << ", ";
5027 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5028 }
5029
5030 if (Function->isVariadic()) {
5031 if (Function->getNumParams())
5032 OS << ", ";
5033 OS << "...";
5034 }
5035 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005036 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 }
5038
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005039 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 SmallString<64> Str;
5041 llvm::raw_svector_ostream OS(Str);
5042 OS << *ClassTemplate;
5043 OS << "<";
5044 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5045 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5046 if (I)
5047 OS << ", ";
5048
5049 NamedDecl *Param = Params->getParam(I);
5050 if (Param->getIdentifier()) {
5051 OS << Param->getIdentifier()->getName();
5052 continue;
5053 }
5054
5055 // There is no parameter name, which makes this tricky. Try to come up
5056 // with something useful that isn't too long.
5057 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Saar Razff1e0fc2020-01-15 02:48:42 +02005058 if (const auto *TC = TTP->getTypeConstraint()) {
5059 TC->getConceptNameInfo().printName(OS, Policy);
5060 if (TC->hasExplicitTemplateArgs())
5061 OS << "<...>";
5062 } else
5063 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 else if (NonTypeTemplateParmDecl *NTTP
5065 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5066 OS << NTTP->getType().getAsString(Policy);
5067 else
5068 OS << "template<...> class";
5069 }
5070
5071 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005072 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 }
5074
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005075 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5077 // If the type was explicitly written, use that.
5078 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005079 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005080
Benjamin Kramer9170e912013-02-22 15:46:01 +00005081 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 llvm::raw_svector_ostream OS(Str);
5083 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005084 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5085 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005086 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 }
5088
5089 return clang_getCursorSpelling(C);
5090}
5091
5092CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5093 switch (Kind) {
5094 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005097 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005101 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005158 case CXCursor_FixedPointLiteral:
5159 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005174 case CXCursor_OMPArraySectionExpr:
5175 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005226 case CXCursor_ObjCAvailabilityCheckExpr:
5227 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005228 case CXCursor_ObjCSelfExpr:
5229 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005256 case CXCursor_BuiltinBitCastExpr:
5257 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005265 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005277 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005297 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005307 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005309 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005311 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005313 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005315 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005317 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005319 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005320 case CXCursor_SEHLeaveStmt:
5321 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005323 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005325 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005327 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005328 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005329 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005330 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005331 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005333 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005335 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005337 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005338 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005339 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005340 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005341 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005343 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005345 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005347 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005349 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005350 case CXCursor_PackedAttr:
5351 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005352 case CXCursor_PureAttr:
5353 return cxstring::createRef("attribute(pure)");
5354 case CXCursor_ConstAttr:
5355 return cxstring::createRef("attribute(const)");
5356 case CXCursor_NoDuplicateAttr:
5357 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005358 case CXCursor_CUDAConstantAttr:
5359 return cxstring::createRef("attribute(constant)");
5360 case CXCursor_CUDADeviceAttr:
5361 return cxstring::createRef("attribute(device)");
5362 case CXCursor_CUDAGlobalAttr:
5363 return cxstring::createRef("attribute(global)");
5364 case CXCursor_CUDAHostAttr:
5365 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005366 case CXCursor_CUDASharedAttr:
5367 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005368 case CXCursor_VisibilityAttr:
5369 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005370 case CXCursor_DLLExport:
5371 return cxstring::createRef("attribute(dllexport)");
5372 case CXCursor_DLLImport:
5373 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005374 case CXCursor_NSReturnsRetained:
5375 return cxstring::createRef("attribute(ns_returns_retained)");
5376 case CXCursor_NSReturnsNotRetained:
5377 return cxstring::createRef("attribute(ns_returns_not_retained)");
5378 case CXCursor_NSReturnsAutoreleased:
5379 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5380 case CXCursor_NSConsumesSelf:
5381 return cxstring::createRef("attribute(ns_consumes_self)");
5382 case CXCursor_NSConsumed:
5383 return cxstring::createRef("attribute(ns_consumed)");
5384 case CXCursor_ObjCException:
5385 return cxstring::createRef("attribute(objc_exception)");
5386 case CXCursor_ObjCNSObject:
5387 return cxstring::createRef("attribute(NSObject)");
5388 case CXCursor_ObjCIndependentClass:
5389 return cxstring::createRef("attribute(objc_independent_class)");
5390 case CXCursor_ObjCPreciseLifetime:
5391 return cxstring::createRef("attribute(objc_precise_lifetime)");
5392 case CXCursor_ObjCReturnsInnerPointer:
5393 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5394 case CXCursor_ObjCRequiresSuper:
5395 return cxstring::createRef("attribute(objc_requires_super)");
5396 case CXCursor_ObjCRootClass:
5397 return cxstring::createRef("attribute(objc_root_class)");
5398 case CXCursor_ObjCSubclassingRestricted:
5399 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5400 case CXCursor_ObjCExplicitProtocolImpl:
5401 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5402 case CXCursor_ObjCDesignatedInitializer:
5403 return cxstring::createRef("attribute(objc_designated_initializer)");
5404 case CXCursor_ObjCRuntimeVisible:
5405 return cxstring::createRef("attribute(objc_runtime_visible)");
5406 case CXCursor_ObjCBoxable:
5407 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005408 case CXCursor_FlagEnum:
5409 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005410 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005411 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005412 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005413 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005414 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005415 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005416 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005417 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005418 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005419 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005420 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005421 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005422 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005423 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005425 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005426 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005427 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005428 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005429 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005431 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005432 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005433 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005434 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005435 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005436 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005437 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005438 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005439 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005441 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005442 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005443 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005444 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005445 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005446 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005447 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005448 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005449 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005451 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005453 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005454 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005455 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005457 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005458 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005459 return cxstring::createRef("OMPParallelDirective");
5460 case CXCursor_OMPSimdDirective:
5461 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005462 case CXCursor_OMPForDirective:
5463 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005464 case CXCursor_OMPForSimdDirective:
5465 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005466 case CXCursor_OMPSectionsDirective:
5467 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005468 case CXCursor_OMPSectionDirective:
5469 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005470 case CXCursor_OMPSingleDirective:
5471 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005472 case CXCursor_OMPMasterDirective:
5473 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005474 case CXCursor_OMPCriticalDirective:
5475 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005476 case CXCursor_OMPParallelForDirective:
5477 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005478 case CXCursor_OMPParallelForSimdDirective:
5479 return cxstring::createRef("OMPParallelForSimdDirective");
cchen47d60942019-12-05 13:43:48 -05005480 case CXCursor_OMPParallelMasterDirective:
5481 return cxstring::createRef("OMPParallelMasterDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005482 case CXCursor_OMPParallelSectionsDirective:
5483 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005484 case CXCursor_OMPTaskDirective:
5485 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005486 case CXCursor_OMPTaskyieldDirective:
5487 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005488 case CXCursor_OMPBarrierDirective:
5489 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005490 case CXCursor_OMPTaskwaitDirective:
5491 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005492 case CXCursor_OMPTaskgroupDirective:
5493 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005494 case CXCursor_OMPFlushDirective:
5495 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005496 case CXCursor_OMPOrderedDirective:
5497 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005498 case CXCursor_OMPAtomicDirective:
5499 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005500 case CXCursor_OMPTargetDirective:
5501 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005502 case CXCursor_OMPTargetDataDirective:
5503 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005504 case CXCursor_OMPTargetEnterDataDirective:
5505 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005506 case CXCursor_OMPTargetExitDataDirective:
5507 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005508 case CXCursor_OMPTargetParallelDirective:
5509 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005510 case CXCursor_OMPTargetParallelForDirective:
5511 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005512 case CXCursor_OMPTargetUpdateDirective:
5513 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005514 case CXCursor_OMPTeamsDirective:
5515 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005516 case CXCursor_OMPCancellationPointDirective:
5517 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005518 case CXCursor_OMPCancelDirective:
5519 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005520 case CXCursor_OMPTaskLoopDirective:
5521 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005522 case CXCursor_OMPTaskLoopSimdDirective:
5523 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005524 case CXCursor_OMPMasterTaskLoopDirective:
5525 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005526 case CXCursor_OMPMasterTaskLoopSimdDirective:
5527 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005528 case CXCursor_OMPParallelMasterTaskLoopDirective:
5529 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Alexey Bataev14a388f2019-10-25 10:27:13 -04005530 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5531 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005532 case CXCursor_OMPDistributeDirective:
5533 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005534 case CXCursor_OMPDistributeParallelForDirective:
5535 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005536 case CXCursor_OMPDistributeParallelForSimdDirective:
5537 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005538 case CXCursor_OMPDistributeSimdDirective:
5539 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005540 case CXCursor_OMPTargetParallelForSimdDirective:
5541 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005542 case CXCursor_OMPTargetSimdDirective:
5543 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005544 case CXCursor_OMPTeamsDistributeDirective:
5545 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005546 case CXCursor_OMPTeamsDistributeSimdDirective:
5547 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005548 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5549 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005550 case CXCursor_OMPTeamsDistributeParallelForDirective:
5551 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005552 case CXCursor_OMPTargetTeamsDirective:
5553 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005554 case CXCursor_OMPTargetTeamsDistributeDirective:
5555 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005556 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5557 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005558 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5559 return cxstring::createRef(
5560 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005561 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5562 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005563 case CXCursor_OverloadCandidate:
5564 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005565 case CXCursor_TypeAliasTemplateDecl:
5566 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005567 case CXCursor_StaticAssert:
5568 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005569 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005570 return cxstring::createRef("FriendDecl");
5571 case CXCursor_ConvergentAttr:
5572 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005573 case CXCursor_WarnUnusedAttr:
5574 return cxstring::createRef("attribute(warn_unused)");
5575 case CXCursor_WarnUnusedResultAttr:
5576 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005577 case CXCursor_AlignedAttr:
5578 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005579 }
5580
5581 llvm_unreachable("Unhandled CXCursorKind");
5582}
5583
5584struct GetCursorData {
5585 SourceLocation TokenBeginLoc;
5586 bool PointsAtMacroArgExpansion;
5587 bool VisitedObjCPropertyImplDecl;
5588 SourceLocation VisitedDeclaratorDeclStartLoc;
5589 CXCursor &BestCursor;
5590
5591 GetCursorData(SourceManager &SM,
5592 SourceLocation tokenBegin, CXCursor &outputCursor)
5593 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5594 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5595 VisitedObjCPropertyImplDecl = false;
5596 }
5597};
5598
5599static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5600 CXCursor parent,
5601 CXClientData client_data) {
5602 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5603 CXCursor *BestCursor = &Data->BestCursor;
5604
5605 // If we point inside a macro argument we should provide info of what the
5606 // token is so use the actual cursor, don't replace it with a macro expansion
5607 // cursor.
5608 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5609 return CXChildVisit_Recurse;
5610
5611 if (clang_isDeclaration(cursor.kind)) {
5612 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005613 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005614 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5615 if (MD->isImplicit())
5616 return CXChildVisit_Break;
5617
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005618 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005619 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5620 // Check that when we have multiple @class references in the same line,
5621 // that later ones do not override the previous ones.
5622 // If we have:
5623 // @class Foo, Bar;
5624 // source ranges for both start at '@', so 'Bar' will end up overriding
5625 // 'Foo' even though the cursor location was at 'Foo'.
5626 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5627 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005628 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5630 if (PrevID != ID &&
5631 !PrevID->isThisDeclarationADefinition() &&
5632 !ID->isThisDeclarationADefinition())
5633 return CXChildVisit_Break;
5634 }
5635
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005636 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005637 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5638 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5639 // Check that when we have multiple declarators in the same line,
5640 // that later ones do not override the previous ones.
5641 // If we have:
5642 // int Foo, Bar;
5643 // source ranges for both start at 'int', so 'Bar' will end up overriding
5644 // 'Foo' even though the cursor location was at 'Foo'.
5645 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5646 return CXChildVisit_Break;
5647 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5648
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005649 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005650 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5651 (void)PropImp;
5652 // Check that when we have multiple @synthesize in the same line,
5653 // that later ones do not override the previous ones.
5654 // If we have:
5655 // @synthesize Foo, Bar;
5656 // source ranges for both start at '@', so 'Bar' will end up overriding
5657 // 'Foo' even though the cursor location was at 'Foo'.
5658 if (Data->VisitedObjCPropertyImplDecl)
5659 return CXChildVisit_Break;
5660 Data->VisitedObjCPropertyImplDecl = true;
5661 }
5662 }
5663
5664 if (clang_isExpression(cursor.kind) &&
5665 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005666 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005667 // Avoid having the cursor of an expression replace the declaration cursor
5668 // when the expression source range overlaps the declaration range.
5669 // This can happen for C++ constructor expressions whose range generally
5670 // include the variable declaration, e.g.:
5671 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5672 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5673 D->getLocation() == Data->TokenBeginLoc)
5674 return CXChildVisit_Break;
5675 }
5676 }
5677
5678 // If our current best cursor is the construction of a temporary object,
5679 // don't replace that cursor with a type reference, because we want
5680 // clang_getCursor() to point at the constructor.
5681 if (clang_isExpression(BestCursor->kind) &&
5682 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5683 cursor.kind == CXCursor_TypeRef) {
5684 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5685 // as having the actual point on the type reference.
5686 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5687 return CXChildVisit_Recurse;
5688 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005689
5690 // If we already have an Objective-C superclass reference, don't
5691 // update it further.
5692 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5693 return CXChildVisit_Break;
5694
Guy Benyei11169dd2012-12-18 14:30:41 +00005695 *BestCursor = cursor;
5696 return CXChildVisit_Recurse;
5697}
5698
5699CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005700 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005701 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005702 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005703 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005704
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005705 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005706 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5707
5708 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5709 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5710
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005711 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 CXFile SearchFile;
5713 unsigned SearchLine, SearchColumn;
5714 CXFile ResultFile;
5715 unsigned ResultLine, ResultColumn;
5716 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5717 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5718 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005719
5720 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5721 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005722 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005723 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005724 SearchFileName = clang_getFileName(SearchFile);
5725 ResultFileName = clang_getFileName(ResultFile);
5726 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5727 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005728 *Log << llvm::format("(%s:%d:%d) = %s",
5729 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5730 clang_getCString(KindSpelling))
5731 << llvm::format("(%s:%d:%d):%s%s",
5732 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5733 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 clang_disposeString(SearchFileName);
5735 clang_disposeString(ResultFileName);
5736 clang_disposeString(KindSpelling);
5737 clang_disposeString(USR);
5738
5739 CXCursor Definition = clang_getCursorDefinition(Result);
5740 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5741 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5742 CXString DefinitionKindSpelling
5743 = clang_getCursorKindSpelling(Definition.kind);
5744 CXFile DefinitionFile;
5745 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005746 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005747 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005748 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005749 *Log << llvm::format(" -> %s(%s:%d:%d)",
5750 clang_getCString(DefinitionKindSpelling),
5751 clang_getCString(DefinitionFileName),
5752 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005753 clang_disposeString(DefinitionFileName);
5754 clang_disposeString(DefinitionKindSpelling);
5755 }
5756 }
5757
5758 return Result;
5759}
5760
5761CXCursor clang_getNullCursor(void) {
5762 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5763}
5764
5765unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005766 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5767 // can't set consistently. For example, when visiting a DeclStmt we will set
5768 // it but we don't set it on the result of clang_getCursorDefinition for
5769 // a reference of the same declaration.
5770 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5771 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5772 // to provide that kind of info.
5773 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005774 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005775 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005776 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005777
Guy Benyei11169dd2012-12-18 14:30:41 +00005778 return X == Y;
5779}
5780
5781unsigned clang_hashCursor(CXCursor C) {
5782 unsigned Index = 0;
5783 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5784 Index = 1;
5785
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005786 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005787 std::make_pair(C.kind, C.data[Index]));
5788}
5789
5790unsigned clang_isInvalid(enum CXCursorKind K) {
5791 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5792}
5793
5794unsigned clang_isDeclaration(enum CXCursorKind K) {
5795 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005796 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5797}
5798
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005799unsigned clang_isInvalidDeclaration(CXCursor C) {
5800 if (clang_isDeclaration(C.kind)) {
5801 if (const Decl *D = getCursorDecl(C))
5802 return D->isInvalidDecl();
5803 }
5804
5805 return 0;
5806}
5807
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005808unsigned clang_isReference(enum CXCursorKind K) {
5809 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5810}
Guy Benyei11169dd2012-12-18 14:30:41 +00005811
5812unsigned clang_isExpression(enum CXCursorKind K) {
5813 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5814}
5815
5816unsigned clang_isStatement(enum CXCursorKind K) {
5817 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5818}
5819
5820unsigned clang_isAttribute(enum CXCursorKind K) {
5821 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5822}
5823
5824unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5825 return K == CXCursor_TranslationUnit;
5826}
5827
5828unsigned clang_isPreprocessing(enum CXCursorKind K) {
5829 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5830}
5831
5832unsigned clang_isUnexposed(enum CXCursorKind K) {
5833 switch (K) {
5834 case CXCursor_UnexposedDecl:
5835 case CXCursor_UnexposedExpr:
5836 case CXCursor_UnexposedStmt:
5837 case CXCursor_UnexposedAttr:
5838 return true;
5839 default:
5840 return false;
5841 }
5842}
5843
5844CXCursorKind clang_getCursorKind(CXCursor C) {
5845 return C.kind;
5846}
5847
5848CXSourceLocation clang_getCursorLocation(CXCursor C) {
5849 if (clang_isReference(C.kind)) {
5850 switch (C.kind) {
5851 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005852 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005853 = getCursorObjCSuperClassRef(C);
5854 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5855 }
5856
5857 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005858 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005859 = getCursorObjCProtocolRef(C);
5860 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5861 }
5862
5863 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005864 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005865 = getCursorObjCClassRef(C);
5866 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5867 }
5868
5869 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005870 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005871 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5872 }
5873
5874 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005875 std::pair<const TemplateDecl *, SourceLocation> P =
5876 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005877 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5878 }
5879
5880 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005881 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005882 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5883 }
5884
5885 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005886 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005887 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5888 }
5889
5890 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005891 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005892 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5893 }
5894
5895 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005896 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005897 if (!BaseSpec)
5898 return clang_getNullLocation();
5899
5900 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5901 return cxloc::translateSourceLocation(getCursorContext(C),
5902 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005903
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005905 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005906 }
5907
5908 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005909 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005910 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5911 }
5912
5913 case CXCursor_OverloadedDeclRef:
5914 return cxloc::translateSourceLocation(getCursorContext(C),
5915 getCursorOverloadedDeclRef(C).second);
5916
5917 default:
5918 // FIXME: Need a way to enumerate all non-reference cases.
5919 llvm_unreachable("Missed a reference kind");
5920 }
5921 }
5922
5923 if (clang_isExpression(C.kind))
5924 return cxloc::translateSourceLocation(getCursorContext(C),
5925 getLocationFromExpr(getCursorExpr(C)));
5926
5927 if (clang_isStatement(C.kind))
5928 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005929 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005930
5931 if (C.kind == CXCursor_PreprocessingDirective) {
5932 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5933 return cxloc::translateSourceLocation(getCursorContext(C), L);
5934 }
5935
5936 if (C.kind == CXCursor_MacroExpansion) {
5937 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005938 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005939 return cxloc::translateSourceLocation(getCursorContext(C), L);
5940 }
5941
5942 if (C.kind == CXCursor_MacroDefinition) {
5943 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5944 return cxloc::translateSourceLocation(getCursorContext(C), L);
5945 }
5946
5947 if (C.kind == CXCursor_InclusionDirective) {
5948 SourceLocation L
5949 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5950 return cxloc::translateSourceLocation(getCursorContext(C), L);
5951 }
5952
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005953 if (clang_isAttribute(C.kind)) {
5954 SourceLocation L
5955 = cxcursor::getCursorAttr(C)->getLocation();
5956 return cxloc::translateSourceLocation(getCursorContext(C), L);
5957 }
5958
Guy Benyei11169dd2012-12-18 14:30:41 +00005959 if (!clang_isDeclaration(C.kind))
5960 return clang_getNullLocation();
5961
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005962 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005963 if (!D)
5964 return clang_getNullLocation();
5965
5966 SourceLocation Loc = D->getLocation();
5967 // FIXME: Multiple variables declared in a single declaration
5968 // currently lack the information needed to correctly determine their
5969 // ranges when accounting for the type-specifier. We use context
5970 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5971 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005972 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005973 if (!cxcursor::isFirstInDeclGroup(C))
5974 Loc = VD->getLocation();
5975 }
5976
5977 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005978 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005979 Loc = MD->getSelectorStartLoc();
5980
5981 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5982}
5983
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005984} // end extern "C"
5985
Guy Benyei11169dd2012-12-18 14:30:41 +00005986CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5987 assert(TU);
5988
5989 // Guard against an invalid SourceLocation, or we may assert in one
5990 // of the following calls.
5991 if (SLoc.isInvalid())
5992 return clang_getNullCursor();
5993
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005994 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005995
5996 // Translate the given source location to make it point at the beginning of
5997 // the token under the cursor.
5998 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5999 CXXUnit->getASTContext().getLangOpts());
6000
6001 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
6002 if (SLoc.isValid()) {
6003 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
6004 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
6005 /*VisitPreprocessorLast=*/true,
6006 /*VisitIncludedEntities=*/false,
6007 SourceLocation(SLoc));
6008 CursorVis.visitFileRegion();
6009 }
6010
6011 return Result;
6012}
6013
6014static SourceRange getRawCursorExtent(CXCursor C) {
6015 if (clang_isReference(C.kind)) {
6016 switch (C.kind) {
6017 case CXCursor_ObjCSuperClassRef:
6018 return getCursorObjCSuperClassRef(C).second;
6019
6020 case CXCursor_ObjCProtocolRef:
6021 return getCursorObjCProtocolRef(C).second;
6022
6023 case CXCursor_ObjCClassRef:
6024 return getCursorObjCClassRef(C).second;
6025
6026 case CXCursor_TypeRef:
6027 return getCursorTypeRef(C).second;
6028
6029 case CXCursor_TemplateRef:
6030 return getCursorTemplateRef(C).second;
6031
6032 case CXCursor_NamespaceRef:
6033 return getCursorNamespaceRef(C).second;
6034
6035 case CXCursor_MemberRef:
6036 return getCursorMemberRef(C).second;
6037
6038 case CXCursor_CXXBaseSpecifier:
6039 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6040
6041 case CXCursor_LabelRef:
6042 return getCursorLabelRef(C).second;
6043
6044 case CXCursor_OverloadedDeclRef:
6045 return getCursorOverloadedDeclRef(C).second;
6046
6047 case CXCursor_VariableRef:
6048 return getCursorVariableRef(C).second;
6049
6050 default:
6051 // FIXME: Need a way to enumerate all non-reference cases.
6052 llvm_unreachable("Missed a reference kind");
6053 }
6054 }
6055
6056 if (clang_isExpression(C.kind))
6057 return getCursorExpr(C)->getSourceRange();
6058
6059 if (clang_isStatement(C.kind))
6060 return getCursorStmt(C)->getSourceRange();
6061
6062 if (clang_isAttribute(C.kind))
6063 return getCursorAttr(C)->getRange();
6064
6065 if (C.kind == CXCursor_PreprocessingDirective)
6066 return cxcursor::getCursorPreprocessingDirective(C);
6067
6068 if (C.kind == CXCursor_MacroExpansion) {
6069 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006070 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006071 return TU->mapRangeFromPreamble(Range);
6072 }
6073
6074 if (C.kind == CXCursor_MacroDefinition) {
6075 ASTUnit *TU = getCursorASTUnit(C);
6076 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6077 return TU->mapRangeFromPreamble(Range);
6078 }
6079
6080 if (C.kind == CXCursor_InclusionDirective) {
6081 ASTUnit *TU = getCursorASTUnit(C);
6082 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6083 return TU->mapRangeFromPreamble(Range);
6084 }
6085
6086 if (C.kind == CXCursor_TranslationUnit) {
6087 ASTUnit *TU = getCursorASTUnit(C);
6088 FileID MainID = TU->getSourceManager().getMainFileID();
6089 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6090 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6091 return SourceRange(Start, End);
6092 }
6093
6094 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006095 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006096 if (!D)
6097 return SourceRange();
6098
6099 SourceRange R = D->getSourceRange();
6100 // FIXME: Multiple variables declared in a single declaration
6101 // currently lack the information needed to correctly determine their
6102 // ranges when accounting for the type-specifier. We use context
6103 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6104 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006105 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 if (!cxcursor::isFirstInDeclGroup(C))
6107 R.setBegin(VD->getLocation());
6108 }
6109 return R;
6110 }
6111 return SourceRange();
6112}
6113
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006114/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006115/// the decl-specifier-seq for declarations.
6116static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6117 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006118 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006119 if (!D)
6120 return SourceRange();
6121
6122 SourceRange R = D->getSourceRange();
6123
6124 // Adjust the start of the location for declarations preceded by
6125 // declaration specifiers.
6126 SourceLocation StartLoc;
6127 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6128 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006129 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006130 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006131 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006132 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006133 }
6134
6135 if (StartLoc.isValid() && R.getBegin().isValid() &&
6136 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6137 R.setBegin(StartLoc);
6138
6139 // FIXME: Multiple variables declared in a single declaration
6140 // currently lack the information needed to correctly determine their
6141 // ranges when accounting for the type-specifier. We use context
6142 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6143 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006144 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 if (!cxcursor::isFirstInDeclGroup(C))
6146 R.setBegin(VD->getLocation());
6147 }
6148
6149 return R;
6150 }
6151
6152 return getRawCursorExtent(C);
6153}
6154
Guy Benyei11169dd2012-12-18 14:30:41 +00006155CXSourceRange clang_getCursorExtent(CXCursor C) {
6156 SourceRange R = getRawCursorExtent(C);
6157 if (R.isInvalid())
6158 return clang_getNullRange();
6159
6160 return cxloc::translateSourceRange(getCursorContext(C), R);
6161}
6162
6163CXCursor clang_getCursorReferenced(CXCursor C) {
6164 if (clang_isInvalid(C.kind))
6165 return clang_getNullCursor();
6166
6167 CXTranslationUnit tu = getCursorTU(C);
6168 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006169 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006170 if (!D)
6171 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006172 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006173 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006174 if (const ObjCPropertyImplDecl *PropImpl =
6175 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006176 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6177 return MakeCXCursor(Property, tu);
6178
6179 return C;
6180 }
6181
6182 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006183 const Expr *E = getCursorExpr(C);
6184 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006185 if (D) {
6186 CXCursor declCursor = MakeCXCursor(D, tu);
6187 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6188 declCursor);
6189 return declCursor;
6190 }
6191
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006192 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006193 return MakeCursorOverloadedDeclRef(Ovl, tu);
6194
6195 return clang_getNullCursor();
6196 }
6197
6198 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006199 const Stmt *S = getCursorStmt(C);
6200 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006201 if (LabelDecl *label = Goto->getLabel())
6202 if (LabelStmt *labelS = label->getStmt())
6203 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6204
6205 return clang_getNullCursor();
6206 }
Richard Smith66a81862015-05-04 02:25:31 +00006207
Guy Benyei11169dd2012-12-18 14:30:41 +00006208 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006209 if (const MacroDefinitionRecord *Def =
6210 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006211 return MakeMacroDefinitionCursor(Def, tu);
6212 }
6213
6214 if (!clang_isReference(C.kind))
6215 return clang_getNullCursor();
6216
6217 switch (C.kind) {
6218 case CXCursor_ObjCSuperClassRef:
6219 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6220
6221 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006222 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6223 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 return MakeCXCursor(Def, tu);
6225
6226 return MakeCXCursor(Prot, tu);
6227 }
6228
6229 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006230 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6231 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 return MakeCXCursor(Def, tu);
6233
6234 return MakeCXCursor(Class, tu);
6235 }
6236
6237 case CXCursor_TypeRef:
6238 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6239
6240 case CXCursor_TemplateRef:
6241 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6242
6243 case CXCursor_NamespaceRef:
6244 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6245
6246 case CXCursor_MemberRef:
6247 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6248
6249 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006250 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006251 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6252 tu ));
6253 }
6254
6255 case CXCursor_LabelRef:
6256 // FIXME: We end up faking the "parent" declaration here because we
6257 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006258 return MakeCXCursor(getCursorLabelRef(C).first,
6259 cxtu::getASTUnit(tu)->getASTContext()
6260 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006261 tu);
6262
6263 case CXCursor_OverloadedDeclRef:
6264 return C;
6265
6266 case CXCursor_VariableRef:
6267 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6268
6269 default:
6270 // We would prefer to enumerate all non-reference cursor kinds here.
6271 llvm_unreachable("Unhandled reference cursor kind");
6272 }
6273}
6274
6275CXCursor clang_getCursorDefinition(CXCursor C) {
6276 if (clang_isInvalid(C.kind))
6277 return clang_getNullCursor();
6278
6279 CXTranslationUnit TU = getCursorTU(C);
6280
6281 bool WasReference = false;
6282 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6283 C = clang_getCursorReferenced(C);
6284 WasReference = true;
6285 }
6286
6287 if (C.kind == CXCursor_MacroExpansion)
6288 return clang_getCursorReferenced(C);
6289
6290 if (!clang_isDeclaration(C.kind))
6291 return clang_getNullCursor();
6292
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006293 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 if (!D)
6295 return clang_getNullCursor();
6296
6297 switch (D->getKind()) {
6298 // Declaration kinds that don't really separate the notions of
6299 // declaration and definition.
6300 case Decl::Namespace:
6301 case Decl::Typedef:
6302 case Decl::TypeAlias:
6303 case Decl::TypeAliasTemplate:
6304 case Decl::TemplateTypeParm:
6305 case Decl::EnumConstant:
6306 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006307 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006308 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006309 case Decl::IndirectField:
6310 case Decl::ObjCIvar:
6311 case Decl::ObjCAtDefsField:
6312 case Decl::ImplicitParam:
6313 case Decl::ParmVar:
6314 case Decl::NonTypeTemplateParm:
6315 case Decl::TemplateTemplateParm:
6316 case Decl::ObjCCategoryImpl:
6317 case Decl::ObjCImplementation:
6318 case Decl::AccessSpec:
6319 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006320 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006321 case Decl::ObjCPropertyImpl:
6322 case Decl::FileScopeAsm:
6323 case Decl::StaticAssert:
6324 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006325 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006326 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006327 case Decl::Label: // FIXME: Is this right??
6328 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006329 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006331 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006332 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006333 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006334 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006335 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006336 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006337 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006338 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006339 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006340 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006341 case Decl::Concept:
Tykerb0561b32019-11-17 11:41:55 +01006342 case Decl::LifetimeExtendedTemporary:
Saar Raza0f50d72020-01-18 09:11:43 +02006343 case Decl::RequiresExprBody:
Guy Benyei11169dd2012-12-18 14:30:41 +00006344 return C;
6345
6346 // Declaration kinds that don't make any sense here, but are
6347 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006348 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006350 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006351 break;
6352
6353 // Declaration kinds for which the definition is not resolvable.
6354 case Decl::UnresolvedUsingTypename:
6355 case Decl::UnresolvedUsingValue:
6356 break;
6357
6358 case Decl::UsingDirective:
6359 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6360 TU);
6361
6362 case Decl::NamespaceAlias:
6363 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6364
6365 case Decl::Enum:
6366 case Decl::Record:
6367 case Decl::CXXRecord:
6368 case Decl::ClassTemplateSpecialization:
6369 case Decl::ClassTemplatePartialSpecialization:
6370 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6371 return MakeCXCursor(Def, TU);
6372 return clang_getNullCursor();
6373
6374 case Decl::Function:
6375 case Decl::CXXMethod:
6376 case Decl::CXXConstructor:
6377 case Decl::CXXDestructor:
6378 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006379 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006381 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006382 return clang_getNullCursor();
6383 }
6384
Larisse Voufo39a1e502013-08-06 01:03:05 +00006385 case Decl::Var:
6386 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006387 case Decl::VarTemplatePartialSpecialization:
6388 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006389 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006390 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006391 return MakeCXCursor(Def, TU);
6392 return clang_getNullCursor();
6393 }
6394
6395 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006396 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006397 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6398 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6399 return clang_getNullCursor();
6400 }
6401
6402 case Decl::ClassTemplate: {
6403 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6404 ->getDefinition())
6405 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6406 TU);
6407 return clang_getNullCursor();
6408 }
6409
Larisse Voufo39a1e502013-08-06 01:03:05 +00006410 case Decl::VarTemplate: {
6411 if (VarDecl *Def =
6412 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6413 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6414 return clang_getNullCursor();
6415 }
6416
Guy Benyei11169dd2012-12-18 14:30:41 +00006417 case Decl::Using:
6418 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6419 D->getLocation(), TU);
6420
6421 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006422 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006423 return clang_getCursorDefinition(
6424 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6425 TU));
6426
6427 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006428 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006429 if (Method->isThisDeclarationADefinition())
6430 return C;
6431
6432 // Dig out the method definition in the associated
6433 // @implementation, if we have it.
6434 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006435 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006436 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6437 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6438 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6439 Method->isInstanceMethod()))
6440 if (Def->isThisDeclarationADefinition())
6441 return MakeCXCursor(Def, TU);
6442
6443 return clang_getNullCursor();
6444 }
6445
6446 case Decl::ObjCCategory:
6447 if (ObjCCategoryImplDecl *Impl
6448 = cast<ObjCCategoryDecl>(D)->getImplementation())
6449 return MakeCXCursor(Impl, TU);
6450 return clang_getNullCursor();
6451
6452 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006453 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006454 return MakeCXCursor(Def, TU);
6455 return clang_getNullCursor();
6456
6457 case Decl::ObjCInterface: {
6458 // There are two notions of a "definition" for an Objective-C
6459 // class: the interface and its implementation. When we resolved a
6460 // reference to an Objective-C class, produce the @interface as
6461 // the definition; when we were provided with the interface,
6462 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006463 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006464 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006465 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006466 return MakeCXCursor(Def, TU);
6467 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6468 return MakeCXCursor(Impl, TU);
6469 return clang_getNullCursor();
6470 }
6471
6472 case Decl::ObjCProperty:
6473 // FIXME: We don't really know where to find the
6474 // ObjCPropertyImplDecls that implement this property.
6475 return clang_getNullCursor();
6476
6477 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006478 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006479 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006480 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006481 return MakeCXCursor(Def, TU);
6482
6483 return clang_getNullCursor();
6484
6485 case Decl::Friend:
6486 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6487 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6488 return clang_getNullCursor();
6489
6490 case Decl::FriendTemplate:
6491 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6492 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6493 return clang_getNullCursor();
6494 }
6495
6496 return clang_getNullCursor();
6497}
6498
6499unsigned clang_isCursorDefinition(CXCursor C) {
6500 if (!clang_isDeclaration(C.kind))
6501 return 0;
6502
6503 return clang_getCursorDefinition(C) == C;
6504}
6505
6506CXCursor clang_getCanonicalCursor(CXCursor C) {
6507 if (!clang_isDeclaration(C.kind))
6508 return C;
6509
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006510 if (const Decl *D = getCursorDecl(C)) {
6511 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006512 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6513 return MakeCXCursor(CatD, getCursorTU(C));
6514
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006515 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6516 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 return MakeCXCursor(IFD, getCursorTU(C));
6518
6519 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6520 }
6521
6522 return C;
6523}
6524
6525int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6526 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6527}
6528
6529unsigned clang_getNumOverloadedDecls(CXCursor C) {
6530 if (C.kind != CXCursor_OverloadedDeclRef)
6531 return 0;
6532
6533 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006534 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 return E->getNumDecls();
6536
6537 if (OverloadedTemplateStorage *S
6538 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6539 return S->size();
6540
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006541 const Decl *D = Storage.get<const Decl *>();
6542 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006543 return Using->shadow_size();
6544
6545 return 0;
6546}
6547
6548CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6549 if (cursor.kind != CXCursor_OverloadedDeclRef)
6550 return clang_getNullCursor();
6551
6552 if (index >= clang_getNumOverloadedDecls(cursor))
6553 return clang_getNullCursor();
6554
6555 CXTranslationUnit TU = getCursorTU(cursor);
6556 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006557 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006558 return MakeCXCursor(E->decls_begin()[index], TU);
6559
6560 if (OverloadedTemplateStorage *S
6561 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6562 return MakeCXCursor(S->begin()[index], TU);
6563
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006564 const Decl *D = Storage.get<const Decl *>();
6565 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006566 // FIXME: This is, unfortunately, linear time.
6567 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6568 std::advance(Pos, index);
6569 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6570 }
6571
6572 return clang_getNullCursor();
6573}
6574
6575void clang_getDefinitionSpellingAndExtent(CXCursor C,
6576 const char **startBuf,
6577 const char **endBuf,
6578 unsigned *startLine,
6579 unsigned *startColumn,
6580 unsigned *endLine,
6581 unsigned *endColumn) {
6582 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006583 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006584 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6585
6586 SourceManager &SM = FD->getASTContext().getSourceManager();
6587 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6588 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6589 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6590 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6591 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6592 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6593}
6594
6595
6596CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6597 unsigned PieceIndex) {
6598 RefNamePieces Pieces;
6599
6600 switch (C.kind) {
6601 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006602 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006603 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6604 E->getQualifierLoc().getSourceRange());
6605 break;
6606
6607 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006608 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6609 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6610 Pieces =
6611 buildPieces(NameFlags, false, E->getNameInfo(),
6612 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6613 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 break;
6615
6616 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006617 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006619 const Expr *Callee = OCE->getCallee();
6620 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 Callee = ICE->getSubExpr();
6622
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006623 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006624 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6625 DRE->getQualifierLoc().getSourceRange());
6626 }
6627 break;
6628
6629 default:
6630 break;
6631 }
6632
6633 if (Pieces.empty()) {
6634 if (PieceIndex == 0)
6635 return clang_getCursorExtent(C);
6636 } else if (PieceIndex < Pieces.size()) {
6637 SourceRange R = Pieces[PieceIndex];
6638 if (R.isValid())
6639 return cxloc::translateSourceRange(getCursorContext(C), R);
6640 }
6641
6642 return clang_getNullRange();
6643}
6644
6645void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006646 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6647 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006648}
6649
6650void clang_executeOnThread(void (*fn)(void*), void *user_data,
6651 unsigned stack_size) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05006652 llvm::llvm_execute_on_thread(fn, user_data,
6653 stack_size == 0
6654 ? clang::DesiredStackSize
6655 : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006656}
6657
Guy Benyei11169dd2012-12-18 14:30:41 +00006658//===----------------------------------------------------------------------===//
6659// Token-based Operations.
6660//===----------------------------------------------------------------------===//
6661
6662/* CXToken layout:
6663 * int_data[0]: a CXTokenKind
6664 * int_data[1]: starting token location
6665 * int_data[2]: token length
6666 * int_data[3]: reserved
6667 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6668 * otherwise unused.
6669 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006670CXTokenKind clang_getTokenKind(CXToken CXTok) {
6671 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6672}
6673
6674CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6675 switch (clang_getTokenKind(CXTok)) {
6676 case CXToken_Identifier:
6677 case CXToken_Keyword:
6678 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006679 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006680 ->getNameStart());
6681
6682 case CXToken_Literal: {
6683 // We have stashed the starting pointer in the ptr_data field. Use it.
6684 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006685 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006686 }
6687
6688 case CXToken_Punctuation:
6689 case CXToken_Comment:
6690 break;
6691 }
6692
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006693 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006694 LOG_BAD_TU(TU);
6695 return cxstring::createEmpty();
6696 }
6697
Guy Benyei11169dd2012-12-18 14:30:41 +00006698 // We have to find the starting buffer pointer the hard way, by
6699 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006700 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006701 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006702 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006703
6704 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6705 std::pair<FileID, unsigned> LocInfo
6706 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6707 bool Invalid = false;
6708 StringRef Buffer
6709 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6710 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006711 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006712
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006713 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006714}
6715
6716CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006717 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006718 LOG_BAD_TU(TU);
6719 return clang_getNullLocation();
6720 }
6721
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006722 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006723 if (!CXXUnit)
6724 return clang_getNullLocation();
6725
6726 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6727 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6728}
6729
6730CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006731 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006732 LOG_BAD_TU(TU);
6733 return clang_getNullRange();
6734 }
6735
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006736 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006737 if (!CXXUnit)
6738 return clang_getNullRange();
6739
6740 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6741 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6742}
6743
6744static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6745 SmallVectorImpl<CXToken> &CXTokens) {
6746 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6747 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006748 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006749 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006750 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006751
6752 // Cannot tokenize across files.
6753 if (BeginLocInfo.first != EndLocInfo.first)
6754 return;
6755
6756 // Create a lexer
6757 bool Invalid = false;
6758 StringRef Buffer
6759 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6760 if (Invalid)
6761 return;
6762
6763 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6764 CXXUnit->getASTContext().getLangOpts(),
6765 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6766 Lex.SetCommentRetentionState(true);
6767
6768 // Lex tokens until we hit the end of the range.
6769 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6770 Token Tok;
6771 bool previousWasAt = false;
6772 do {
6773 // Lex the next token
6774 Lex.LexFromRawLexer(Tok);
6775 if (Tok.is(tok::eof))
6776 break;
6777
6778 // Initialize the CXToken.
6779 CXToken CXTok;
6780
6781 // - Common fields
6782 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6783 CXTok.int_data[2] = Tok.getLength();
6784 CXTok.int_data[3] = 0;
6785
6786 // - Kind-specific fields
6787 if (Tok.isLiteral()) {
6788 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006789 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006790 } else if (Tok.is(tok::raw_identifier)) {
6791 // Lookup the identifier to determine whether we have a keyword.
6792 IdentifierInfo *II
6793 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6794
6795 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6796 CXTok.int_data[0] = CXToken_Keyword;
6797 }
6798 else {
6799 CXTok.int_data[0] = Tok.is(tok::identifier)
6800 ? CXToken_Identifier
6801 : CXToken_Keyword;
6802 }
6803 CXTok.ptr_data = II;
6804 } else if (Tok.is(tok::comment)) {
6805 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006806 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006807 } else {
6808 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006809 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006810 }
6811 CXTokens.push_back(CXTok);
6812 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006813 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006814}
6815
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006816CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6817 LOG_FUNC_SECTION {
6818 *Log << TU << ' ' << Location;
6819 }
6820
6821 if (isNotUsableTU(TU)) {
6822 LOG_BAD_TU(TU);
6823 return NULL;
6824 }
6825
6826 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6827 if (!CXXUnit)
6828 return NULL;
6829
6830 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6831 if (Begin.isInvalid())
6832 return NULL;
6833 SourceManager &SM = CXXUnit->getSourceManager();
6834 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6835 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6836
6837 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6838
6839 SmallVector<CXToken, 32> CXTokens;
6840 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6841
6842 if (CXTokens.empty())
6843 return NULL;
6844
6845 CXTokens.resize(1);
6846 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6847
6848 memmove(Token, CXTokens.data(), sizeof(CXToken));
6849 return Token;
6850}
6851
Guy Benyei11169dd2012-12-18 14:30:41 +00006852void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6853 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006854 LOG_FUNC_SECTION {
6855 *Log << TU << ' ' << Range;
6856 }
6857
Guy Benyei11169dd2012-12-18 14:30:41 +00006858 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006859 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 if (NumTokens)
6861 *NumTokens = 0;
6862
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006863 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006864 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006865 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006866 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006867
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006868 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006869 if (!CXXUnit || !Tokens || !NumTokens)
6870 return;
6871
6872 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6873
6874 SourceRange R = cxloc::translateCXSourceRange(Range);
6875 if (R.isInvalid())
6876 return;
6877
6878 SmallVector<CXToken, 32> CXTokens;
6879 getTokens(CXXUnit, R, CXTokens);
6880
6881 if (CXTokens.empty())
6882 return;
6883
Serge Pavlov52525732018-02-21 02:02:39 +00006884 *Tokens = static_cast<CXToken *>(
6885 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006886 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6887 *NumTokens = CXTokens.size();
6888}
6889
6890void clang_disposeTokens(CXTranslationUnit TU,
6891 CXToken *Tokens, unsigned NumTokens) {
6892 free(Tokens);
6893}
6894
Guy Benyei11169dd2012-12-18 14:30:41 +00006895//===----------------------------------------------------------------------===//
6896// Token annotation APIs.
6897//===----------------------------------------------------------------------===//
6898
Guy Benyei11169dd2012-12-18 14:30:41 +00006899static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6900 CXCursor parent,
6901 CXClientData client_data);
6902static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6903 CXClientData client_data);
6904
6905namespace {
6906class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 CXToken *Tokens;
6908 CXCursor *Cursors;
6909 unsigned NumTokens;
6910 unsigned TokIdx;
6911 unsigned PreprocessingTokIdx;
6912 CursorVisitor AnnotateVis;
6913 SourceManager &SrcMgr;
6914 bool HasContextSensitiveKeywords;
6915
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006916 struct PostChildrenAction {
6917 CXCursor cursor;
6918 enum Action { Invalid, Ignore, Postpone } action;
6919 };
6920 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6921
Guy Benyei11169dd2012-12-18 14:30:41 +00006922 struct PostChildrenInfo {
6923 CXCursor Cursor;
6924 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006925 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006927 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006928 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006929 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006930
6931 CXToken &getTok(unsigned Idx) {
6932 assert(Idx < NumTokens);
6933 return Tokens[Idx];
6934 }
6935 const CXToken &getTok(unsigned Idx) const {
6936 assert(Idx < NumTokens);
6937 return Tokens[Idx];
6938 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006939 bool MoreTokens() const { return TokIdx < NumTokens; }
6940 unsigned NextToken() const { return TokIdx; }
6941 void AdvanceToken() { ++TokIdx; }
6942 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006943 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 }
6945 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006946 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 }
6948 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006949 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 }
6951
6952 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006953 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006954 SourceRange);
6955
6956public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006957 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006958 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006959 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006960 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006961 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006962 AnnotateTokensVisitor, this,
6963 /*VisitPreprocessorLast=*/true,
6964 /*VisitIncludedEntities=*/false,
6965 RegionOfInterest,
6966 /*VisitDeclsOnly=*/false,
6967 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006968 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 HasContextSensitiveKeywords(false) { }
6970
6971 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6972 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006973 bool IsIgnoredChildCursor(CXCursor cursor) const;
6974 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6975
Guy Benyei11169dd2012-12-18 14:30:41 +00006976 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006977 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6978 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6979
Guy Benyei11169dd2012-12-18 14:30:41 +00006980 void AnnotateTokens();
6981
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006982 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 /// context-sensitive keywords.
6984 bool hasContextSensitiveKeywords() const {
6985 return HasContextSensitiveKeywords;
6986 }
6987
6988 ~AnnotateTokensWorker() {
6989 assert(PostChildrenInfos.empty());
6990 }
6991};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006992}
Guy Benyei11169dd2012-12-18 14:30:41 +00006993
6994void AnnotateTokensWorker::AnnotateTokens() {
6995 // Walk the AST within the region of interest, annotating tokens
6996 // along the way.
6997 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006998}
Guy Benyei11169dd2012-12-18 14:30:41 +00006999
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007000bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
7001 if (PostChildrenInfos.empty())
7002 return false;
7003
7004 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
7005 if (ChildAction.cursor == cursor &&
7006 ChildAction.action == PostChildrenAction::Ignore) {
7007 return true;
7008 }
7009 }
7010
7011 return false;
7012}
7013
7014const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
7015 if (!clang_isExpression(Cursor.kind))
7016 return nullptr;
7017
7018 const Expr *E = getCursorExpr(Cursor);
7019 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7020 const OverloadedOperatorKind Kind = OCE->getOperator();
7021 if (Kind == OO_Call || Kind == OO_Subscript)
7022 return OCE;
7023 }
7024
7025 return nullptr;
7026}
7027
7028AnnotateTokensWorker::PostChildrenActions
7029AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7030 PostChildrenActions actions;
7031
7032 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
7033 // visited before the arguments to the operator call. For the Call and
7034 // Subscript operator the range of this DeclRefExpr includes the whole call
7035 // expression, so that all tokens in that range would be mapped to the
7036 // operator function, including the tokens of the arguments. To avoid that,
7037 // ensure to visit this DeclRefExpr as last node.
7038 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7039 const Expr *Callee = OCE->getCallee();
7040 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7041 const Expr *SubExpr = ICE->getSubExpr();
7042 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007043 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007044 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7045
7046 // Visit the DeclRefExpr as last.
7047 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7048 actions.push_back({cxChild, PostChildrenAction::Postpone});
7049
7050 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7051 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7052 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7053 actions.push_back({cxChild, PostChildrenAction::Ignore});
7054 }
7055 }
7056 }
7057
7058 return actions;
7059}
7060
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007061static inline void updateCursorAnnotation(CXCursor &Cursor,
7062 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007063 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007064 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007065 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007066}
7067
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007068/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007069//// between the cursor location and the source range is the same as
7070/// \arg compResult.
7071///
7072/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7073/// Pass RangeOverlap to annotate tokens inside a range.
7074void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7075 RangeComparisonResult compResult,
7076 SourceRange range) {
7077 while (MoreTokens()) {
7078 const unsigned I = NextToken();
7079 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007080 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7081 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007082
7083 SourceLocation TokLoc = GetTokenLoc(I);
7084 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007085 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007086 AdvanceToken();
7087 continue;
7088 }
7089 break;
7090 }
7091}
7092
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007093/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007094/// \returns true if it advanced beyond all macro tokens, false otherwise.
7095bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007096 CXCursor updateC,
7097 RangeComparisonResult compResult,
7098 SourceRange range) {
7099 assert(MoreTokens());
7100 assert(isFunctionMacroToken(NextToken()) &&
7101 "Should be called only for macro arg tokens");
7102
7103 // This works differently than annotateAndAdvanceTokens; because expanded
7104 // macro arguments can have arbitrary translation-unit source order, we do not
7105 // advance the token index one by one until a token fails the range test.
7106 // We only advance once past all of the macro arg tokens if all of them
7107 // pass the range test. If one of them fails we keep the token index pointing
7108 // at the start of the macro arg tokens so that the failing token will be
7109 // annotated by a subsequent annotation try.
7110
7111 bool atLeastOneCompFail = false;
7112
7113 unsigned I = NextToken();
7114 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7115 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7116 if (TokLoc.isFileID())
7117 continue; // not macro arg token, it's parens or comma.
7118 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7119 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7120 Cursors[I] = updateC;
7121 } else
7122 atLeastOneCompFail = true;
7123 }
7124
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007125 if (atLeastOneCompFail)
7126 return false;
7127
7128 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7129 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007130}
7131
7132enum CXChildVisitResult
7133AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007134 SourceRange cursorRange = getRawCursorExtent(cursor);
7135 if (cursorRange.isInvalid())
7136 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007137
7138 if (IsIgnoredChildCursor(cursor))
7139 return CXChildVisit_Continue;
7140
Guy Benyei11169dd2012-12-18 14:30:41 +00007141 if (!HasContextSensitiveKeywords) {
7142 // Objective-C properties can have context-sensitive keywords.
7143 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007144 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007145 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7146 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7147 }
7148 // Objective-C methods can have context-sensitive keywords.
7149 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7150 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007151 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007152 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7153 if (Method->getObjCDeclQualifier())
7154 HasContextSensitiveKeywords = true;
7155 else {
David Majnemer59f77922016-06-24 04:05:48 +00007156 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007157 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007158 HasContextSensitiveKeywords = true;
7159 break;
7160 }
7161 }
7162 }
7163 }
7164 }
7165 // C++ methods can have context-sensitive keywords.
7166 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007167 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007168 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7169 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7170 HasContextSensitiveKeywords = true;
7171 }
7172 }
7173 // C++ classes can have context-sensitive keywords.
7174 else if (cursor.kind == CXCursor_StructDecl ||
7175 cursor.kind == CXCursor_ClassDecl ||
7176 cursor.kind == CXCursor_ClassTemplate ||
7177 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007178 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007179 if (D->hasAttr<FinalAttr>())
7180 HasContextSensitiveKeywords = true;
7181 }
7182 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007183
7184 // Don't override a property annotation with its getter/setter method.
7185 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7186 parent.kind == CXCursor_ObjCPropertyDecl)
7187 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007188
7189 if (clang_isPreprocessing(cursor.kind)) {
7190 // Items in the preprocessing record are kept separate from items in
7191 // declarations, so we keep a separate token index.
7192 unsigned SavedTokIdx = TokIdx;
7193 TokIdx = PreprocessingTokIdx;
7194
7195 // Skip tokens up until we catch up to the beginning of the preprocessing
7196 // entry.
7197 while (MoreTokens()) {
7198 const unsigned I = NextToken();
7199 SourceLocation TokLoc = GetTokenLoc(I);
7200 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7201 case RangeBefore:
7202 AdvanceToken();
7203 continue;
7204 case RangeAfter:
7205 case RangeOverlap:
7206 break;
7207 }
7208 break;
7209 }
7210
7211 // Look at all of the tokens within this range.
7212 while (MoreTokens()) {
7213 const unsigned I = NextToken();
7214 SourceLocation TokLoc = GetTokenLoc(I);
7215 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7216 case RangeBefore:
7217 llvm_unreachable("Infeasible");
7218 case RangeAfter:
7219 break;
7220 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007221 // For macro expansions, just note where the beginning of the macro
7222 // expansion occurs.
7223 if (cursor.kind == CXCursor_MacroExpansion) {
7224 if (TokLoc == cursorRange.getBegin())
7225 Cursors[I] = cursor;
7226 AdvanceToken();
7227 break;
7228 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007229 // We may have already annotated macro names inside macro definitions.
7230 if (Cursors[I].kind != CXCursor_MacroExpansion)
7231 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007232 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 continue;
7234 }
7235 break;
7236 }
7237
7238 // Save the preprocessing token index; restore the non-preprocessing
7239 // token index.
7240 PreprocessingTokIdx = TokIdx;
7241 TokIdx = SavedTokIdx;
7242 return CXChildVisit_Recurse;
7243 }
7244
7245 if (cursorRange.isInvalid())
7246 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007247
7248 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007249 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007250 const enum CXCursorKind K = clang_getCursorKind(parent);
7251 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007252 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7253 // Attributes are annotated out-of-order, skip tokens until we reach it.
7254 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 ? clang_getNullCursor() : parent;
7256
7257 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7258
7259 // Avoid having the cursor of an expression "overwrite" the annotation of the
7260 // variable declaration that it belongs to.
7261 // This can happen for C++ constructor expressions whose range generally
7262 // include the variable declaration, e.g.:
7263 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007264 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007265 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007266 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007267 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007268 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7269 E->getBeginLoc() == D->getLocation() &&
7270 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007271 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007272 AdvanceToken();
7273 }
7274 }
7275 }
7276
7277 // Before recursing into the children keep some state that we are going
7278 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7279 // extra work after the child nodes are visited.
7280 // Note that we don't call VisitChildren here to avoid traversing statements
7281 // code-recursively which can blow the stack.
7282
7283 PostChildrenInfo Info;
7284 Info.Cursor = cursor;
7285 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007286 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007287 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007288 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 PostChildrenInfos.push_back(Info);
7290
7291 return CXChildVisit_Recurse;
7292}
7293
7294bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7295 if (PostChildrenInfos.empty())
7296 return false;
7297 const PostChildrenInfo &Info = PostChildrenInfos.back();
7298 if (!clang_equalCursors(Info.Cursor, cursor))
7299 return false;
7300
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007301 HandlePostPonedChildCursors(Info);
7302
Guy Benyei11169dd2012-12-18 14:30:41 +00007303 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7304 const unsigned AfterChildren = NextToken();
7305 SourceRange cursorRange = Info.CursorRange;
7306
7307 // Scan the tokens that are at the end of the cursor, but are not captured
7308 // but the child cursors.
7309 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7310
7311 // Scan the tokens that are at the beginning of the cursor, but are not
7312 // capture by the child cursors.
7313 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7314 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7315 break;
7316
7317 Cursors[I] = cursor;
7318 }
7319
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007320 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7321 // encountered the attribute cursor.
7322 if (clang_isAttribute(cursor.kind))
7323 TokIdx = Info.BeforeReachingCursorIdx;
7324
Guy Benyei11169dd2012-12-18 14:30:41 +00007325 PostChildrenInfos.pop_back();
7326 return false;
7327}
7328
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007329void AnnotateTokensWorker::HandlePostPonedChildCursors(
7330 const PostChildrenInfo &Info) {
7331 for (const auto &ChildAction : Info.ChildActions) {
7332 if (ChildAction.action == PostChildrenAction::Postpone) {
7333 HandlePostPonedChildCursor(ChildAction.cursor,
7334 Info.BeforeChildrenTokenIdx);
7335 }
7336 }
7337}
7338
7339void AnnotateTokensWorker::HandlePostPonedChildCursor(
7340 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007341 unsigned I = StartTokenIndex;
7342
7343 // The bracket tokens of a Call or Subscript operator are mapped to
7344 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7345 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7346 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007347 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7348 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007349 if (clang_Range_isNull(CXRefNameRange))
7350 break; // All ranges handled.
7351
7352 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7353 while (I < NumTokens) {
7354 const SourceLocation TokenLocation = GetTokenLoc(I);
7355 if (!TokenLocation.isValid())
7356 break;
7357
7358 // Adapt the end range, because LocationCompare() reports
7359 // RangeOverlap even for the not-inclusive end location.
7360 const SourceLocation fixedEnd =
7361 RefNameRange.getEnd().getLocWithOffset(-1);
7362 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7363
7364 const RangeComparisonResult ComparisonResult =
7365 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7366
7367 if (ComparisonResult == RangeOverlap) {
7368 Cursors[I++] = Cursor;
7369 } else if (ComparisonResult == RangeBefore) {
7370 ++I; // Not relevant token, check next one.
7371 } else if (ComparisonResult == RangeAfter) {
7372 break; // All tokens updated for current range, check next.
7373 }
7374 }
7375 }
7376}
7377
Guy Benyei11169dd2012-12-18 14:30:41 +00007378static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7379 CXCursor parent,
7380 CXClientData client_data) {
7381 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7382}
7383
7384static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7385 CXClientData client_data) {
7386 return static_cast<AnnotateTokensWorker*>(client_data)->
7387 postVisitChildren(cursor);
7388}
7389
7390namespace {
7391
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007392/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007393/// and mark tokens that are macro arguments. This info is used by the
7394/// AnnotateTokensWorker.
7395class MarkMacroArgTokensVisitor {
7396 SourceManager &SM;
7397 CXToken *Tokens;
7398 unsigned NumTokens;
7399 unsigned CurIdx;
7400
7401public:
7402 MarkMacroArgTokensVisitor(SourceManager &SM,
7403 CXToken *tokens, unsigned numTokens)
7404 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7405
7406 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7407 if (cursor.kind != CXCursor_MacroExpansion)
7408 return CXChildVisit_Continue;
7409
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007410 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007411 if (macroRange.getBegin() == macroRange.getEnd())
7412 return CXChildVisit_Continue; // it's not a function macro.
7413
7414 for (; CurIdx < NumTokens; ++CurIdx) {
7415 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7416 macroRange.getBegin()))
7417 break;
7418 }
7419
7420 if (CurIdx == NumTokens)
7421 return CXChildVisit_Break;
7422
7423 for (; CurIdx < NumTokens; ++CurIdx) {
7424 SourceLocation tokLoc = getTokenLoc(CurIdx);
7425 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7426 break;
7427
7428 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7429 }
7430
7431 if (CurIdx == NumTokens)
7432 return CXChildVisit_Break;
7433
7434 return CXChildVisit_Continue;
7435 }
7436
7437private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007438 CXToken &getTok(unsigned Idx) {
7439 assert(Idx < NumTokens);
7440 return Tokens[Idx];
7441 }
7442 const CXToken &getTok(unsigned Idx) const {
7443 assert(Idx < NumTokens);
7444 return Tokens[Idx];
7445 }
7446
Guy Benyei11169dd2012-12-18 14:30:41 +00007447 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007448 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007449 }
7450
7451 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7452 // The third field is reserved and currently not used. Use it here
7453 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007454 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007455 }
7456};
7457
7458} // end anonymous namespace
7459
7460static CXChildVisitResult
7461MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7462 CXClientData client_data) {
7463 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7464 parent);
7465}
7466
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007467/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007468/// \returns true if lexing was finished, false otherwise.
7469static bool lexNext(Lexer &Lex, Token &Tok,
7470 unsigned &NextIdx, unsigned NumTokens) {
7471 if (NextIdx >= NumTokens)
7472 return true;
7473
7474 ++NextIdx;
7475 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007476 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007477}
7478
Guy Benyei11169dd2012-12-18 14:30:41 +00007479static void annotatePreprocessorTokens(CXTranslationUnit TU,
7480 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007481 CXCursor *Cursors,
7482 CXToken *Tokens,
7483 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007484 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007485
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007486 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7488 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007489 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007490 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007491 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007492
7493 if (BeginLocInfo.first != EndLocInfo.first)
7494 return;
7495
7496 StringRef Buffer;
7497 bool Invalid = false;
7498 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7499 if (Buffer.empty() || Invalid)
7500 return;
7501
7502 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7503 CXXUnit->getASTContext().getLangOpts(),
7504 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7505 Buffer.end());
7506 Lex.SetCommentRetentionState(true);
7507
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007508 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007509 // Lex tokens in raw mode until we hit the end of the range, to avoid
7510 // entering #includes or expanding macros.
7511 while (true) {
7512 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007513 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7514 break;
7515 unsigned TokIdx = NextIdx-1;
7516 assert(Tok.getLocation() ==
7517 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007518
7519 reprocess:
7520 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007521 // We have found a preprocessing directive. Annotate the tokens
7522 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007523 //
7524 // FIXME: Some simple tests here could identify macro definitions and
7525 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007526
7527 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007528 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7529 break;
7530
Craig Topper69186e72014-06-08 08:38:04 +00007531 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007532 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007533 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7534 break;
7535
7536 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007537 IdentifierInfo &II =
7538 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007539 SourceLocation MappedTokLoc =
7540 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7541 MI = getMacroInfo(II, MappedTokLoc, TU);
7542 }
7543 }
7544
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007545 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007546 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007547 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7548 finished = true;
7549 break;
7550 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007551 // If we are in a macro definition, check if the token was ever a
7552 // macro name and annotate it if that's the case.
7553 if (MI) {
7554 SourceLocation SaveLoc = Tok.getLocation();
7555 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007556 MacroDefinitionRecord *MacroDef =
7557 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007558 Tok.setLocation(SaveLoc);
7559 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007560 Cursors[NextIdx - 1] =
7561 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007562 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007563 } while (!Tok.isAtStartOfLine());
7564
7565 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7566 assert(TokIdx <= LastIdx);
7567 SourceLocation EndLoc =
7568 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7569 CXCursor Cursor =
7570 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7571
7572 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007573 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007574
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007575 if (finished)
7576 break;
7577 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007578 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007579 }
7580}
7581
7582// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007583static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7584 CXToken *Tokens, unsigned NumTokens,
7585 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007586 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007587 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7588 setThreadBackgroundPriority();
7589
7590 // Determine the region of interest, which contains all of the tokens.
7591 SourceRange RegionOfInterest;
7592 RegionOfInterest.setBegin(
7593 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7594 RegionOfInterest.setEnd(
7595 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7596 Tokens[NumTokens-1])));
7597
Guy Benyei11169dd2012-12-18 14:30:41 +00007598 // Relex the tokens within the source range to look for preprocessing
7599 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007600 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007601
7602 // If begin location points inside a macro argument, set it to the expansion
7603 // location so we can have the full context when annotating semantically.
7604 {
7605 SourceManager &SM = CXXUnit->getSourceManager();
7606 SourceLocation Loc =
7607 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7608 if (Loc.isMacroID())
7609 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7610 }
7611
Guy Benyei11169dd2012-12-18 14:30:41 +00007612 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7613 // Search and mark tokens that are macro argument expansions.
7614 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7615 Tokens, NumTokens);
7616 CursorVisitor MacroArgMarker(TU,
7617 MarkMacroArgTokensVisitorDelegate, &Visitor,
7618 /*VisitPreprocessorLast=*/true,
7619 /*VisitIncludedEntities=*/false,
7620 RegionOfInterest);
7621 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7622 }
7623
7624 // Annotate all of the source locations in the region of interest that map to
7625 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007626 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007627
7628 // FIXME: We use a ridiculous stack size here because the data-recursion
7629 // algorithm uses a large stack frame than the non-data recursive version,
7630 // and AnnotationTokensWorker currently transforms the data-recursion
7631 // algorithm back into a traditional recursion by explicitly calling
7632 // VisitChildren(). We will need to remove this explicit recursive call.
7633 W.AnnotateTokens();
7634
7635 // If we ran into any entities that involve context-sensitive keywords,
7636 // take another pass through the tokens to mark them as such.
7637 if (W.hasContextSensitiveKeywords()) {
7638 for (unsigned I = 0; I != NumTokens; ++I) {
7639 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7640 continue;
7641
7642 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7643 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007644 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007645 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7646 if (Property->getPropertyAttributesAsWritten() != 0 &&
7647 llvm::StringSwitch<bool>(II->getName())
7648 .Case("readonly", true)
7649 .Case("assign", true)
7650 .Case("unsafe_unretained", true)
7651 .Case("readwrite", true)
7652 .Case("retain", true)
7653 .Case("copy", true)
7654 .Case("nonatomic", true)
7655 .Case("atomic", true)
7656 .Case("getter", true)
7657 .Case("setter", true)
7658 .Case("strong", true)
7659 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007660 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007661 .Default(false))
7662 Tokens[I].int_data[0] = CXToken_Keyword;
7663 }
7664 continue;
7665 }
7666
7667 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7668 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7669 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7670 if (llvm::StringSwitch<bool>(II->getName())
7671 .Case("in", true)
7672 .Case("out", true)
7673 .Case("inout", true)
7674 .Case("oneway", true)
7675 .Case("bycopy", true)
7676 .Case("byref", true)
7677 .Default(false))
7678 Tokens[I].int_data[0] = CXToken_Keyword;
7679 continue;
7680 }
7681
7682 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7683 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7684 Tokens[I].int_data[0] = CXToken_Keyword;
7685 continue;
7686 }
7687 }
7688 }
7689}
7690
Guy Benyei11169dd2012-12-18 14:30:41 +00007691void clang_annotateTokens(CXTranslationUnit TU,
7692 CXToken *Tokens, unsigned NumTokens,
7693 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007694 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007695 LOG_BAD_TU(TU);
7696 return;
7697 }
7698 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007699 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007701 }
7702
7703 LOG_FUNC_SECTION {
7704 *Log << TU << ' ';
7705 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7706 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7707 *Log << clang_getRange(bloc, eloc);
7708 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007709
7710 // Any token we don't specifically annotate will have a NULL cursor.
7711 CXCursor C = clang_getNullCursor();
7712 for (unsigned I = 0; I != NumTokens; ++I)
7713 Cursors[I] = C;
7714
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007715 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007716 if (!CXXUnit)
7717 return;
7718
7719 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007720
7721 auto AnnotateTokensImpl = [=]() {
7722 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7723 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007724 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007725 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007726 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7727 }
7728}
7729
Guy Benyei11169dd2012-12-18 14:30:41 +00007730//===----------------------------------------------------------------------===//
7731// Operations for querying linkage of a cursor.
7732//===----------------------------------------------------------------------===//
7733
Guy Benyei11169dd2012-12-18 14:30:41 +00007734CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7735 if (!clang_isDeclaration(cursor.kind))
7736 return CXLinkage_Invalid;
7737
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007738 const Decl *D = cxcursor::getCursorDecl(cursor);
7739 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007740 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007741 case NoLinkage:
7742 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007743 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007744 case InternalLinkage: return CXLinkage_Internal;
7745 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007746 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007747 case ExternalLinkage: return CXLinkage_External;
7748 };
7749
7750 return CXLinkage_Invalid;
7751}
Guy Benyei11169dd2012-12-18 14:30:41 +00007752
7753//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007754// Operations for querying visibility of a cursor.
7755//===----------------------------------------------------------------------===//
7756
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007757CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7758 if (!clang_isDeclaration(cursor.kind))
7759 return CXVisibility_Invalid;
7760
7761 const Decl *D = cxcursor::getCursorDecl(cursor);
7762 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7763 switch (ND->getVisibility()) {
7764 case HiddenVisibility: return CXVisibility_Hidden;
7765 case ProtectedVisibility: return CXVisibility_Protected;
7766 case DefaultVisibility: return CXVisibility_Default;
7767 };
7768
7769 return CXVisibility_Invalid;
7770}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007771
7772//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007773// Operations for querying language of a cursor.
7774//===----------------------------------------------------------------------===//
7775
7776static CXLanguageKind getDeclLanguage(const Decl *D) {
7777 if (!D)
7778 return CXLanguage_C;
7779
7780 switch (D->getKind()) {
7781 default:
7782 break;
7783 case Decl::ImplicitParam:
7784 case Decl::ObjCAtDefsField:
7785 case Decl::ObjCCategory:
7786 case Decl::ObjCCategoryImpl:
7787 case Decl::ObjCCompatibleAlias:
7788 case Decl::ObjCImplementation:
7789 case Decl::ObjCInterface:
7790 case Decl::ObjCIvar:
7791 case Decl::ObjCMethod:
7792 case Decl::ObjCProperty:
7793 case Decl::ObjCPropertyImpl:
7794 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007795 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007796 return CXLanguage_ObjC;
7797 case Decl::CXXConstructor:
7798 case Decl::CXXConversion:
7799 case Decl::CXXDestructor:
7800 case Decl::CXXMethod:
7801 case Decl::CXXRecord:
7802 case Decl::ClassTemplate:
7803 case Decl::ClassTemplatePartialSpecialization:
7804 case Decl::ClassTemplateSpecialization:
7805 case Decl::Friend:
7806 case Decl::FriendTemplate:
7807 case Decl::FunctionTemplate:
7808 case Decl::LinkageSpec:
7809 case Decl::Namespace:
7810 case Decl::NamespaceAlias:
7811 case Decl::NonTypeTemplateParm:
7812 case Decl::StaticAssert:
7813 case Decl::TemplateTemplateParm:
7814 case Decl::TemplateTypeParm:
7815 case Decl::UnresolvedUsingTypename:
7816 case Decl::UnresolvedUsingValue:
7817 case Decl::Using:
7818 case Decl::UsingDirective:
7819 case Decl::UsingShadow:
7820 return CXLanguage_CPlusPlus;
7821 }
7822
7823 return CXLanguage_C;
7824}
7825
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007826static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7827 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007828 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007829
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007830 switch (D->getAvailability()) {
7831 case AR_Available:
7832 case AR_NotYetIntroduced:
7833 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007834 return getCursorAvailabilityForDecl(
7835 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007836 return CXAvailability_Available;
7837
7838 case AR_Deprecated:
7839 return CXAvailability_Deprecated;
7840
7841 case AR_Unavailable:
7842 return CXAvailability_NotAvailable;
7843 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007844
7845 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007846}
7847
Guy Benyei11169dd2012-12-18 14:30:41 +00007848enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7849 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007850 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7851 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007852
7853 return CXAvailability_Available;
7854}
7855
7856static CXVersion convertVersion(VersionTuple In) {
7857 CXVersion Out = { -1, -1, -1 };
7858 if (In.empty())
7859 return Out;
7860
7861 Out.Major = In.getMajor();
7862
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007863 Optional<unsigned> Minor = In.getMinor();
7864 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007865 Out.Minor = *Minor;
7866 else
7867 return Out;
7868
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007869 Optional<unsigned> Subminor = In.getSubminor();
7870 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007871 Out.Subminor = *Subminor;
7872
7873 return Out;
7874}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007875
Alex Lorenz1345ea22017-06-12 19:06:30 +00007876static void getCursorPlatformAvailabilityForDecl(
7877 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7878 int *always_unavailable, CXString *unavailable_message,
7879 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007880 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007881 for (auto A : D->attrs()) {
7882 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007883 HadAvailAttr = true;
7884 if (always_deprecated)
7885 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007886 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007887 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007888 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007889 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007890 continue;
7891 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007892
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007893 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007894 HadAvailAttr = true;
7895 if (always_unavailable)
7896 *always_unavailable = 1;
7897 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007898 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007899 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7900 }
7901 continue;
7902 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007903
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007904 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007905 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007906 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007907 }
7908 }
7909
7910 if (!HadAvailAttr)
7911 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7912 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007913 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7914 deprecated_message, always_unavailable, unavailable_message,
7915 AvailabilityAttrs);
7916
7917 if (AvailabilityAttrs.empty())
7918 return;
7919
Fangrui Song55fab262018-09-26 22:16:28 +00007920 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007921 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7922 return LHS->getPlatform()->getName() <
7923 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007924 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007925 ASTContext &Ctx = D->getASTContext();
7926 auto It = std::unique(
7927 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7928 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7929 if (LHS->getPlatform() != RHS->getPlatform())
7930 return false;
7931
7932 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7933 LHS->getDeprecated() == RHS->getDeprecated() &&
7934 LHS->getObsoleted() == RHS->getObsoleted() &&
7935 LHS->getMessage() == RHS->getMessage() &&
7936 LHS->getReplacement() == RHS->getReplacement())
7937 return true;
7938
7939 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7940 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7941 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7942 return false;
7943
7944 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7945 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7946
7947 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7948 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7949 if (LHS->getMessage().empty())
7950 LHS->setMessage(Ctx, RHS->getMessage());
7951 if (LHS->getReplacement().empty())
7952 LHS->setReplacement(Ctx, RHS->getReplacement());
7953 }
7954
7955 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7956 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7957 if (LHS->getMessage().empty())
7958 LHS->setMessage(Ctx, RHS->getMessage());
7959 if (LHS->getReplacement().empty())
7960 LHS->setReplacement(Ctx, RHS->getReplacement());
7961 }
7962
7963 return true;
7964 });
7965 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007966}
7967
Alex Lorenz1345ea22017-06-12 19:06:30 +00007968int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007969 CXString *deprecated_message,
7970 int *always_unavailable,
7971 CXString *unavailable_message,
7972 CXPlatformAvailability *availability,
7973 int availability_size) {
7974 if (always_deprecated)
7975 *always_deprecated = 0;
7976 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007977 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 if (always_unavailable)
7979 *always_unavailable = 0;
7980 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007981 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007982
Guy Benyei11169dd2012-12-18 14:30:41 +00007983 if (!clang_isDeclaration(cursor.kind))
7984 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007985
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007986 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007987 if (!D)
7988 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007989
Alex Lorenz1345ea22017-06-12 19:06:30 +00007990 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7991 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7992 always_unavailable, unavailable_message,
7993 AvailabilityAttrs);
7994 for (const auto &Avail :
7995 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7996 .take_front(availability_size))) {
7997 availability[Avail.index()].Platform =
7998 cxstring::createDup(Avail.value()->getPlatform()->getName());
7999 availability[Avail.index()].Introduced =
8000 convertVersion(Avail.value()->getIntroduced());
8001 availability[Avail.index()].Deprecated =
8002 convertVersion(Avail.value()->getDeprecated());
8003 availability[Avail.index()].Obsoleted =
8004 convertVersion(Avail.value()->getObsoleted());
8005 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
8006 availability[Avail.index()].Message =
8007 cxstring::createDup(Avail.value()->getMessage());
8008 }
8009
8010 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008011}
Alex Lorenz1345ea22017-06-12 19:06:30 +00008012
Guy Benyei11169dd2012-12-18 14:30:41 +00008013void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
8014 clang_disposeString(availability->Platform);
8015 clang_disposeString(availability->Message);
8016}
8017
8018CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
8019 if (clang_isDeclaration(cursor.kind))
8020 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
8021
8022 return CXLanguage_Invalid;
8023}
8024
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00008025CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
8026 const Decl *D = cxcursor::getCursorDecl(cursor);
8027 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8028 switch (VD->getTLSKind()) {
8029 case VarDecl::TLS_None:
8030 return CXTLS_None;
8031 case VarDecl::TLS_Dynamic:
8032 return CXTLS_Dynamic;
8033 case VarDecl::TLS_Static:
8034 return CXTLS_Static;
8035 }
8036 }
8037
8038 return CXTLS_None;
8039}
8040
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008041 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008042 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008043 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008044static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008045 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008046 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008047
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008048 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008049 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8050 return FunTmpl;
8051
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008052 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008053 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8054 return ClassTmpl;
8055
8056 return D;
8057}
8058
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008059
8060enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8061 StorageClass sc = SC_None;
8062 const Decl *D = getCursorDecl(C);
8063 if (D) {
8064 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8065 sc = FD->getStorageClass();
8066 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8067 sc = VD->getStorageClass();
8068 } else {
8069 return CX_SC_Invalid;
8070 }
8071 } else {
8072 return CX_SC_Invalid;
8073 }
8074 switch (sc) {
8075 case SC_None:
8076 return CX_SC_None;
8077 case SC_Extern:
8078 return CX_SC_Extern;
8079 case SC_Static:
8080 return CX_SC_Static;
8081 case SC_PrivateExtern:
8082 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008083 case SC_Auto:
8084 return CX_SC_Auto;
8085 case SC_Register:
8086 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008087 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008088 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008089}
8090
Guy Benyei11169dd2012-12-18 14:30:41 +00008091CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8092 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008093 if (const Decl *D = getCursorDecl(cursor)) {
8094 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008095 if (!DC)
8096 return clang_getNullCursor();
8097
8098 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8099 getCursorTU(cursor));
8100 }
8101 }
8102
8103 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008104 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008105 return MakeCXCursor(D, getCursorTU(cursor));
8106 }
8107
8108 return clang_getNullCursor();
8109}
8110
8111CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8112 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008113 if (const Decl *D = getCursorDecl(cursor)) {
8114 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008115 if (!DC)
8116 return clang_getNullCursor();
8117
8118 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8119 getCursorTU(cursor));
8120 }
8121 }
8122
8123 // FIXME: Note that we can't easily compute the lexical context of a
8124 // statement or expression, so we return nothing.
8125 return clang_getNullCursor();
8126}
8127
8128CXFile clang_getIncludedFile(CXCursor cursor) {
8129 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008130 return nullptr;
8131
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008132 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008133 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008134}
8135
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008136unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8137 if (C.kind != CXCursor_ObjCPropertyDecl)
8138 return CXObjCPropertyAttr_noattr;
8139
8140 unsigned Result = CXObjCPropertyAttr_noattr;
8141 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8142 ObjCPropertyDecl::PropertyAttributeKind Attr =
8143 PD->getPropertyAttributesAsWritten();
8144
8145#define SET_CXOBJCPROP_ATTR(A) \
8146 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8147 Result |= CXObjCPropertyAttr_##A
8148 SET_CXOBJCPROP_ATTR(readonly);
8149 SET_CXOBJCPROP_ATTR(getter);
8150 SET_CXOBJCPROP_ATTR(assign);
8151 SET_CXOBJCPROP_ATTR(readwrite);
8152 SET_CXOBJCPROP_ATTR(retain);
8153 SET_CXOBJCPROP_ATTR(copy);
8154 SET_CXOBJCPROP_ATTR(nonatomic);
8155 SET_CXOBJCPROP_ATTR(setter);
8156 SET_CXOBJCPROP_ATTR(atomic);
8157 SET_CXOBJCPROP_ATTR(weak);
8158 SET_CXOBJCPROP_ATTR(strong);
8159 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008160 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008161#undef SET_CXOBJCPROP_ATTR
8162
8163 return Result;
8164}
8165
Michael Wu6e88f532018-08-03 05:38:29 +00008166CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8167 if (C.kind != CXCursor_ObjCPropertyDecl)
8168 return cxstring::createNull();
8169
8170 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8171 Selector sel = PD->getGetterName();
8172 if (sel.isNull())
8173 return cxstring::createNull();
8174
8175 return cxstring::createDup(sel.getAsString());
8176}
8177
8178CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8179 if (C.kind != CXCursor_ObjCPropertyDecl)
8180 return cxstring::createNull();
8181
8182 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8183 Selector sel = PD->getSetterName();
8184 if (sel.isNull())
8185 return cxstring::createNull();
8186
8187 return cxstring::createDup(sel.getAsString());
8188}
8189
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008190unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8191 if (!clang_isDeclaration(C.kind))
8192 return CXObjCDeclQualifier_None;
8193
8194 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8195 const Decl *D = getCursorDecl(C);
8196 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8197 QT = MD->getObjCDeclQualifier();
8198 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8199 QT = PD->getObjCDeclQualifier();
8200 if (QT == Decl::OBJC_TQ_None)
8201 return CXObjCDeclQualifier_None;
8202
8203 unsigned Result = CXObjCDeclQualifier_None;
8204 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8205 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8206 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8207 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8208 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8209 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8210
8211 return Result;
8212}
8213
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008214unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8215 if (!clang_isDeclaration(C.kind))
8216 return 0;
8217
8218 const Decl *D = getCursorDecl(C);
8219 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8220 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8221 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8222 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8223
8224 return 0;
8225}
8226
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008227unsigned clang_Cursor_isVariadic(CXCursor C) {
8228 if (!clang_isDeclaration(C.kind))
8229 return 0;
8230
8231 const Decl *D = getCursorDecl(C);
8232 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8233 return FD->isVariadic();
8234 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8235 return MD->isVariadic();
8236
8237 return 0;
8238}
8239
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008240unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8241 CXString *language, CXString *definedIn,
8242 unsigned *isGenerated) {
8243 if (!clang_isDeclaration(C.kind))
8244 return 0;
8245
8246 const Decl *D = getCursorDecl(C);
8247
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008248 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008249 if (language)
8250 *language = cxstring::createDup(attr->getLanguage());
8251 if (definedIn)
8252 *definedIn = cxstring::createDup(attr->getDefinedIn());
8253 if (isGenerated)
8254 *isGenerated = attr->getGeneratedDeclaration();
8255 return 1;
8256 }
8257 return 0;
8258}
8259
Guy Benyei11169dd2012-12-18 14:30:41 +00008260CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8261 if (!clang_isDeclaration(C.kind))
8262 return clang_getNullRange();
8263
8264 const Decl *D = getCursorDecl(C);
8265 ASTContext &Context = getCursorContext(C);
8266 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8267 if (!RC)
8268 return clang_getNullRange();
8269
8270 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8271}
8272
8273CXString clang_Cursor_getRawCommentText(CXCursor C) {
8274 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008275 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008276
8277 const Decl *D = getCursorDecl(C);
8278 ASTContext &Context = getCursorContext(C);
8279 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8280 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8281 StringRef();
8282
8283 // Don't duplicate the string because RawText points directly into source
8284 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008285 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008286}
8287
8288CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8289 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008290 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008291
8292 const Decl *D = getCursorDecl(C);
8293 const ASTContext &Context = getCursorContext(C);
8294 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8295
8296 if (RC) {
8297 StringRef BriefText = RC->getBriefText(Context);
8298
8299 // Don't duplicate the string because RawComment ensures that this memory
8300 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008301 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008302 }
8303
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008304 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008305}
8306
Guy Benyei11169dd2012-12-18 14:30:41 +00008307CXModule clang_Cursor_getModule(CXCursor C) {
8308 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008309 if (const ImportDecl *ImportD =
8310 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008311 return ImportD->getImportedModule();
8312 }
8313
Craig Topper69186e72014-06-08 08:38:04 +00008314 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008315}
8316
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008317CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8318 if (isNotUsableTU(TU)) {
8319 LOG_BAD_TU(TU);
8320 return nullptr;
8321 }
8322 if (!File)
8323 return nullptr;
8324 FileEntry *FE = static_cast<FileEntry *>(File);
8325
8326 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8327 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8328 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8329
Richard Smithfeb54b62014-10-23 02:01:19 +00008330 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008331}
8332
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008333CXFile clang_Module_getASTFile(CXModule CXMod) {
8334 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008335 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008336 Module *Mod = static_cast<Module*>(CXMod);
8337 return const_cast<FileEntry *>(Mod->getASTFile());
8338}
8339
Guy Benyei11169dd2012-12-18 14:30:41 +00008340CXModule clang_Module_getParent(CXModule CXMod) {
8341 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008342 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008343 Module *Mod = static_cast<Module*>(CXMod);
8344 return Mod->Parent;
8345}
8346
8347CXString clang_Module_getName(CXModule CXMod) {
8348 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008349 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008350 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008351 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008352}
8353
8354CXString clang_Module_getFullName(CXModule CXMod) {
8355 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008356 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008357 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008358 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008359}
8360
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008361int clang_Module_isSystem(CXModule CXMod) {
8362 if (!CXMod)
8363 return 0;
8364 Module *Mod = static_cast<Module*>(CXMod);
8365 return Mod->IsSystem;
8366}
8367
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008368unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8369 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008370 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008371 LOG_BAD_TU(TU);
8372 return 0;
8373 }
8374 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008375 return 0;
8376 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008377 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8378 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8379 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008380}
8381
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008382CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8383 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008384 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008385 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008386 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008387 }
8388 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008389 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008390 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008391 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008392
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008393 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8394 if (Index < TopHeaders.size())
8395 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008396
Craig Topper69186e72014-06-08 08:38:04 +00008397 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008398}
8399
Guy Benyei11169dd2012-12-18 14:30:41 +00008400//===----------------------------------------------------------------------===//
8401// C++ AST instrospection.
8402//===----------------------------------------------------------------------===//
8403
Jonathan Coe29565352016-04-27 12:48:25 +00008404unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8405 if (!clang_isDeclaration(C.kind))
8406 return 0;
8407
8408 const Decl *D = cxcursor::getCursorDecl(C);
8409 const CXXConstructorDecl *Constructor =
8410 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8411 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8412}
8413
8414unsigned clang_CXXConstructor_isCopyConstructor(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->isCopyConstructor()) ? 1 : 0;
8422}
8423
8424unsigned clang_CXXConstructor_isMoveConstructor(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->isMoveConstructor()) ? 1 : 0;
8432}
8433
8434unsigned clang_CXXConstructor_isConvertingConstructor(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 // Passing 'false' excludes constructors marked 'explicit'.
8442 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8443}
8444
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008445unsigned clang_CXXField_isMutable(CXCursor C) {
8446 if (!clang_isDeclaration(C.kind))
8447 return 0;
8448
8449 if (const auto D = cxcursor::getCursorDecl(C))
8450 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8451 return FD->isMutable() ? 1 : 0;
8452 return 0;
8453}
8454
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008455unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8456 if (!clang_isDeclaration(C.kind))
8457 return 0;
8458
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008459 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008460 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008461 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008462 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8463}
8464
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008465unsigned clang_CXXMethod_isConst(CXCursor C) {
8466 if (!clang_isDeclaration(C.kind))
8467 return 0;
8468
8469 const Decl *D = cxcursor::getCursorDecl(C);
8470 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008471 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008472 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008473}
8474
Jonathan Coe29565352016-04-27 12:48:25 +00008475unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8476 if (!clang_isDeclaration(C.kind))
8477 return 0;
8478
8479 const Decl *D = cxcursor::getCursorDecl(C);
8480 const CXXMethodDecl *Method =
8481 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8482 return (Method && Method->isDefaulted()) ? 1 : 0;
8483}
8484
Guy Benyei11169dd2012-12-18 14:30:41 +00008485unsigned clang_CXXMethod_isStatic(CXCursor C) {
8486 if (!clang_isDeclaration(C.kind))
8487 return 0;
8488
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008489 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008490 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008491 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008492 return (Method && Method->isStatic()) ? 1 : 0;
8493}
8494
8495unsigned clang_CXXMethod_isVirtual(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->isVirtual()) ? 1 : 0;
8503}
Guy Benyei11169dd2012-12-18 14:30:41 +00008504
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008505unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8506 if (!clang_isDeclaration(C.kind))
8507 return 0;
8508
8509 const auto *D = cxcursor::getCursorDecl(C);
8510 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8511 if (RD)
8512 RD = RD->getDefinition();
8513 return (RD && RD->isAbstract()) ? 1 : 0;
8514}
8515
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008516unsigned clang_EnumDecl_isScoped(CXCursor C) {
8517 if (!clang_isDeclaration(C.kind))
8518 return 0;
8519
8520 const Decl *D = cxcursor::getCursorDecl(C);
8521 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8522 return (Enum && Enum->isScoped()) ? 1 : 0;
8523}
8524
Guy Benyei11169dd2012-12-18 14:30:41 +00008525//===----------------------------------------------------------------------===//
8526// Attribute introspection.
8527//===----------------------------------------------------------------------===//
8528
Guy Benyei11169dd2012-12-18 14:30:41 +00008529CXType clang_getIBOutletCollectionType(CXCursor C) {
8530 if (C.kind != CXCursor_IBOutletCollectionAttr)
8531 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8532
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008533 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008534 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8535
8536 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8537}
Guy Benyei11169dd2012-12-18 14:30:41 +00008538
8539//===----------------------------------------------------------------------===//
8540// Inspecting memory usage.
8541//===----------------------------------------------------------------------===//
8542
8543typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8544
8545static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8546 enum CXTUResourceUsageKind k,
8547 unsigned long amount) {
8548 CXTUResourceUsageEntry entry = { k, amount };
8549 entries.push_back(entry);
8550}
8551
Guy Benyei11169dd2012-12-18 14:30:41 +00008552const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8553 const char *str = "";
8554 switch (kind) {
8555 case CXTUResourceUsage_AST:
8556 str = "ASTContext: expressions, declarations, and types";
8557 break;
8558 case CXTUResourceUsage_Identifiers:
8559 str = "ASTContext: identifiers";
8560 break;
8561 case CXTUResourceUsage_Selectors:
8562 str = "ASTContext: selectors";
8563 break;
8564 case CXTUResourceUsage_GlobalCompletionResults:
8565 str = "Code completion: cached global results";
8566 break;
8567 case CXTUResourceUsage_SourceManagerContentCache:
8568 str = "SourceManager: content cache allocator";
8569 break;
8570 case CXTUResourceUsage_AST_SideTables:
8571 str = "ASTContext: side tables";
8572 break;
8573 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8574 str = "SourceManager: malloc'ed memory buffers";
8575 break;
8576 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8577 str = "SourceManager: mmap'ed memory buffers";
8578 break;
8579 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8580 str = "ExternalASTSource: malloc'ed memory buffers";
8581 break;
8582 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8583 str = "ExternalASTSource: mmap'ed memory buffers";
8584 break;
8585 case CXTUResourceUsage_Preprocessor:
8586 str = "Preprocessor: malloc'ed memory";
8587 break;
8588 case CXTUResourceUsage_PreprocessingRecord:
8589 str = "Preprocessor: PreprocessingRecord";
8590 break;
8591 case CXTUResourceUsage_SourceManager_DataStructures:
8592 str = "SourceManager: data structures and tables";
8593 break;
8594 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8595 str = "Preprocessor: header search tables";
8596 break;
8597 }
8598 return str;
8599}
8600
8601CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008602 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008603 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008604 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008605 return usage;
8606 }
8607
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008608 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008609 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008610 ASTContext &astContext = astUnit->getASTContext();
8611
8612 // How much memory is used by AST nodes and types?
8613 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8614 (unsigned long) astContext.getASTAllocatedMemory());
8615
8616 // How much memory is used by identifiers?
8617 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8618 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8619
8620 // How much memory is used for selectors?
8621 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8622 (unsigned long) astContext.Selectors.getTotalMemory());
8623
8624 // How much memory is used by ASTContext's side tables?
8625 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8626 (unsigned long) astContext.getSideTableAllocatedMemory());
8627
8628 // How much memory is used for caching global code completion results?
8629 unsigned long completionBytes = 0;
8630 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008631 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008632 completionBytes = completionAllocator->getTotalMemory();
8633 }
8634 createCXTUResourceUsageEntry(*entries,
8635 CXTUResourceUsage_GlobalCompletionResults,
8636 completionBytes);
8637
8638 // How much memory is being used by SourceManager's content cache?
8639 createCXTUResourceUsageEntry(*entries,
8640 CXTUResourceUsage_SourceManagerContentCache,
8641 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8642
8643 // How much memory is being used by the MemoryBuffer's in SourceManager?
8644 const SourceManager::MemoryBufferSizes &srcBufs =
8645 astUnit->getSourceManager().getMemoryBufferSizes();
8646
8647 createCXTUResourceUsageEntry(*entries,
8648 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8649 (unsigned long) srcBufs.malloc_bytes);
8650 createCXTUResourceUsageEntry(*entries,
8651 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8652 (unsigned long) srcBufs.mmap_bytes);
8653 createCXTUResourceUsageEntry(*entries,
8654 CXTUResourceUsage_SourceManager_DataStructures,
8655 (unsigned long) astContext.getSourceManager()
8656 .getDataStructureSizes());
8657
8658 // How much memory is being used by the ExternalASTSource?
8659 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8660 const ExternalASTSource::MemoryBufferSizes &sizes =
8661 esrc->getMemoryBufferSizes();
8662
8663 createCXTUResourceUsageEntry(*entries,
8664 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8665 (unsigned long) sizes.malloc_bytes);
8666 createCXTUResourceUsageEntry(*entries,
8667 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8668 (unsigned long) sizes.mmap_bytes);
8669 }
8670
8671 // How much memory is being used by the Preprocessor?
8672 Preprocessor &pp = astUnit->getPreprocessor();
8673 createCXTUResourceUsageEntry(*entries,
8674 CXTUResourceUsage_Preprocessor,
8675 pp.getTotalMemory());
8676
8677 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8678 createCXTUResourceUsageEntry(*entries,
8679 CXTUResourceUsage_PreprocessingRecord,
8680 pRec->getTotalMemory());
8681 }
8682
8683 createCXTUResourceUsageEntry(*entries,
8684 CXTUResourceUsage_Preprocessor_HeaderSearch,
8685 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008686
Guy Benyei11169dd2012-12-18 14:30:41 +00008687 CXTUResourceUsage usage = { (void*) entries.get(),
8688 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008689 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008690 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008691 return usage;
8692}
8693
8694void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8695 if (usage.data)
8696 delete (MemUsageEntries*) usage.data;
8697}
8698
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008699CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8700 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008701 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008702 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008703
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008704 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008705 LOG_BAD_TU(TU);
8706 return skipped;
8707 }
8708
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008709 if (!file)
8710 return skipped;
8711
8712 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8713 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8714 if (!ppRec)
8715 return skipped;
8716
8717 ASTContext &Ctx = astUnit->getASTContext();
8718 SourceManager &sm = Ctx.getSourceManager();
8719 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8720 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008721 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008722
8723 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8724 std::vector<SourceRange> wantedRanges;
8725 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8726 i != ei; ++i) {
8727 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8728 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008729 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8730 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008731 }
8732
8733 skipped->count = wantedRanges.size();
8734 skipped->ranges = new CXSourceRange[skipped->count];
8735 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8736 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8737
8738 return skipped;
8739}
8740
Cameron Desrochersd8091282016-08-18 15:43:55 +00008741CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8742 CXSourceRangeList *skipped = new CXSourceRangeList;
8743 skipped->count = 0;
8744 skipped->ranges = nullptr;
8745
8746 if (isNotUsableTU(TU)) {
8747 LOG_BAD_TU(TU);
8748 return skipped;
8749 }
8750
8751 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8752 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8753 if (!ppRec)
8754 return skipped;
8755
8756 ASTContext &Ctx = astUnit->getASTContext();
8757
8758 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8759
8760 skipped->count = SkippedRanges.size();
8761 skipped->ranges = new CXSourceRange[skipped->count];
8762 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8763 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8764
8765 return skipped;
8766}
8767
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008768void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8769 if (ranges) {
8770 delete[] ranges->ranges;
8771 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008772 }
8773}
8774
Guy Benyei11169dd2012-12-18 14:30:41 +00008775void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8776 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8777 for (unsigned I = 0; I != Usage.numEntries; ++I)
8778 fprintf(stderr, " %s: %lu\n",
8779 clang_getTUResourceUsageName(Usage.entries[I].kind),
8780 Usage.entries[I].amount);
8781
8782 clang_disposeCXTUResourceUsage(Usage);
8783}
8784
8785//===----------------------------------------------------------------------===//
8786// Misc. utility functions.
8787//===----------------------------------------------------------------------===//
8788
Richard Smith0a7b2972018-07-03 21:34:13 +00008789/// Default to using our desired 8 MB stack size on "safety" threads.
8790static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008791
8792namespace clang {
8793
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008794bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008795 unsigned Size) {
8796 if (!Size)
8797 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008798 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008799 return CRC.RunSafelyOnThread(Fn, Size);
8800 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008801}
8802
8803unsigned GetSafetyThreadStackSize() {
8804 return SafetyStackThreadSize;
8805}
8806
8807void SetSafetyThreadStackSize(unsigned Value) {
8808 SafetyStackThreadSize = Value;
8809}
8810
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008811}
Guy Benyei11169dd2012-12-18 14:30:41 +00008812
8813void clang::setThreadBackgroundPriority() {
8814 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8815 return;
8816
Nico Weber18cfd9f2019-04-21 19:18:41 +00008817#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008818 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008819#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008820}
8821
8822void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8823 if (!Unit)
8824 return;
8825
8826 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8827 DEnd = Unit->stored_diag_end();
8828 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008829 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008830 CXString Msg = clang_formatDiagnostic(&Diag,
8831 clang_defaultDiagnosticDisplayOptions());
8832 fprintf(stderr, "%s\n", clang_getCString(Msg));
8833 clang_disposeString(Msg);
8834 }
Nico Weber1865df42018-04-27 19:11:14 +00008835#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008836 // On Windows, force a flush, since there may be multiple copies of
8837 // stderr and stdout in the file system, all with different buffers
8838 // but writing to the same device.
8839 fflush(stderr);
8840#endif
8841}
8842
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008843MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8844 SourceLocation MacroDefLoc,
8845 CXTranslationUnit TU){
8846 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008847 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008848 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008849 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008850
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008851 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008852 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008853 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008854 if (MD) {
8855 for (MacroDirective::DefInfo
8856 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8857 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8858 return Def.getMacroInfo();
8859 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008860 }
8861
Craig Topper69186e72014-06-08 08:38:04 +00008862 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008863}
8864
Richard Smith66a81862015-05-04 02:25:31 +00008865const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008866 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008867 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008868 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008869 const IdentifierInfo *II = MacroDef->getName();
8870 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008871 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008872
8873 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8874}
8875
Richard Smith66a81862015-05-04 02:25:31 +00008876MacroDefinitionRecord *
8877cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8878 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008879 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008880 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008881 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008882 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008883
8884 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008885 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008886 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8887 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008888 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008889
8890 // Check that the token is inside the definition and not its argument list.
8891 SourceManager &SM = Unit->getSourceManager();
8892 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008893 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008894 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008895 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008896
8897 Preprocessor &PP = Unit->getPreprocessor();
8898 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8899 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008900 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008901
Alp Toker2d57cea2014-05-17 04:53:25 +00008902 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008903 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008904 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008905
8906 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008907 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008908 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008909
Richard Smith20e883e2015-04-29 23:20:19 +00008910 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008911 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008912 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008913
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008914 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008915}
8916
Richard Smith66a81862015-05-04 02:25:31 +00008917MacroDefinitionRecord *
8918cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8919 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008920 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008921 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008922
8923 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008924 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008925 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008926 Preprocessor &PP = Unit->getPreprocessor();
8927 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008928 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008929 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8930 Token Tok;
8931 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008932 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008933
8934 return checkForMacroInMacroDefinition(MI, Tok, TU);
8935}
8936
Guy Benyei11169dd2012-12-18 14:30:41 +00008937CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008938 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008939}
8940
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008941Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8942 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008943 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008944 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008945 if (Unit->isMainFileAST())
8946 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008947 return *this;
8948 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008949 } else {
8950 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008951 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008952 return *this;
8953}
8954
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008955Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8956 *this << FE->getName();
8957 return *this;
8958}
8959
8960Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8961 CXString cursorName = clang_getCursorDisplayName(cursor);
8962 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8963 clang_disposeString(cursorName);
8964 return *this;
8965}
8966
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008967Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8968 CXFile File;
8969 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008970 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008971 CXString FileName = clang_getFileName(File);
8972 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8973 clang_disposeString(FileName);
8974 return *this;
8975}
8976
8977Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8978 CXSourceLocation BLoc = clang_getRangeStart(range);
8979 CXSourceLocation ELoc = clang_getRangeEnd(range);
8980
8981 CXFile BFile;
8982 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008983 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008984
8985 CXFile EFile;
8986 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008987 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008988
8989 CXString BFileName = clang_getFileName(BFile);
8990 if (BFile == EFile) {
8991 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8992 BLine, BColumn, ELine, EColumn);
8993 } else {
8994 CXString EFileName = clang_getFileName(EFile);
8995 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8996 BLine, BColumn)
8997 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8998 ELine, EColumn);
8999 clang_disposeString(EFileName);
9000 }
9001 clang_disposeString(BFileName);
9002 return *this;
9003}
9004
9005Logger &cxindex::Logger::operator<<(CXString Str) {
9006 *this << clang_getCString(Str);
9007 return *this;
9008}
9009
9010Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
9011 LogOS << Fmt;
9012 return *this;
9013}
9014
Benjamin Kramer762bc332019-08-07 14:44:40 +00009015static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00009016
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009017cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00009018 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009019
9020 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
9021
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009022 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009023 OS << "[libclang:" << Name << ':';
9024
Alp Toker1a86ad22014-07-06 06:24:00 +00009025#ifdef USE_DARWIN_THREADS
9026 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009027 mach_port_t tid = pthread_mach_thread_np(pthread_self());
9028 OS << tid << ':';
9029#endif
9030
9031 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
9032 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00009033 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009034
9035 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00009036 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009037 OS << "--------------------------------------------------\n";
9038 }
9039}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00009040
9041#ifdef CLANG_TOOL_EXTRA_BUILD
9042// This anchor is used to force the linker to link the clang-tidy plugin.
9043extern volatile int ClangTidyPluginAnchorSource;
9044static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9045 ClangTidyPluginAnchorSource;
9046
9047// This anchor is used to force the linker to link the clang-include-fixer
9048// plugin.
9049extern volatile int ClangIncludeFixerPluginAnchorSource;
9050static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9051 ClangIncludeFixerPluginAnchorSource;
9052#endif