blob: 95cb517fa3328140e86547decee2e3a90c7996fe [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 Bataevea9166b2020-02-06 16:30:23 -05002237void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
2238
Alexey Bataev346265e2015-09-25 10:37:12 +00002239void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2240
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002241void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2242
Alexey Bataevb825de12015-12-07 10:51:44 +00002243void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2244
Kelvin Li1408f912018-09-26 04:28:39 +00002245void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2246 const OMPUnifiedAddressClause *) {}
2247
Patrick Lyster4a370b92018-10-01 13:47:43 +00002248void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2249 const OMPUnifiedSharedMemoryClause *) {}
2250
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002251void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2252 const OMPReverseOffloadClause *) {}
2253
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002254void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2255 const OMPDynamicAllocatorsClause *) {}
2256
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002257void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2258 const OMPAtomicDefaultMemOrderClause *) {}
2259
Michael Wonge710d542015-08-07 16:16:36 +00002260void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2261 Visitor->AddStmt(C->getDevice());
2262}
2263
Kelvin Li099bb8c2015-11-24 20:50:12 +00002264void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002265 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002266 Visitor->AddStmt(C->getNumTeams());
2267}
2268
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002269void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002270 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002271 Visitor->AddStmt(C->getThreadLimit());
2272}
2273
Alexey Bataeva0569352015-12-01 10:17:31 +00002274void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2275 Visitor->AddStmt(C->getPriority());
2276}
2277
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002278void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2279 Visitor->AddStmt(C->getGrainsize());
2280}
2281
Alexey Bataev382967a2015-12-08 12:06:20 +00002282void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2283 Visitor->AddStmt(C->getNumTasks());
2284}
2285
Alexey Bataev28c75412015-12-15 08:19:24 +00002286void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2287 Visitor->AddStmt(C->getHint());
2288}
2289
Alexey Bataev756c1962013-09-24 03:17:45 +00002290template<typename T>
2291void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002292 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002293 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002294 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002295}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002296
Alexey Bataeve04483e2019-03-27 14:14:31 +00002297void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2298 VisitOMPClauseList(C);
2299 Visitor->AddStmt(C->getAllocator());
2300}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002301void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002302 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002303 for (const auto *E : C->private_copies()) {
2304 Visitor->AddStmt(E);
2305 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002306}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002307void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2308 const OMPFirstprivateClause *C) {
2309 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002310 VisitOMPClauseWithPreInit(C);
2311 for (const auto *E : C->private_copies()) {
2312 Visitor->AddStmt(E);
2313 }
2314 for (const auto *E : C->inits()) {
2315 Visitor->AddStmt(E);
2316 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002317}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002318void OMPClauseEnqueue::VisitOMPLastprivateClause(
2319 const OMPLastprivateClause *C) {
2320 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002321 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002322 for (auto *E : C->private_copies()) {
2323 Visitor->AddStmt(E);
2324 }
2325 for (auto *E : C->source_exprs()) {
2326 Visitor->AddStmt(E);
2327 }
2328 for (auto *E : C->destination_exprs()) {
2329 Visitor->AddStmt(E);
2330 }
2331 for (auto *E : C->assignment_ops()) {
2332 Visitor->AddStmt(E);
2333 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002334}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002335void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002336 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002337}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002338void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2339 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002340 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002341 for (auto *E : C->privates()) {
2342 Visitor->AddStmt(E);
2343 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002344 for (auto *E : C->lhs_exprs()) {
2345 Visitor->AddStmt(E);
2346 }
2347 for (auto *E : C->rhs_exprs()) {
2348 Visitor->AddStmt(E);
2349 }
2350 for (auto *E : C->reduction_ops()) {
2351 Visitor->AddStmt(E);
2352 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002353}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002354void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2355 const OMPTaskReductionClause *C) {
2356 VisitOMPClauseList(C);
2357 VisitOMPClauseWithPostUpdate(C);
2358 for (auto *E : C->privates()) {
2359 Visitor->AddStmt(E);
2360 }
2361 for (auto *E : C->lhs_exprs()) {
2362 Visitor->AddStmt(E);
2363 }
2364 for (auto *E : C->rhs_exprs()) {
2365 Visitor->AddStmt(E);
2366 }
2367 for (auto *E : C->reduction_ops()) {
2368 Visitor->AddStmt(E);
2369 }
2370}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002371void OMPClauseEnqueue::VisitOMPInReductionClause(
2372 const OMPInReductionClause *C) {
2373 VisitOMPClauseList(C);
2374 VisitOMPClauseWithPostUpdate(C);
2375 for (auto *E : C->privates()) {
2376 Visitor->AddStmt(E);
2377 }
2378 for (auto *E : C->lhs_exprs()) {
2379 Visitor->AddStmt(E);
2380 }
2381 for (auto *E : C->rhs_exprs()) {
2382 Visitor->AddStmt(E);
2383 }
2384 for (auto *E : C->reduction_ops()) {
2385 Visitor->AddStmt(E);
2386 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002387 for (auto *E : C->taskgroup_descriptors())
2388 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002389}
Alexander Musman8dba6642014-04-22 13:09:42 +00002390void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2391 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002392 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002393 for (const auto *E : C->privates()) {
2394 Visitor->AddStmt(E);
2395 }
Alexander Musman3276a272015-03-21 10:12:56 +00002396 for (const auto *E : C->inits()) {
2397 Visitor->AddStmt(E);
2398 }
2399 for (const auto *E : C->updates()) {
2400 Visitor->AddStmt(E);
2401 }
2402 for (const auto *E : C->finals()) {
2403 Visitor->AddStmt(E);
2404 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002405 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002406 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002407}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002408void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2409 VisitOMPClauseList(C);
2410 Visitor->AddStmt(C->getAlignment());
2411}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002412void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2413 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002414 for (auto *E : C->source_exprs()) {
2415 Visitor->AddStmt(E);
2416 }
2417 for (auto *E : C->destination_exprs()) {
2418 Visitor->AddStmt(E);
2419 }
2420 for (auto *E : C->assignment_ops()) {
2421 Visitor->AddStmt(E);
2422 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002423}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002424void
2425OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2426 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002427 for (auto *E : C->source_exprs()) {
2428 Visitor->AddStmt(E);
2429 }
2430 for (auto *E : C->destination_exprs()) {
2431 Visitor->AddStmt(E);
2432 }
2433 for (auto *E : C->assignment_ops()) {
2434 Visitor->AddStmt(E);
2435 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002436}
Alexey Bataev6125da92014-07-21 11:26:11 +00002437void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2438 VisitOMPClauseList(C);
2439}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002440void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2441 VisitOMPClauseList(C);
2442}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002443void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2444 VisitOMPClauseList(C);
2445}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002446void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2447 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002448 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002449 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002450}
Alexey Bataev3392d762016-02-16 11:18:12 +00002451void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2452 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002453void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2454 VisitOMPClauseList(C);
2455}
Samuel Antaoec172c62016-05-26 17:49:04 +00002456void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2457 VisitOMPClauseList(C);
2458}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002459void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2460 VisitOMPClauseList(C);
2461}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002462void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2463 VisitOMPClauseList(C);
2464}
Alexey Bataevb6e70842019-12-16 15:54:17 -05002465void OMPClauseEnqueue::VisitOMPNontemporalClause(
2466 const OMPNontemporalClause *C) {
2467 VisitOMPClauseList(C);
Alexey Bataev0860db92019-12-19 10:01:10 -05002468 for (const auto *E : C->private_refs())
2469 Visitor->AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05002470}
Alexey Bataevcb8e6912020-01-31 16:09:26 -05002471void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002472}
Alexey Bataev756c1962013-09-24 03:17:45 +00002473
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002474void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2475 unsigned size = WL.size();
2476 OMPClauseEnqueue Visitor(this);
2477 Visitor.Visit(S);
2478 if (size == WL.size())
2479 return;
2480 // Now reverse the entries we just added. This will match the DFS
2481 // ordering performed by the worklist.
2482 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2483 std::reverse(I, E);
2484}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002485void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2487}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002488void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 AddDecl(B->getBlockDecl());
2490}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002491void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 EnqueueChildren(E);
2493 AddTypeLoc(E->getTypeSourceInfo());
2494}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002495void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002496 for (auto &I : llvm::reverse(S->body()))
2497 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002498}
2499void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002500VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 AddStmt(S->getSubStmt());
2502 AddDeclarationNameInfo(S);
2503 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2504 AddNestedNameSpecifierLoc(QualifierLoc);
2505}
2506
2507void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002508VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002509 if (E->hasExplicitTemplateArgs())
2510 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 AddDeclarationNameInfo(E);
2512 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2513 AddNestedNameSpecifierLoc(QualifierLoc);
2514 if (!E->isImplicitAccess())
2515 AddStmt(E->getBase());
2516}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002517void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 // Enqueue the initializer , if any.
2519 AddStmt(E->getInitializer());
2520 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002521 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 // Enqueue the allocated type.
2523 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2524 // Enqueue the placement arguments.
2525 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2526 AddStmt(E->getPlacementArg(I-1));
2527}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002528void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2530 AddStmt(CE->getArg(I-1));
2531 AddStmt(CE->getCallee());
2532 AddStmt(CE->getArg(0));
2533}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2535 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 // Visit the name of the type being destroyed.
2537 AddTypeLoc(E->getDestroyedTypeInfo());
2538 // Visit the scope type that looks disturbingly like the nested-name-specifier
2539 // but isn't.
2540 AddTypeLoc(E->getScopeTypeInfo());
2541 // Visit the nested-name-specifier.
2542 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2543 AddNestedNameSpecifierLoc(QualifierLoc);
2544 // Visit base expression.
2545 AddStmt(E->getBase());
2546}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002547void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2548 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 AddTypeLoc(E->getTypeSourceInfo());
2550}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002551void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2552 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 EnqueueChildren(E);
2554 AddTypeLoc(E->getTypeSourceInfo());
2555}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002556void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 EnqueueChildren(E);
2558 if (E->isTypeOperand())
2559 AddTypeLoc(E->getTypeOperandSourceInfo());
2560}
2561
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002562void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2563 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 EnqueueChildren(E);
2565 AddTypeLoc(E->getTypeSourceInfo());
2566}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002567void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 EnqueueChildren(E);
2569 if (E->isTypeOperand())
2570 AddTypeLoc(E->getTypeOperandSourceInfo());
2571}
2572
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002573void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 EnqueueChildren(S);
2575 AddDecl(S->getExceptionDecl());
2576}
2577
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002578void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002579 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002580 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002581 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002582}
2583
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002584void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002585 if (DR->hasExplicitTemplateArgs())
2586 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 WL.push_back(DeclRefExprParts(DR, Parent));
2588}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002589void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2590 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002591 if (E->hasExplicitTemplateArgs())
2592 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002593 AddDeclarationNameInfo(E);
2594 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2595}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002596void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 unsigned size = WL.size();
2598 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002599 for (const auto *D : S->decls()) {
2600 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 isFirst = false;
2602 }
2603 if (size == WL.size())
2604 return;
2605 // Now reverse the entries we just added. This will match the DFS
2606 // ordering performed by the worklist.
2607 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2608 std::reverse(I, E);
2609}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002610void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002612 for (const DesignatedInitExpr::Designator &D :
2613 llvm::reverse(E->designators())) {
2614 if (D.isFieldDesignator()) {
2615 if (FieldDecl *Field = D.getField())
2616 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 continue;
2618 }
David Majnemerf7e36092016-06-23 00:15:04 +00002619 if (D.isArrayDesignator()) {
2620 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 continue;
2622 }
David Majnemerf7e36092016-06-23 00:15:04 +00002623 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2624 AddStmt(E->getArrayRangeEnd(D));
2625 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 }
2627}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002628void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 EnqueueChildren(E);
2630 AddTypeLoc(E->getTypeInfoAsWritten());
2631}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002632void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 AddStmt(FS->getBody());
2634 AddStmt(FS->getInc());
2635 AddStmt(FS->getCond());
2636 AddDecl(FS->getConditionVariable());
2637 AddStmt(FS->getInit());
2638}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002639void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2641}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002642void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 AddStmt(If->getElse());
2644 AddStmt(If->getThen());
2645 AddStmt(If->getCond());
2646 AddDecl(If->getConditionVariable());
2647}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002648void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 // We care about the syntactic form of the initializer list, only.
2650 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2651 IE = Syntactic;
2652 EnqueueChildren(IE);
2653}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002654void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 WL.push_back(MemberExprParts(M, Parent));
2656
2657 // If the base of the member access expression is an implicit 'this', don't
2658 // visit it.
2659 // FIXME: If we ever want to show these implicit accesses, this will be
2660 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002661 if (M->isImplicitAccess())
2662 return;
2663
2664 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002665 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002666 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2667 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2668 if (FD->isAnonymousStructOrUnion()) {
2669 AddStmt(SubME->getBase());
2670 return;
2671 }
2672 }
2673 }
2674
2675 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002676}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002677void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 AddTypeLoc(E->getEncodedTypeSourceInfo());
2679}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002680void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 EnqueueChildren(M);
2682 AddTypeLoc(M->getClassReceiverTypeInfo());
2683}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002684void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 // Visit the components of the offsetof expression.
2686 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 const OffsetOfNode &Node = E->getComponent(I-1);
2688 switch (Node.getKind()) {
2689 case OffsetOfNode::Array:
2690 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2691 break;
2692 case OffsetOfNode::Field:
2693 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2694 break;
2695 case OffsetOfNode::Identifier:
2696 case OffsetOfNode::Base:
2697 continue;
2698 }
2699 }
2700 // Visit the type into which we're computing the offset.
2701 AddTypeLoc(E->getTypeSourceInfo());
2702}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002703void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002704 if (E->hasExplicitTemplateArgs())
2705 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 WL.push_back(OverloadExprParts(E, Parent));
2707}
2708void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002709 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 EnqueueChildren(E);
2711 if (E->isArgumentType())
2712 AddTypeLoc(E->getArgumentTypeInfo());
2713}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002714void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 EnqueueChildren(S);
2716}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002717void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 AddStmt(S->getBody());
2719 AddStmt(S->getCond());
2720 AddDecl(S->getConditionVariable());
2721}
2722
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002723void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 AddStmt(W->getBody());
2725 AddStmt(W->getCond());
2726 AddDecl(W->getConditionVariable());
2727}
2728
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002729void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 for (unsigned I = E->getNumArgs(); I > 0; --I)
2731 AddTypeLoc(E->getArg(I-1));
2732}
2733
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002734void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 AddTypeLoc(E->getQueriedTypeSourceInfo());
2736}
2737
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002738void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 EnqueueChildren(E);
2740}
2741
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002742void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 VisitOverloadExpr(U);
2744 if (!U->isImplicitAccess())
2745 AddStmt(U->getBase());
2746}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002747void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 AddStmt(E->getSubExpr());
2749 AddTypeLoc(E->getWrittenTypeInfo());
2750}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002751void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 WL.push_back(SizeOfPackExprParts(E, Parent));
2753}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002754void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 // If the opaque value has a source expression, just transparently
2756 // visit that. This is useful for (e.g.) pseudo-object expressions.
2757 if (Expr *SourceExpr = E->getSourceExpr())
2758 return Visit(SourceExpr);
2759}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002760void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 AddStmt(E->getBody());
2762 WL.push_back(LambdaExprParts(E, Parent));
2763}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002764void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 // Treat the expression like its syntactic form.
2766 Visit(E->getSyntacticForm());
2767}
2768
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002769void EnqueueVisitor::VisitOMPExecutableDirective(
2770 const OMPExecutableDirective *D) {
2771 EnqueueChildren(D);
2772 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2773 E = D->clauses().end();
2774 I != E; ++I)
2775 EnqueueChildren(*I);
2776}
2777
Alexander Musman3aaab662014-08-19 11:27:13 +00002778void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2779 VisitOMPExecutableDirective(D);
2780}
2781
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002782void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2783 VisitOMPExecutableDirective(D);
2784}
2785
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002786void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002787 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002788}
2789
Alexey Bataevf29276e2014-06-18 04:14:57 +00002790void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002791 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002792}
2793
Alexander Musmanf82886e2014-09-18 05:12:34 +00002794void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2795 VisitOMPLoopDirective(D);
2796}
2797
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002798void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2799 VisitOMPExecutableDirective(D);
2800}
2801
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002802void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2803 VisitOMPExecutableDirective(D);
2804}
2805
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002806void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2807 VisitOMPExecutableDirective(D);
2808}
2809
Alexander Musman80c22892014-07-17 08:54:58 +00002810void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2811 VisitOMPExecutableDirective(D);
2812}
2813
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002814void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2815 VisitOMPExecutableDirective(D);
2816 AddDeclarationNameInfo(D);
2817}
2818
Alexey Bataev4acb8592014-07-07 13:01:15 +00002819void
2820EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002821 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002822}
2823
Alexander Musmane4e893b2014-09-23 09:33:00 +00002824void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2825 const OMPParallelForSimdDirective *D) {
2826 VisitOMPLoopDirective(D);
2827}
2828
cchen47d60942019-12-05 13:43:48 -05002829void EnqueueVisitor::VisitOMPParallelMasterDirective(
2830 const OMPParallelMasterDirective *D) {
2831 VisitOMPExecutableDirective(D);
2832}
2833
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002834void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2835 const OMPParallelSectionsDirective *D) {
2836 VisitOMPExecutableDirective(D);
2837}
2838
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002839void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2840 VisitOMPExecutableDirective(D);
2841}
2842
Alexey Bataev68446b72014-07-18 07:47:19 +00002843void
2844EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2845 VisitOMPExecutableDirective(D);
2846}
2847
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002848void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2849 VisitOMPExecutableDirective(D);
2850}
2851
Alexey Bataev2df347a2014-07-18 10:17:07 +00002852void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2853 VisitOMPExecutableDirective(D);
2854}
2855
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002856void EnqueueVisitor::VisitOMPTaskgroupDirective(
2857 const OMPTaskgroupDirective *D) {
2858 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002859 if (const Expr *E = D->getReductionRef())
2860 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002861}
2862
Alexey Bataev6125da92014-07-21 11:26:11 +00002863void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2864 VisitOMPExecutableDirective(D);
2865}
2866
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002867void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2868 VisitOMPExecutableDirective(D);
2869}
2870
Alexey Bataev0162e452014-07-22 10:10:35 +00002871void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2872 VisitOMPExecutableDirective(D);
2873}
2874
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002875void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2876 VisitOMPExecutableDirective(D);
2877}
2878
Michael Wong65f367f2015-07-21 13:44:28 +00002879void EnqueueVisitor::VisitOMPTargetDataDirective(const
2880 OMPTargetDataDirective *D) {
2881 VisitOMPExecutableDirective(D);
2882}
2883
Samuel Antaodf67fc42016-01-19 19:15:56 +00002884void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2885 const OMPTargetEnterDataDirective *D) {
2886 VisitOMPExecutableDirective(D);
2887}
2888
Samuel Antao72590762016-01-19 20:04:50 +00002889void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2890 const OMPTargetExitDataDirective *D) {
2891 VisitOMPExecutableDirective(D);
2892}
2893
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002894void EnqueueVisitor::VisitOMPTargetParallelDirective(
2895 const OMPTargetParallelDirective *D) {
2896 VisitOMPExecutableDirective(D);
2897}
2898
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002899void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2900 const OMPTargetParallelForDirective *D) {
2901 VisitOMPLoopDirective(D);
2902}
2903
Alexey Bataev13314bf2014-10-09 04:18:56 +00002904void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2905 VisitOMPExecutableDirective(D);
2906}
2907
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002908void EnqueueVisitor::VisitOMPCancellationPointDirective(
2909 const OMPCancellationPointDirective *D) {
2910 VisitOMPExecutableDirective(D);
2911}
2912
Alexey Bataev80909872015-07-02 11:25:17 +00002913void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2914 VisitOMPExecutableDirective(D);
2915}
2916
Alexey Bataev49f6e782015-12-01 04:18:41 +00002917void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2918 VisitOMPLoopDirective(D);
2919}
2920
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002921void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2922 const OMPTaskLoopSimdDirective *D) {
2923 VisitOMPLoopDirective(D);
2924}
2925
Alexey Bataev60e51c42019-10-10 20:13:02 +00002926void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2927 const OMPMasterTaskLoopDirective *D) {
2928 VisitOMPLoopDirective(D);
2929}
2930
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002931void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2932 const OMPMasterTaskLoopSimdDirective *D) {
2933 VisitOMPLoopDirective(D);
2934}
2935
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002936void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2937 const OMPParallelMasterTaskLoopDirective *D) {
2938 VisitOMPLoopDirective(D);
2939}
2940
Alexey Bataev14a388f2019-10-25 10:27:13 -04002941void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
2942 const OMPParallelMasterTaskLoopSimdDirective *D) {
2943 VisitOMPLoopDirective(D);
2944}
2945
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002946void EnqueueVisitor::VisitOMPDistributeDirective(
2947 const OMPDistributeDirective *D) {
2948 VisitOMPLoopDirective(D);
2949}
2950
Carlo Bertolli9925f152016-06-27 14:55:37 +00002951void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2952 const OMPDistributeParallelForDirective *D) {
2953 VisitOMPLoopDirective(D);
2954}
2955
Kelvin Li4a39add2016-07-05 05:00:15 +00002956void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2957 const OMPDistributeParallelForSimdDirective *D) {
2958 VisitOMPLoopDirective(D);
2959}
2960
Kelvin Li787f3fc2016-07-06 04:45:38 +00002961void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2962 const OMPDistributeSimdDirective *D) {
2963 VisitOMPLoopDirective(D);
2964}
2965
Kelvin Lia579b912016-07-14 02:54:56 +00002966void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2967 const OMPTargetParallelForSimdDirective *D) {
2968 VisitOMPLoopDirective(D);
2969}
2970
Kelvin Li986330c2016-07-20 22:57:10 +00002971void EnqueueVisitor::VisitOMPTargetSimdDirective(
2972 const OMPTargetSimdDirective *D) {
2973 VisitOMPLoopDirective(D);
2974}
2975
Kelvin Li02532872016-08-05 14:37:37 +00002976void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2977 const OMPTeamsDistributeDirective *D) {
2978 VisitOMPLoopDirective(D);
2979}
2980
Kelvin Li4e325f72016-10-25 12:50:55 +00002981void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2982 const OMPTeamsDistributeSimdDirective *D) {
2983 VisitOMPLoopDirective(D);
2984}
2985
Kelvin Li579e41c2016-11-30 23:51:03 +00002986void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2987 const OMPTeamsDistributeParallelForSimdDirective *D) {
2988 VisitOMPLoopDirective(D);
2989}
2990
Kelvin Li7ade93f2016-12-09 03:24:30 +00002991void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2992 const OMPTeamsDistributeParallelForDirective *D) {
2993 VisitOMPLoopDirective(D);
2994}
2995
Kelvin Libf594a52016-12-17 05:48:59 +00002996void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2997 const OMPTargetTeamsDirective *D) {
2998 VisitOMPExecutableDirective(D);
2999}
3000
Kelvin Li83c451e2016-12-25 04:52:54 +00003001void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3002 const OMPTargetTeamsDistributeDirective *D) {
3003 VisitOMPLoopDirective(D);
3004}
3005
Kelvin Li80e8f562016-12-29 22:16:30 +00003006void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3007 const OMPTargetTeamsDistributeParallelForDirective *D) {
3008 VisitOMPLoopDirective(D);
3009}
3010
Kelvin Li1851df52017-01-03 05:23:48 +00003011void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3012 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3013 VisitOMPLoopDirective(D);
3014}
3015
Kelvin Lida681182017-01-10 18:08:18 +00003016void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3017 const OMPTargetTeamsDistributeSimdDirective *D) {
3018 VisitOMPLoopDirective(D);
3019}
3020
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003021void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
3023}
3024
3025bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3026 if (RegionOfInterest.isValid()) {
3027 SourceRange Range = getRawCursorExtent(C);
3028 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3029 return false;
3030 }
3031 return true;
3032}
3033
3034bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3035 while (!WL.empty()) {
3036 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003037 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003038
3039 // Set the Parent field, then back to its old value once we're done.
3040 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3041
3042 switch (LI.getKind()) {
3043 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003044 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 if (!D)
3046 continue;
3047
3048 // For now, perform default visitation for Decls.
3049 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3050 cast<DeclVisit>(&LI)->isFirst())))
3051 return true;
3052
3053 continue;
3054 }
3055 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003056 for (const TemplateArgumentLoc &Arg :
3057 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3058 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003059 return true;
3060 }
3061 continue;
3062 }
3063 case VisitorJob::TypeLocVisitKind: {
3064 // Perform default visitation for TypeLocs.
3065 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3066 return true;
3067 continue;
3068 }
3069 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003070 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 if (LabelStmt *stmt = LS->getStmt()) {
3072 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3073 TU))) {
3074 return true;
3075 }
3076 }
3077 continue;
3078 }
3079
3080 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3081 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3082 if (VisitNestedNameSpecifierLoc(V->get()))
3083 return true;
3084 continue;
3085 }
3086
3087 case VisitorJob::DeclarationNameInfoVisitKind: {
3088 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3089 ->get()))
3090 return true;
3091 continue;
3092 }
3093 case VisitorJob::MemberRefVisitKind: {
3094 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3095 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3096 return true;
3097 continue;
3098 }
3099 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003100 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 if (!S)
3102 continue;
3103
3104 // Update the current cursor.
3105 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3106 if (!IsInRegionOfInterest(Cursor))
3107 continue;
3108 switch (Visitor(Cursor, Parent, ClientData)) {
3109 case CXChildVisit_Break: return true;
3110 case CXChildVisit_Continue: break;
3111 case CXChildVisit_Recurse:
3112 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003113 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 EnqueueWorkList(WL, S);
3115 break;
3116 }
3117 continue;
3118 }
3119 case VisitorJob::MemberExprPartsKind: {
3120 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003121 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003122
3123 // Visit the nested-name-specifier
3124 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3125 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3126 return true;
3127
3128 // Visit the declaration name.
3129 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3130 return true;
3131
3132 // Visit the explicitly-specified template arguments, if any.
3133 if (M->hasExplicitTemplateArgs()) {
3134 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3135 *ArgEnd = Arg + M->getNumTemplateArgs();
3136 Arg != ArgEnd; ++Arg) {
3137 if (VisitTemplateArgumentLoc(*Arg))
3138 return true;
3139 }
3140 }
3141 continue;
3142 }
3143 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003144 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 // Visit nested-name-specifier, if present.
3146 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3147 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3148 return true;
3149 // Visit declaration name.
3150 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3151 return true;
3152 continue;
3153 }
3154 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003155 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003156 // Visit the nested-name-specifier.
3157 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3158 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3159 return true;
3160 // Visit the declaration name.
3161 if (VisitDeclarationNameInfo(O->getNameInfo()))
3162 return true;
3163 // Visit the overloaded declaration reference.
3164 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3165 return true;
3166 continue;
3167 }
3168 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003169 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 NamedDecl *Pack = E->getPack();
3171 if (isa<TemplateTypeParmDecl>(Pack)) {
3172 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3173 E->getPackLoc(), TU)))
3174 return true;
3175
3176 continue;
3177 }
3178
3179 if (isa<TemplateTemplateParmDecl>(Pack)) {
3180 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3181 E->getPackLoc(), TU)))
3182 return true;
3183
3184 continue;
3185 }
3186
3187 // Non-type template parameter packs and function parameter packs are
3188 // treated like DeclRefExpr cursors.
3189 continue;
3190 }
3191
3192 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003193 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003194 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003195 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3196 CEnd = E->explicit_capture_end();
3197 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003198 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003199 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003200
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3202 C->getLocation(),
3203 TU)))
3204 return true;
3205 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003206 // Visit init captures
3207 for (auto InitExpr : E->capture_inits()) {
3208 if (Visit(InitExpr))
3209 return true;
3210 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003211
Haojian Wuef87c262018-12-18 15:29:12 +00003212 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003213 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003214 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3215 if (E->hasExplicitParameters()) {
3216 // Visit parameters.
3217 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3218 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003219 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003220 }
3221 if (E->hasExplicitResultType()) {
3222 // Visit result type.
3223 if (Visit(Proto.getReturnLoc()))
3224 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 }
3226 }
3227 break;
3228 }
3229
3230 case VisitorJob::PostChildrenVisitKind:
3231 if (PostChildrenVisitor(Parent, ClientData))
3232 return true;
3233 break;
3234 }
3235 }
3236 return false;
3237}
3238
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003239bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003240 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003241 if (!WorkListFreeList.empty()) {
3242 WL = WorkListFreeList.back();
3243 WL->clear();
3244 WorkListFreeList.pop_back();
3245 }
3246 else {
3247 WL = new VisitorWorkList();
3248 WorkListCache.push_back(WL);
3249 }
3250 EnqueueWorkList(*WL, S);
3251 bool result = RunVisitorWorkList(*WL);
3252 WorkListFreeList.push_back(WL);
3253 return result;
3254}
3255
3256namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003257typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003258RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3259 const DeclarationNameInfo &NI, SourceRange QLoc,
3260 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003261 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3262 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3263 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3264
3265 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3266
3267 RefNamePieces Pieces;
3268
3269 if (WantQualifier && QLoc.isValid())
3270 Pieces.push_back(QLoc);
3271
3272 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3273 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003274
3275 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3276 Pieces.push_back(*TemplateArgsLoc);
3277
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 if (Kind == DeclarationName::CXXOperatorName) {
3279 Pieces.push_back(SourceLocation::getFromRawEncoding(
3280 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3281 Pieces.push_back(SourceLocation::getFromRawEncoding(
3282 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3283 }
3284
3285 if (WantSinglePiece) {
3286 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3287 Pieces.clear();
3288 Pieces.push_back(R);
3289 }
3290
3291 return Pieces;
3292}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003293}
Guy Benyei11169dd2012-12-18 14:30:41 +00003294
3295//===----------------------------------------------------------------------===//
3296// Misc. API hooks.
3297//===----------------------------------------------------------------------===//
3298
Chandler Carruth66660742014-06-27 16:37:27 +00003299namespace {
3300struct RegisterFatalErrorHandler {
3301 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003302 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003303 }
3304};
3305}
3306
3307static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3308
Guy Benyei11169dd2012-12-18 14:30:41 +00003309CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3310 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 // We use crash recovery to make some of our APIs more reliable, implicitly
3312 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003313 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3314 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003315
Chandler Carruth66660742014-06-27 16:37:27 +00003316 // Look through the managed static to trigger construction of the managed
3317 // static which registers our fatal error handler. This ensures it is only
3318 // registered once.
3319 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003320
Adrian Prantlbc068582015-07-08 01:00:30 +00003321 // Initialize targets for clang module support.
3322 llvm::InitializeAllTargets();
3323 llvm::InitializeAllTargetMCs();
3324 llvm::InitializeAllAsmPrinters();
3325 llvm::InitializeAllAsmParsers();
3326
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003327 CIndexer *CIdxr = new CIndexer();
3328
Guy Benyei11169dd2012-12-18 14:30:41 +00003329 if (excludeDeclarationsFromPCH)
3330 CIdxr->setOnlyLocalDecls();
3331 if (displayDiagnostics)
3332 CIdxr->setDisplayDiagnostics();
3333
3334 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3335 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3336 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3337 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3338 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3339 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3340
3341 return CIdxr;
3342}
3343
3344void clang_disposeIndex(CXIndex CIdx) {
3345 if (CIdx)
3346 delete static_cast<CIndexer *>(CIdx);
3347}
3348
3349void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3350 if (CIdx)
3351 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3352}
3353
3354unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3355 if (CIdx)
3356 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3357 return 0;
3358}
3359
Alex Lorenz08615792017-12-04 21:56:36 +00003360void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3361 const char *Path) {
3362 if (CIdx)
3363 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3364}
3365
Guy Benyei11169dd2012-12-18 14:30:41 +00003366void clang_toggleCrashRecovery(unsigned isEnabled) {
3367 if (isEnabled)
3368 llvm::CrashRecoveryContext::Enable();
3369 else
3370 llvm::CrashRecoveryContext::Disable();
3371}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003372
Guy Benyei11169dd2012-12-18 14:30:41 +00003373CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3374 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003375 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003376 enum CXErrorCode Result =
3377 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003378 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003379 assert((TU && Result == CXError_Success) ||
3380 (!TU && Result != CXError_Success));
3381 return TU;
3382}
3383
3384enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3385 const char *ast_filename,
3386 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003387 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003388 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003389
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003390 if (!CIdx || !ast_filename || !out_TU)
3391 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003392
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003393 LOG_FUNC_SECTION {
3394 *Log << ast_filename;
3395 }
3396
Guy Benyei11169dd2012-12-18 14:30:41 +00003397 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3398 FileSystemOptions FileSystemOpts;
3399
Justin Bognerd512c1e2014-10-15 00:33:06 +00003400 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3401 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003402 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003403 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3404 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003405 FileSystemOpts, /*UseDebugInfo=*/false,
3406 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003407 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003408 /*AllowPCHWithCompilerErrors=*/true,
3409 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003410 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003411 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003412}
3413
3414unsigned clang_defaultEditingTranslationUnitOptions() {
3415 return CXTranslationUnit_PrecompiledPreamble |
3416 CXTranslationUnit_CacheCompletionResults;
3417}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003418
Guy Benyei11169dd2012-12-18 14:30:41 +00003419CXTranslationUnit
3420clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3421 const char *source_filename,
3422 int num_command_line_args,
3423 const char * const *command_line_args,
3424 unsigned num_unsaved_files,
3425 struct CXUnsavedFile *unsaved_files) {
3426 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3427 return clang_parseTranslationUnit(CIdx, source_filename,
3428 command_line_args, num_command_line_args,
3429 unsaved_files, num_unsaved_files,
3430 Options);
3431}
3432
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003433static CXErrorCode
3434clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3435 const char *const *command_line_args,
3436 int num_command_line_args,
3437 ArrayRef<CXUnsavedFile> unsaved_files,
3438 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003439 // Set up the initial return values.
3440 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003441 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003442
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003443 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003444 if (!CIdx || !out_TU)
3445 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003446
Guy Benyei11169dd2012-12-18 14:30:41 +00003447 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3448
3449 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3450 setThreadBackgroundPriority();
3451
3452 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003453 bool CreatePreambleOnFirstParse =
3454 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003455 // FIXME: Add a flag for modules.
3456 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003457 = (options & (CXTranslationUnit_Incomplete |
3458 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003459 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003460 = options & CXTranslationUnit_CacheCompletionResults;
3461 bool IncludeBriefCommentsInCodeCompletion
3462 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003463 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3464 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003465 bool RetainExcludedCB = options &
3466 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003467 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3468 if (options & CXTranslationUnit_SkipFunctionBodies) {
3469 SkipFunctionBodies =
3470 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3471 ? SkipFunctionBodiesScope::Preamble
3472 : SkipFunctionBodiesScope::PreambleAndMainFile;
3473 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003474
3475 // Configure the diagnostics.
3476 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003477 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003478
Manuel Klimek016c0242016-03-01 10:56:19 +00003479 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003480 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003481
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003482 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3483 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3484 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3485
Guy Benyei11169dd2012-12-18 14:30:41 +00003486 // Recover resources if we crash before exiting this function.
3487 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3488 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003489 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003490
Ahmed Charlesb8984322014-03-07 20:03:18 +00003491 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3492 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003493
3494 // Recover resources if we crash before exiting this function.
3495 llvm::CrashRecoveryContextCleanupRegistrar<
3496 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3497
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003498 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003499 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003500 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003501 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 }
3503
Ahmed Charlesb8984322014-03-07 20:03:18 +00003504 std::unique_ptr<std::vector<const char *>> Args(
3505 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003506
3507 // Recover resources if we crash before exiting this method.
3508 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3509 ArgsCleanup(Args.get());
3510
3511 // Since the Clang C library is primarily used by batch tools dealing with
3512 // (often very broken) source code, where spell-checking can have a
3513 // significant negative impact on performance (particularly when
3514 // precompiled headers are involved), we disable it by default.
3515 // Only do this if we haven't found a spell-checking-related argument.
3516 bool FoundSpellCheckingArgument = false;
3517 for (int I = 0; I != num_command_line_args; ++I) {
3518 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3519 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3520 FoundSpellCheckingArgument = true;
3521 break;
3522 }
3523 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 Args->insert(Args->end(), command_line_args,
3525 command_line_args + num_command_line_args);
3526
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003527 if (!FoundSpellCheckingArgument)
3528 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3529
Guy Benyei11169dd2012-12-18 14:30:41 +00003530 // The 'source_filename' argument is optional. If the caller does not
3531 // specify it then it is assumed that the source file is specified
3532 // in the actual argument list.
3533 // Put the source file after command_line_args otherwise if '-x' flag is
3534 // present it will be unused.
3535 if (source_filename)
3536 Args->push_back(source_filename);
3537
3538 // Do we need the detailed preprocessing record?
3539 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3540 Args->push_back("-Xclang");
3541 Args->push_back("-detailed-preprocessing-record");
3542 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003543
3544 // Suppress any editor placeholder diagnostics.
3545 Args->push_back("-fallow-editor-placeholders");
3546
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003548 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003549 // Unless the user specified that they want the preamble on the first parse
3550 // set it up to be created on the first reparse. This makes the first parse
3551 // faster, trading for a slower (first) reparse.
3552 unsigned PrecompilePreambleAfterNParses =
3553 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003554
Alex Lorenz08615792017-12-04 21:56:36 +00003555 LibclangInvocationReporter InvocationReporter(
3556 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003557 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3558 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003559 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003560 Args->data(), Args->data() + Args->size(),
3561 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003562 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003563 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003564 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3565 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003566 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003567 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003568 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3569 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003570
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003571 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003572 if (!Unit && !ErrUnit)
3573 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003574
Guy Benyei11169dd2012-12-18 14:30:41 +00003575 if (NumErrors != Diags->getClient()->getNumErrors()) {
3576 // Make sure to check that 'Unit' is non-NULL.
3577 if (CXXIdx->getDisplayDiagnostics())
3578 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3579 }
3580
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003581 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3582 return CXError_ASTReadError;
3583
David Blaikieea4395e2017-01-06 19:49:01 +00003584 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003585 if (CXTranslationUnitImpl *TU = *out_TU) {
3586 TU->ParsingOptions = options;
3587 TU->Arguments.reserve(Args->size());
3588 for (const char *Arg : *Args)
3589 TU->Arguments.push_back(Arg);
3590 return CXError_Success;
3591 }
3592 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003593}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003594
3595CXTranslationUnit
3596clang_parseTranslationUnit(CXIndex CIdx,
3597 const char *source_filename,
3598 const char *const *command_line_args,
3599 int num_command_line_args,
3600 struct CXUnsavedFile *unsaved_files,
3601 unsigned num_unsaved_files,
3602 unsigned options) {
3603 CXTranslationUnit TU;
3604 enum CXErrorCode Result = clang_parseTranslationUnit2(
3605 CIdx, source_filename, command_line_args, num_command_line_args,
3606 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003607 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003608 assert((TU && Result == CXError_Success) ||
3609 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003610 return TU;
3611}
3612
3613enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003614 CXIndex CIdx, const char *source_filename,
3615 const char *const *command_line_args, int num_command_line_args,
3616 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3617 unsigned options, CXTranslationUnit *out_TU) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003618 noteBottomOfStack();
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003619 SmallVector<const char *, 4> Args;
3620 Args.push_back("clang");
3621 Args.append(command_line_args, command_line_args + num_command_line_args);
3622 return clang_parseTranslationUnit2FullArgv(
3623 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3624 num_unsaved_files, options, out_TU);
3625}
3626
3627enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3628 CXIndex CIdx, const char *source_filename,
3629 const char *const *command_line_args, int num_command_line_args,
3630 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3631 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003632 LOG_FUNC_SECTION {
3633 *Log << source_filename << ": ";
3634 for (int i = 0; i != num_command_line_args; ++i)
3635 *Log << command_line_args[i] << " ";
3636 }
3637
Alp Toker9d85b182014-07-07 01:23:14 +00003638 if (num_unsaved_files && !unsaved_files)
3639 return CXError_InvalidArguments;
3640
Alp Toker5c532982014-07-07 22:42:03 +00003641 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003642 auto ParseTranslationUnitImpl = [=, &result] {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003643 noteBottomOfStack();
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003644 result = clang_parseTranslationUnit_Impl(
3645 CIdx, source_filename, command_line_args, num_command_line_args,
3646 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3647 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003648
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 llvm::CrashRecoveryContext CRC;
3650
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003651 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003652 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3653 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3654 fprintf(stderr, " 'command_line_args' : [");
3655 for (int i = 0; i != num_command_line_args; ++i) {
3656 if (i)
3657 fprintf(stderr, ", ");
3658 fprintf(stderr, "'%s'", command_line_args[i]);
3659 }
3660 fprintf(stderr, "],\n");
3661 fprintf(stderr, " 'unsaved_files' : [");
3662 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3663 if (i)
3664 fprintf(stderr, ", ");
3665 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3666 unsaved_files[i].Length);
3667 }
3668 fprintf(stderr, "],\n");
3669 fprintf(stderr, " 'options' : %d,\n", options);
3670 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003671
3672 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003674 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003675 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 }
Alp Toker5c532982014-07-07 22:42:03 +00003677
3678 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003679}
3680
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003681CXString clang_Type_getObjCEncoding(CXType CT) {
3682 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3683 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3684 std::string encoding;
3685 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3686 encoding);
3687
3688 return cxstring::createDup(encoding);
3689}
3690
3691static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3692 if (C.kind == CXCursor_MacroDefinition) {
3693 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3694 return MDR->getName();
3695 } else if (C.kind == CXCursor_MacroExpansion) {
3696 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3697 return ME.getName();
3698 }
3699 return nullptr;
3700}
3701
3702unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3703 const IdentifierInfo *II = getMacroIdentifier(C);
3704 if (!II) {
3705 return false;
3706 }
3707 ASTUnit *ASTU = getCursorASTUnit(C);
3708 Preprocessor &PP = ASTU->getPreprocessor();
3709 if (const MacroInfo *MI = PP.getMacroInfo(II))
3710 return MI->isFunctionLike();
3711 return false;
3712}
3713
3714unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3715 const IdentifierInfo *II = getMacroIdentifier(C);
3716 if (!II) {
3717 return false;
3718 }
3719 ASTUnit *ASTU = getCursorASTUnit(C);
3720 Preprocessor &PP = ASTU->getPreprocessor();
3721 if (const MacroInfo *MI = PP.getMacroInfo(II))
3722 return MI->isBuiltinMacro();
3723 return false;
3724}
3725
3726unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3727 const Decl *D = getCursorDecl(C);
3728 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3729 if (!FD) {
3730 return false;
3731 }
3732 return FD->isInlined();
3733}
3734
3735static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3736 if (callExpr->getNumArgs() != 1) {
3737 return nullptr;
3738 }
3739
3740 StringLiteral *S = nullptr;
3741 auto *arg = callExpr->getArg(0);
3742 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3743 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3744 auto *subExpr = I->getSubExprAsWritten();
3745
3746 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3747 return nullptr;
3748 }
3749
3750 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3751 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3752 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3753 } else {
3754 return nullptr;
3755 }
3756 return S;
3757}
3758
David Blaikie59272572016-04-13 18:23:33 +00003759struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003760 CXEvalResultKind EvalType;
3761 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003762 unsigned long long unsignedVal;
3763 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003764 double floatVal;
3765 char *stringVal;
3766 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003767 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003768 ~ExprEvalResult() {
3769 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3770 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003771 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003772 }
3773 }
3774};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003775
3776void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003777 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003778}
3779
3780CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3781 if (!E) {
3782 return CXEval_UnExposed;
3783 }
3784 return ((ExprEvalResult *)E)->EvalType;
3785}
3786
3787int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003788 return clang_EvalResult_getAsLongLong(E);
3789}
3790
3791long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003792 if (!E) {
3793 return 0;
3794 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003795 ExprEvalResult *Result = (ExprEvalResult*)E;
3796 if (Result->IsUnsignedInt)
3797 return Result->EvalData.unsignedVal;
3798 return Result->EvalData.intVal;
3799}
3800
3801unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3802 return ((ExprEvalResult *)E)->IsUnsignedInt;
3803}
3804
3805unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3806 if (!E) {
3807 return 0;
3808 }
3809
3810 ExprEvalResult *Result = (ExprEvalResult*)E;
3811 if (Result->IsUnsignedInt)
3812 return Result->EvalData.unsignedVal;
3813 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003814}
3815
3816double clang_EvalResult_getAsDouble(CXEvalResult E) {
3817 if (!E) {
3818 return 0;
3819 }
3820 return ((ExprEvalResult *)E)->EvalData.floatVal;
3821}
3822
3823const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3824 if (!E) {
3825 return nullptr;
3826 }
3827 return ((ExprEvalResult *)E)->EvalData.stringVal;
3828}
3829
3830static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3831 Expr::EvalResult ER;
3832 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003833 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003834 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003835
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003836 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003837 if (expr->isValueDependent())
3838 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003839 if (!expr->EvaluateAsRValue(ER, ctx))
3840 return nullptr;
3841
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003842 QualType rettype;
3843 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003844 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003845 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003846 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003847
David Blaikiebbc00882016-04-13 18:36:19 +00003848 if (ER.Val.isInt()) {
3849 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003850
3851 auto& val = ER.Val.getInt();
3852 if (val.isUnsigned()) {
3853 result->IsUnsignedInt = true;
3854 result->EvalData.unsignedVal = val.getZExtValue();
3855 } else {
3856 result->EvalData.intVal = val.getExtValue();
3857 }
3858
David Blaikiebbc00882016-04-13 18:36:19 +00003859 return result.release();
3860 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003861
David Blaikiebbc00882016-04-13 18:36:19 +00003862 if (ER.Val.isFloat()) {
3863 llvm::SmallVector<char, 100> Buffer;
3864 ER.Val.getFloat().toString(Buffer);
3865 std::string floatStr(Buffer.data(), Buffer.size());
3866 result->EvalType = CXEval_Float;
3867 bool ignored;
3868 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003869 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003870 llvm::APFloat::rmNearestTiesToEven, &ignored);
3871 result->EvalData.floatVal = apFloat.convertToDouble();
3872 return result.release();
3873 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003874
David Blaikiebbc00882016-04-13 18:36:19 +00003875 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3876 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3877 auto *subExpr = I->getSubExprAsWritten();
3878 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3879 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003880 const StringLiteral *StrE = nullptr;
3881 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003882 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003883
3884 if (ObjCExpr) {
3885 StrE = ObjCExpr->getString();
3886 result->EvalType = CXEval_ObjCStrLiteral;
3887 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003888 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003889 result->EvalType = CXEval_StrLiteral;
3890 }
3891
3892 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003893 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003894 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3895 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003896 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003897 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003898 }
3899 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3900 expr->getStmtClass() == Stmt::StringLiteralClass) {
3901 const StringLiteral *StrE = nullptr;
3902 const ObjCStringLiteral *ObjCExpr;
3903 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003904
David Blaikiebbc00882016-04-13 18:36:19 +00003905 if (ObjCExpr) {
3906 StrE = ObjCExpr->getString();
3907 result->EvalType = CXEval_ObjCStrLiteral;
3908 } else {
3909 StrE = cast<StringLiteral>(expr);
3910 result->EvalType = CXEval_StrLiteral;
3911 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003912
David Blaikiebbc00882016-04-13 18:36:19 +00003913 std::string strRef(StrE->getString().str());
3914 result->EvalData.stringVal = new char[strRef.size() + 1];
3915 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3916 result->EvalData.stringVal[strRef.size()] = '\0';
3917 return result.release();
3918 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003919
David Blaikiebbc00882016-04-13 18:36:19 +00003920 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3921 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003922
David Blaikiebbc00882016-04-13 18:36:19 +00003923 rettype = CC->getType();
3924 if (rettype.getAsString() == "CFStringRef" &&
3925 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003926
David Blaikiebbc00882016-04-13 18:36:19 +00003927 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3928 StringLiteral *S = getCFSTR_value(callExpr);
3929 if (S) {
3930 std::string strLiteral(S->getString().str());
3931 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003932
David Blaikiebbc00882016-04-13 18:36:19 +00003933 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3934 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3935 strLiteral.size());
3936 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003937 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003938 }
3939 }
3940
David Blaikiebbc00882016-04-13 18:36:19 +00003941 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3942 callExpr = static_cast<CallExpr *>(expr);
3943 rettype = callExpr->getCallReturnType(ctx);
3944
3945 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3946 return nullptr;
3947
3948 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3949 if (callExpr->getNumArgs() == 1 &&
3950 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3951 return nullptr;
3952 } else if (rettype.getAsString() == "CFStringRef") {
3953
3954 StringLiteral *S = getCFSTR_value(callExpr);
3955 if (S) {
3956 std::string strLiteral(S->getString().str());
3957 result->EvalType = CXEval_CFStr;
3958 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3959 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3960 strLiteral.size());
3961 result->EvalData.stringVal[strLiteral.size()] = '\0';
3962 return result.release();
3963 }
3964 }
3965 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3966 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3967 ValueDecl *V = D->getDecl();
3968 if (V->getKind() == Decl::Function) {
3969 std::string strName = V->getNameAsString();
3970 result->EvalType = CXEval_Other;
3971 result->EvalData.stringVal = new char[strName.size() + 1];
3972 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3973 result->EvalData.stringVal[strName.size()] = '\0';
3974 return result.release();
3975 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003976 }
3977
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003978 return nullptr;
3979}
3980
Alex Lorenz65317e12019-01-08 22:32:51 +00003981static const Expr *evaluateDeclExpr(const Decl *D) {
3982 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003983 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003984 if (auto *Var = dyn_cast<VarDecl>(D))
3985 return Var->getInit();
3986 else if (auto *Field = dyn_cast<FieldDecl>(D))
3987 return Field->getInClassInitializer();
3988 return nullptr;
3989}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003990
Alex Lorenz65317e12019-01-08 22:32:51 +00003991static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3992 assert(CS && "invalid compound statement");
3993 for (auto *bodyIterator : CS->body()) {
3994 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3995 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003996 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003997 return nullptr;
3998}
3999
Alex Lorenz65317e12019-01-08 22:32:51 +00004000CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4001 if (const Expr *E =
4002 clang_getCursorKind(C) == CXCursor_CompoundStmt
4003 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
4004 : evaluateDeclExpr(getCursorDecl(C)))
4005 return const_cast<CXEvalResult>(
4006 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4007 return nullptr;
4008}
4009
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004010unsigned clang_Cursor_hasAttrs(CXCursor C) {
4011 const Decl *D = getCursorDecl(C);
4012 if (!D) {
4013 return 0;
4014 }
4015
4016 if (D->hasAttrs()) {
4017 return 1;
4018 }
4019
4020 return 0;
4021}
Guy Benyei11169dd2012-12-18 14:30:41 +00004022unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4023 return CXSaveTranslationUnit_None;
4024}
4025
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004026static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4027 const char *FileName,
4028 unsigned options) {
4029 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4031 setThreadBackgroundPriority();
4032
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004033 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4034 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004035}
4036
4037int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4038 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004039 LOG_FUNC_SECTION {
4040 *Log << TU << ' ' << FileName;
4041 }
4042
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004043 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004044 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004045 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004046 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004047
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004048 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4050 if (!CXXUnit->hasSema())
4051 return CXSaveError_InvalidTU;
4052
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004053 CXSaveError result;
4054 auto SaveTranslationUnitImpl = [=, &result]() {
4055 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4056 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004057
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004058 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004059 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004060
4061 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4062 PrintLibclangResourceUsage(TU);
4063
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004064 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004065 }
4066
4067 // We have an AST that has invalid nodes due to compiler errors.
4068 // Use a crash recovery thread for protection.
4069
4070 llvm::CrashRecoveryContext CRC;
4071
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004072 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004073 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4074 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4075 fprintf(stderr, " 'options' : %d,\n", options);
4076 fprintf(stderr, "}\n");
4077
4078 return CXSaveError_Unknown;
4079
4080 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4081 PrintLibclangResourceUsage(TU);
4082 }
4083
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004084 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004085}
4086
4087void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4088 if (CTUnit) {
4089 // If the translation unit has been marked as unsafe to free, just discard
4090 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004091 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4092 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 return;
4094
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004095 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004096 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4098 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004099 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 delete CTUnit;
4101 }
4102}
4103
Erik Verbruggen346066b2017-05-30 14:25:54 +00004104unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4105 if (CTUnit) {
4106 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4107
4108 if (Unit && Unit->isUnsafeToFree())
4109 return false;
4110
4111 Unit->ResetForParse();
4112 return true;
4113 }
4114
4115 return false;
4116}
4117
Guy Benyei11169dd2012-12-18 14:30:41 +00004118unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4119 return CXReparse_None;
4120}
4121
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004122static CXErrorCode
4123clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4124 ArrayRef<CXUnsavedFile> unsaved_files,
4125 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004126 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004127 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004128 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004129 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004130 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004131
4132 // Reset the associated diagnostics.
4133 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004134 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004135
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004136 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004137 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4138 setThreadBackgroundPriority();
4139
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004140 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004141 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004142
4143 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4144 new std::vector<ASTUnit::RemappedFile>());
4145
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 // Recover resources if we crash before exiting this function.
4147 llvm::CrashRecoveryContextCleanupRegistrar<
4148 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004149
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004150 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004151 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004152 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004153 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004154 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004155
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004156 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4157 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004158 return CXError_Success;
4159 if (isASTReadError(CXXUnit))
4160 return CXError_ASTReadError;
4161 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004162}
4163
4164int clang_reparseTranslationUnit(CXTranslationUnit TU,
4165 unsigned num_unsaved_files,
4166 struct CXUnsavedFile *unsaved_files,
4167 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004168 LOG_FUNC_SECTION {
4169 *Log << TU;
4170 }
4171
Alp Toker9d85b182014-07-07 01:23:14 +00004172 if (num_unsaved_files && !unsaved_files)
4173 return CXError_InvalidArguments;
4174
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004175 CXErrorCode result;
4176 auto ReparseTranslationUnitImpl = [=, &result]() {
4177 result = clang_reparseTranslationUnit_Impl(
4178 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4179 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004180
Guy Benyei11169dd2012-12-18 14:30:41 +00004181 llvm::CrashRecoveryContext CRC;
4182
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004183 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004185 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004186 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004187 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4188 PrintLibclangResourceUsage(TU);
4189
Alp Toker5c532982014-07-07 22:42:03 +00004190 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004191}
4192
4193
4194CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004195 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004196 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004197 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004198 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004199
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004200 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004201 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004202}
4203
4204CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004205 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004206 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004207 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004208 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004209
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004210 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4212}
4213
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004214CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4215 if (isNotUsableTU(CTUnit)) {
4216 LOG_BAD_TU(CTUnit);
4217 return nullptr;
4218 }
4219
4220 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4221 impl->TranslationUnit = CTUnit;
4222 return impl;
4223}
4224
4225CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4226 if (!TargetInfo)
4227 return cxstring::createEmpty();
4228
4229 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4230 assert(!isNotUsableTU(CTUnit) &&
4231 "Unexpected unusable translation unit in TargetInfo");
4232
4233 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4234 std::string Triple =
4235 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4236 return cxstring::createDup(Triple);
4237}
4238
4239int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4240 if (!TargetInfo)
4241 return -1;
4242
4243 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4244 assert(!isNotUsableTU(CTUnit) &&
4245 "Unexpected unusable translation unit in TargetInfo");
4246
4247 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4248 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4249}
4250
4251void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4252 if (!TargetInfo)
4253 return;
4254
4255 delete TargetInfo;
4256}
4257
Guy Benyei11169dd2012-12-18 14:30:41 +00004258//===----------------------------------------------------------------------===//
4259// CXFile Operations.
4260//===----------------------------------------------------------------------===//
4261
Guy Benyei11169dd2012-12-18 14:30:41 +00004262CXString clang_getFileName(CXFile SFile) {
4263 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004264 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004265
4266 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004267 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004268}
4269
4270time_t clang_getFileTime(CXFile SFile) {
4271 if (!SFile)
4272 return 0;
4273
4274 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4275 return FEnt->getModificationTime();
4276}
4277
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004278CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004279 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004280 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004281 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004282 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004283
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004284 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004285
4286 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004287 auto File = FMgr.getFile(file_name);
4288 if (!File)
4289 return nullptr;
4290 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004291}
4292
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004293const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4294 size_t *size) {
4295 if (isNotUsableTU(TU)) {
4296 LOG_BAD_TU(TU);
4297 return nullptr;
4298 }
4299
4300 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4301 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4302 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004303 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004304 if (Invalid) {
4305 if (size)
4306 *size = 0;
4307 return nullptr;
4308 }
4309 if (size)
4310 *size = buf->getBufferSize();
4311 return buf->getBufferStart();
4312}
4313
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004314unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4315 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004316 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004317 LOG_BAD_TU(TU);
4318 return 0;
4319 }
4320
4321 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 return 0;
4323
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004324 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004325 FileEntry *FEnt = static_cast<FileEntry *>(file);
4326 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4327 .isFileMultipleIncludeGuarded(FEnt);
4328}
4329
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004330int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4331 if (!file || !outID)
4332 return 1;
4333
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004334 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004335 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4336 outID->data[0] = ID.getDevice();
4337 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004338 outID->data[2] = FEnt->getModificationTime();
4339 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004340}
4341
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004342int clang_File_isEqual(CXFile file1, CXFile file2) {
4343 if (file1 == file2)
4344 return true;
4345
4346 if (!file1 || !file2)
4347 return false;
4348
4349 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4350 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4351 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4352}
4353
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004354CXString clang_File_tryGetRealPathName(CXFile SFile) {
4355 if (!SFile)
4356 return cxstring::createNull();
4357
4358 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4359 return cxstring::createRef(FEnt->tryGetRealPathName());
4360}
4361
Guy Benyei11169dd2012-12-18 14:30:41 +00004362//===----------------------------------------------------------------------===//
4363// CXCursor Operations.
4364//===----------------------------------------------------------------------===//
4365
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004366static const Decl *getDeclFromExpr(const Stmt *E) {
4367 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 return getDeclFromExpr(CE->getSubExpr());
4369
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004370 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004372 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004374 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004376 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 if (PRE->isExplicitProperty())
4378 return PRE->getExplicitProperty();
4379 // It could be messaging both getter and setter as in:
4380 // ++myobj.myprop;
4381 // in which case prefer to associate the setter since it is less obvious
4382 // from inspecting the source that the setter is going to get called.
4383 if (PRE->isMessagingSetter())
4384 return PRE->getImplicitPropertySetter();
4385 return PRE->getImplicitPropertyGetter();
4386 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004387 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004389 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 if (Expr *Src = OVE->getSourceExpr())
4391 return getDeclFromExpr(Src);
4392
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004393 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004395 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 if (!CE->isElidable())
4397 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004398 if (const CXXInheritedCtorInitExpr *CE =
4399 dyn_cast<CXXInheritedCtorInitExpr>(E))
4400 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004401 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 return OME->getMethodDecl();
4403
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004404 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004406 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4408 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004409 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4411 isa<ParmVarDecl>(SizeOfPack->getPack()))
4412 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004413
4414 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004415}
4416
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004417static SourceLocation getLocationFromExpr(const Expr *E) {
4418 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 return getLocationFromExpr(CE->getSubExpr());
4420
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004421 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004423 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004425 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004427 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004429 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004431 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004433
4434 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004435}
4436
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004437extern "C" {
4438
Guy Benyei11169dd2012-12-18 14:30:41 +00004439unsigned clang_visitChildren(CXCursor parent,
4440 CXCursorVisitor visitor,
4441 CXClientData client_data) {
4442 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4443 /*VisitPreprocessorLast=*/false);
4444 return CursorVis.VisitChildren(parent);
4445}
4446
4447#ifndef __has_feature
4448#define __has_feature(x) 0
4449#endif
4450#if __has_feature(blocks)
4451typedef enum CXChildVisitResult
4452 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4453
4454static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4455 CXClientData client_data) {
4456 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4457 return block(cursor, parent);
4458}
4459#else
4460// If we are compiled with a compiler that doesn't have native blocks support,
4461// define and call the block manually, so the
4462typedef struct _CXChildVisitResult
4463{
4464 void *isa;
4465 int flags;
4466 int reserved;
4467 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4468 CXCursor);
4469} *CXCursorVisitorBlock;
4470
4471static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4472 CXClientData client_data) {
4473 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4474 return block->invoke(block, cursor, parent);
4475}
4476#endif
4477
4478
4479unsigned clang_visitChildrenWithBlock(CXCursor parent,
4480 CXCursorVisitorBlock block) {
4481 return clang_visitChildren(parent, visitWithBlock, block);
4482}
4483
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004484static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004486 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004487
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004488 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004490 if (const ObjCPropertyImplDecl *PropImpl =
4491 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004493 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004494
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004495 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004497 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004498
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004499 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 }
4501
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004502 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004503 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004504
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004505 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4507 // and returns different names. NamedDecl returns the class name and
4508 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004509 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004510
4511 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004512 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004513
4514 SmallString<1024> S;
4515 llvm::raw_svector_ostream os(S);
4516 ND->printName(os);
4517
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004518 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004519}
4520
4521CXString clang_getCursorSpelling(CXCursor C) {
4522 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004523 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004524
4525 if (clang_isReference(C.kind)) {
4526 switch (C.kind) {
4527 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004528 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004529 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004530 }
4531 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004532 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004533 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 }
4535 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004536 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004538 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 }
4540 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004541 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004542 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 }
4544 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004545 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 assert(Type && "Missing type decl");
4547
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004548 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 getAsString());
4550 }
4551 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004552 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 assert(Template && "Missing template decl");
4554
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004555 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 }
4557
4558 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004559 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 assert(NS && "Missing namespace decl");
4561
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004562 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 }
4564
4565 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004566 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 assert(Field && "Missing member decl");
4568
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004569 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 }
4571
4572 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004573 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 assert(Label && "Missing label");
4575
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004576 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 }
4578
4579 case CXCursor_OverloadedDeclRef: {
4580 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004581 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4582 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004583 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004584 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004586 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004587 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004588 OverloadedTemplateStorage *Ovl
4589 = Storage.get<OverloadedTemplateStorage*>();
4590 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004591 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004592 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 }
4594
4595 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004596 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 assert(Var && "Missing variable decl");
4598
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004599 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 }
4601
4602 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004603 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 }
4605 }
4606
4607 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004608 const Expr *E = getCursorExpr(C);
4609
4610 if (C.kind == CXCursor_ObjCStringLiteral ||
4611 C.kind == CXCursor_StringLiteral) {
4612 const StringLiteral *SLit;
4613 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4614 SLit = OSL->getString();
4615 } else {
4616 SLit = cast<StringLiteral>(E);
4617 }
4618 SmallString<256> Buf;
4619 llvm::raw_svector_ostream OS(Buf);
4620 SLit->outputString(OS);
4621 return cxstring::createDup(OS.str());
4622 }
4623
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004624 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 if (D)
4626 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004627 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 }
4629
4630 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004631 const Stmt *S = getCursorStmt(C);
4632 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004633 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004634
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004635 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 }
4637
4638 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004639 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 ->getNameStart());
4641
4642 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004643 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 ->getNameStart());
4645
4646 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004647 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004648
4649 if (clang_isDeclaration(C.kind))
4650 return getDeclSpelling(getCursorDecl(C));
4651
4652 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004653 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004654 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 }
4656
4657 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004658 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004659 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 }
4661
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004662 if (C.kind == CXCursor_PackedAttr) {
4663 return cxstring::createRef("packed");
4664 }
4665
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004666 if (C.kind == CXCursor_VisibilityAttr) {
4667 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4668 switch (AA->getVisibility()) {
4669 case VisibilityAttr::VisibilityType::Default:
4670 return cxstring::createRef("default");
4671 case VisibilityAttr::VisibilityType::Hidden:
4672 return cxstring::createRef("hidden");
4673 case VisibilityAttr::VisibilityType::Protected:
4674 return cxstring::createRef("protected");
4675 }
4676 llvm_unreachable("unknown visibility type");
4677 }
4678
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004679 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004680}
4681
4682CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4683 unsigned pieceIndex,
4684 unsigned options) {
4685 if (clang_Cursor_isNull(C))
4686 return clang_getNullRange();
4687
4688 ASTContext &Ctx = getCursorContext(C);
4689
4690 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004691 const Stmt *S = getCursorStmt(C);
4692 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 if (pieceIndex > 0)
4694 return clang_getNullRange();
4695 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4696 }
4697
4698 return clang_getNullRange();
4699 }
4700
4701 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004702 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4704 if (pieceIndex >= ME->getNumSelectorLocs())
4705 return clang_getNullRange();
4706 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4707 }
4708 }
4709
4710 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4711 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004712 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4714 if (pieceIndex >= MD->getNumSelectorLocs())
4715 return clang_getNullRange();
4716 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4717 }
4718 }
4719
4720 if (C.kind == CXCursor_ObjCCategoryDecl ||
4721 C.kind == CXCursor_ObjCCategoryImplDecl) {
4722 if (pieceIndex > 0)
4723 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004724 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4726 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004727 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4729 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4730 }
4731
4732 if (C.kind == CXCursor_ModuleImportDecl) {
4733 if (pieceIndex > 0)
4734 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004735 if (const ImportDecl *ImportD =
4736 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4738 if (!Locs.empty())
4739 return cxloc::translateSourceRange(Ctx,
4740 SourceRange(Locs.front(), Locs.back()));
4741 }
4742 return clang_getNullRange();
4743 }
4744
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004745 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004746 C.kind == CXCursor_ConversionFunction ||
4747 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004748 if (pieceIndex > 0)
4749 return clang_getNullRange();
4750 if (const FunctionDecl *FD =
4751 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4752 DeclarationNameInfo FunctionName = FD->getNameInfo();
4753 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4754 }
4755 return clang_getNullRange();
4756 }
4757
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 // FIXME: A CXCursor_InclusionDirective should give the location of the
4759 // filename, but we don't keep track of this.
4760
4761 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4762 // but we don't keep track of this.
4763
4764 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4765 // but we don't keep track of this.
4766
4767 // Default handling, give the location of the cursor.
4768
4769 if (pieceIndex > 0)
4770 return clang_getNullRange();
4771
4772 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4773 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4774 return cxloc::translateSourceRange(Ctx, Loc);
4775}
4776
Eli Bendersky44a206f2014-07-31 18:04:56 +00004777CXString clang_Cursor_getMangling(CXCursor C) {
4778 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4779 return cxstring::createEmpty();
4780
Eli Bendersky44a206f2014-07-31 18:04:56 +00004781 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004782 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004783 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4784 return cxstring::createEmpty();
4785
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004786 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004787 ASTNameGenerator ASTNameGen(Ctx);
4788 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004789}
4790
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004791CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4792 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4793 return nullptr;
4794
4795 const Decl *D = getCursorDecl(C);
4796 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4797 return nullptr;
4798
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004799 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004800 ASTNameGenerator ASTNameGen(Ctx);
4801 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004802 return cxstring::createSet(Manglings);
4803}
4804
Dave Lee1a532c92017-09-22 16:58:57 +00004805CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4806 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4807 return nullptr;
4808
4809 const Decl *D = getCursorDecl(C);
4810 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4811 return nullptr;
4812
4813 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004814 ASTNameGenerator ASTNameGen(Ctx);
4815 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004816 return cxstring::createSet(Manglings);
4817}
4818
Jonathan Coe45ef5032018-01-16 10:19:56 +00004819CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4820 if (clang_Cursor_isNull(C))
4821 return 0;
4822 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4823}
4824
4825void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4826 if (Policy)
4827 delete static_cast<PrintingPolicy *>(Policy);
4828}
4829
4830unsigned
4831clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4832 enum CXPrintingPolicyProperty Property) {
4833 if (!Policy)
4834 return 0;
4835
4836 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4837 switch (Property) {
4838 case CXPrintingPolicy_Indentation:
4839 return P->Indentation;
4840 case CXPrintingPolicy_SuppressSpecifiers:
4841 return P->SuppressSpecifiers;
4842 case CXPrintingPolicy_SuppressTagKeyword:
4843 return P->SuppressTagKeyword;
4844 case CXPrintingPolicy_IncludeTagDefinition:
4845 return P->IncludeTagDefinition;
4846 case CXPrintingPolicy_SuppressScope:
4847 return P->SuppressScope;
4848 case CXPrintingPolicy_SuppressUnwrittenScope:
4849 return P->SuppressUnwrittenScope;
4850 case CXPrintingPolicy_SuppressInitializers:
4851 return P->SuppressInitializers;
4852 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4853 return P->ConstantArraySizeAsWritten;
4854 case CXPrintingPolicy_AnonymousTagLocations:
4855 return P->AnonymousTagLocations;
4856 case CXPrintingPolicy_SuppressStrongLifetime:
4857 return P->SuppressStrongLifetime;
4858 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4859 return P->SuppressLifetimeQualifiers;
4860 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4861 return P->SuppressTemplateArgsInCXXConstructors;
4862 case CXPrintingPolicy_Bool:
4863 return P->Bool;
4864 case CXPrintingPolicy_Restrict:
4865 return P->Restrict;
4866 case CXPrintingPolicy_Alignof:
4867 return P->Alignof;
4868 case CXPrintingPolicy_UnderscoreAlignof:
4869 return P->UnderscoreAlignof;
4870 case CXPrintingPolicy_UseVoidForZeroParams:
4871 return P->UseVoidForZeroParams;
4872 case CXPrintingPolicy_TerseOutput:
4873 return P->TerseOutput;
4874 case CXPrintingPolicy_PolishForDeclaration:
4875 return P->PolishForDeclaration;
4876 case CXPrintingPolicy_Half:
4877 return P->Half;
4878 case CXPrintingPolicy_MSWChar:
4879 return P->MSWChar;
4880 case CXPrintingPolicy_IncludeNewlines:
4881 return P->IncludeNewlines;
4882 case CXPrintingPolicy_MSVCFormatting:
4883 return P->MSVCFormatting;
4884 case CXPrintingPolicy_ConstantsAsWritten:
4885 return P->ConstantsAsWritten;
4886 case CXPrintingPolicy_SuppressImplicitBase:
4887 return P->SuppressImplicitBase;
4888 case CXPrintingPolicy_FullyQualifiedName:
4889 return P->FullyQualifiedName;
4890 }
4891
4892 assert(false && "Invalid CXPrintingPolicyProperty");
4893 return 0;
4894}
4895
4896void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4897 enum CXPrintingPolicyProperty Property,
4898 unsigned Value) {
4899 if (!Policy)
4900 return;
4901
4902 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4903 switch (Property) {
4904 case CXPrintingPolicy_Indentation:
4905 P->Indentation = Value;
4906 return;
4907 case CXPrintingPolicy_SuppressSpecifiers:
4908 P->SuppressSpecifiers = Value;
4909 return;
4910 case CXPrintingPolicy_SuppressTagKeyword:
4911 P->SuppressTagKeyword = Value;
4912 return;
4913 case CXPrintingPolicy_IncludeTagDefinition:
4914 P->IncludeTagDefinition = Value;
4915 return;
4916 case CXPrintingPolicy_SuppressScope:
4917 P->SuppressScope = Value;
4918 return;
4919 case CXPrintingPolicy_SuppressUnwrittenScope:
4920 P->SuppressUnwrittenScope = Value;
4921 return;
4922 case CXPrintingPolicy_SuppressInitializers:
4923 P->SuppressInitializers = Value;
4924 return;
4925 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4926 P->ConstantArraySizeAsWritten = Value;
4927 return;
4928 case CXPrintingPolicy_AnonymousTagLocations:
4929 P->AnonymousTagLocations = Value;
4930 return;
4931 case CXPrintingPolicy_SuppressStrongLifetime:
4932 P->SuppressStrongLifetime = Value;
4933 return;
4934 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4935 P->SuppressLifetimeQualifiers = Value;
4936 return;
4937 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4938 P->SuppressTemplateArgsInCXXConstructors = Value;
4939 return;
4940 case CXPrintingPolicy_Bool:
4941 P->Bool = Value;
4942 return;
4943 case CXPrintingPolicy_Restrict:
4944 P->Restrict = Value;
4945 return;
4946 case CXPrintingPolicy_Alignof:
4947 P->Alignof = Value;
4948 return;
4949 case CXPrintingPolicy_UnderscoreAlignof:
4950 P->UnderscoreAlignof = Value;
4951 return;
4952 case CXPrintingPolicy_UseVoidForZeroParams:
4953 P->UseVoidForZeroParams = Value;
4954 return;
4955 case CXPrintingPolicy_TerseOutput:
4956 P->TerseOutput = Value;
4957 return;
4958 case CXPrintingPolicy_PolishForDeclaration:
4959 P->PolishForDeclaration = Value;
4960 return;
4961 case CXPrintingPolicy_Half:
4962 P->Half = Value;
4963 return;
4964 case CXPrintingPolicy_MSWChar:
4965 P->MSWChar = Value;
4966 return;
4967 case CXPrintingPolicy_IncludeNewlines:
4968 P->IncludeNewlines = Value;
4969 return;
4970 case CXPrintingPolicy_MSVCFormatting:
4971 P->MSVCFormatting = Value;
4972 return;
4973 case CXPrintingPolicy_ConstantsAsWritten:
4974 P->ConstantsAsWritten = Value;
4975 return;
4976 case CXPrintingPolicy_SuppressImplicitBase:
4977 P->SuppressImplicitBase = Value;
4978 return;
4979 case CXPrintingPolicy_FullyQualifiedName:
4980 P->FullyQualifiedName = Value;
4981 return;
4982 }
4983
4984 assert(false && "Invalid CXPrintingPolicyProperty");
4985}
4986
4987CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4988 if (clang_Cursor_isNull(C))
4989 return cxstring::createEmpty();
4990
4991 if (clang_isDeclaration(C.kind)) {
4992 const Decl *D = getCursorDecl(C);
4993 if (!D)
4994 return cxstring::createEmpty();
4995
4996 SmallString<128> Str;
4997 llvm::raw_svector_ostream OS(Str);
4998 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4999 D->print(OS, UserPolicy ? *UserPolicy
5000 : getCursorContext(C).getPrintingPolicy());
5001
5002 return cxstring::createDup(OS.str());
5003 }
5004
5005 return cxstring::createEmpty();
5006}
5007
Guy Benyei11169dd2012-12-18 14:30:41 +00005008CXString clang_getCursorDisplayName(CXCursor C) {
5009 if (!clang_isDeclaration(C.kind))
5010 return clang_getCursorSpelling(C);
5011
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005012 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005014 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005015
5016 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005017 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 D = FunTmpl->getTemplatedDecl();
5019
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005020 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 SmallString<64> Str;
5022 llvm::raw_svector_ostream OS(Str);
5023 OS << *Function;
5024 if (Function->getPrimaryTemplate())
5025 OS << "<>";
5026 OS << "(";
5027 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5028 if (I)
5029 OS << ", ";
5030 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5031 }
5032
5033 if (Function->isVariadic()) {
5034 if (Function->getNumParams())
5035 OS << ", ";
5036 OS << "...";
5037 }
5038 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005039 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 }
5041
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005042 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 SmallString<64> Str;
5044 llvm::raw_svector_ostream OS(Str);
5045 OS << *ClassTemplate;
5046 OS << "<";
5047 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5048 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5049 if (I)
5050 OS << ", ";
5051
5052 NamedDecl *Param = Params->getParam(I);
5053 if (Param->getIdentifier()) {
5054 OS << Param->getIdentifier()->getName();
5055 continue;
5056 }
5057
5058 // There is no parameter name, which makes this tricky. Try to come up
5059 // with something useful that isn't too long.
5060 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Saar Razff1e0fc2020-01-15 02:48:42 +02005061 if (const auto *TC = TTP->getTypeConstraint()) {
5062 TC->getConceptNameInfo().printName(OS, Policy);
5063 if (TC->hasExplicitTemplateArgs())
5064 OS << "<...>";
5065 } else
5066 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 else if (NonTypeTemplateParmDecl *NTTP
5068 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5069 OS << NTTP->getType().getAsString(Policy);
5070 else
5071 OS << "template<...> class";
5072 }
5073
5074 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005075 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 }
5077
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005078 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5080 // If the type was explicitly written, use that.
5081 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005082 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005083
Benjamin Kramer9170e912013-02-22 15:46:01 +00005084 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 llvm::raw_svector_ostream OS(Str);
5086 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005087 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5088 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005089 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 }
5091
5092 return clang_getCursorSpelling(C);
5093}
5094
5095CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5096 switch (Kind) {
5097 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005161 case CXCursor_FixedPointLiteral:
5162 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005177 case CXCursor_OMPArraySectionExpr:
5178 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005229 case CXCursor_ObjCAvailabilityCheckExpr:
5230 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005231 case CXCursor_ObjCSelfExpr:
5232 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005259 case CXCursor_BuiltinBitCastExpr:
5260 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005262 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005268 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005270 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005272 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005273 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005274 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005275 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005276 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005278 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005280 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005282 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005284 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005286 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005288 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005290 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005292 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005294 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005295 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005296 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005298 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005300 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005301 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005302 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005303 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005304 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005305 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005306 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005307 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005308 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005309 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005310 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005312 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005313 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005314 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005316 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005317 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005318 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005319 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005320 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005321 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005322 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005323 case CXCursor_SEHLeaveStmt:
5324 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005325 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005326 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005327 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005328 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005329 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005330 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005332 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005334 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005336 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005338 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005340 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005342 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005344 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005346 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005348 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005350 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005353 case CXCursor_PackedAttr:
5354 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005355 case CXCursor_PureAttr:
5356 return cxstring::createRef("attribute(pure)");
5357 case CXCursor_ConstAttr:
5358 return cxstring::createRef("attribute(const)");
5359 case CXCursor_NoDuplicateAttr:
5360 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005361 case CXCursor_CUDAConstantAttr:
5362 return cxstring::createRef("attribute(constant)");
5363 case CXCursor_CUDADeviceAttr:
5364 return cxstring::createRef("attribute(device)");
5365 case CXCursor_CUDAGlobalAttr:
5366 return cxstring::createRef("attribute(global)");
5367 case CXCursor_CUDAHostAttr:
5368 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005369 case CXCursor_CUDASharedAttr:
5370 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005371 case CXCursor_VisibilityAttr:
5372 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005373 case CXCursor_DLLExport:
5374 return cxstring::createRef("attribute(dllexport)");
5375 case CXCursor_DLLImport:
5376 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005377 case CXCursor_NSReturnsRetained:
5378 return cxstring::createRef("attribute(ns_returns_retained)");
5379 case CXCursor_NSReturnsNotRetained:
5380 return cxstring::createRef("attribute(ns_returns_not_retained)");
5381 case CXCursor_NSReturnsAutoreleased:
5382 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5383 case CXCursor_NSConsumesSelf:
5384 return cxstring::createRef("attribute(ns_consumes_self)");
5385 case CXCursor_NSConsumed:
5386 return cxstring::createRef("attribute(ns_consumed)");
5387 case CXCursor_ObjCException:
5388 return cxstring::createRef("attribute(objc_exception)");
5389 case CXCursor_ObjCNSObject:
5390 return cxstring::createRef("attribute(NSObject)");
5391 case CXCursor_ObjCIndependentClass:
5392 return cxstring::createRef("attribute(objc_independent_class)");
5393 case CXCursor_ObjCPreciseLifetime:
5394 return cxstring::createRef("attribute(objc_precise_lifetime)");
5395 case CXCursor_ObjCReturnsInnerPointer:
5396 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5397 case CXCursor_ObjCRequiresSuper:
5398 return cxstring::createRef("attribute(objc_requires_super)");
5399 case CXCursor_ObjCRootClass:
5400 return cxstring::createRef("attribute(objc_root_class)");
5401 case CXCursor_ObjCSubclassingRestricted:
5402 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5403 case CXCursor_ObjCExplicitProtocolImpl:
5404 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5405 case CXCursor_ObjCDesignatedInitializer:
5406 return cxstring::createRef("attribute(objc_designated_initializer)");
5407 case CXCursor_ObjCRuntimeVisible:
5408 return cxstring::createRef("attribute(objc_runtime_visible)");
5409 case CXCursor_ObjCBoxable:
5410 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005411 case CXCursor_FlagEnum:
5412 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005413 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005414 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005415 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005416 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005417 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005418 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005419 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005420 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005421 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005422 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005424 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005425 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005426 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005427 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005428 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005429 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005430 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005431 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005432 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005433 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005434 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005435 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005436 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005437 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005438 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005439 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005440 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005441 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005442 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005443 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005444 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005445 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005446 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005447 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005448 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005449 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005450 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005451 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005452 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005453 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005454 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005455 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005456 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005457 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005458 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005459 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005460 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005461 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005462 return cxstring::createRef("OMPParallelDirective");
5463 case CXCursor_OMPSimdDirective:
5464 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005465 case CXCursor_OMPForDirective:
5466 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005467 case CXCursor_OMPForSimdDirective:
5468 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005469 case CXCursor_OMPSectionsDirective:
5470 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005471 case CXCursor_OMPSectionDirective:
5472 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005473 case CXCursor_OMPSingleDirective:
5474 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005475 case CXCursor_OMPMasterDirective:
5476 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005477 case CXCursor_OMPCriticalDirective:
5478 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005479 case CXCursor_OMPParallelForDirective:
5480 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005481 case CXCursor_OMPParallelForSimdDirective:
5482 return cxstring::createRef("OMPParallelForSimdDirective");
cchen47d60942019-12-05 13:43:48 -05005483 case CXCursor_OMPParallelMasterDirective:
5484 return cxstring::createRef("OMPParallelMasterDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005485 case CXCursor_OMPParallelSectionsDirective:
5486 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005487 case CXCursor_OMPTaskDirective:
5488 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005489 case CXCursor_OMPTaskyieldDirective:
5490 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005491 case CXCursor_OMPBarrierDirective:
5492 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005493 case CXCursor_OMPTaskwaitDirective:
5494 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005495 case CXCursor_OMPTaskgroupDirective:
5496 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005497 case CXCursor_OMPFlushDirective:
5498 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005499 case CXCursor_OMPOrderedDirective:
5500 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005501 case CXCursor_OMPAtomicDirective:
5502 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005503 case CXCursor_OMPTargetDirective:
5504 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005505 case CXCursor_OMPTargetDataDirective:
5506 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005507 case CXCursor_OMPTargetEnterDataDirective:
5508 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005509 case CXCursor_OMPTargetExitDataDirective:
5510 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005511 case CXCursor_OMPTargetParallelDirective:
5512 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005513 case CXCursor_OMPTargetParallelForDirective:
5514 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005515 case CXCursor_OMPTargetUpdateDirective:
5516 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005517 case CXCursor_OMPTeamsDirective:
5518 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005519 case CXCursor_OMPCancellationPointDirective:
5520 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005521 case CXCursor_OMPCancelDirective:
5522 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005523 case CXCursor_OMPTaskLoopDirective:
5524 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005525 case CXCursor_OMPTaskLoopSimdDirective:
5526 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005527 case CXCursor_OMPMasterTaskLoopDirective:
5528 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005529 case CXCursor_OMPMasterTaskLoopSimdDirective:
5530 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005531 case CXCursor_OMPParallelMasterTaskLoopDirective:
5532 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Alexey Bataev14a388f2019-10-25 10:27:13 -04005533 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5534 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005535 case CXCursor_OMPDistributeDirective:
5536 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005537 case CXCursor_OMPDistributeParallelForDirective:
5538 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005539 case CXCursor_OMPDistributeParallelForSimdDirective:
5540 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005541 case CXCursor_OMPDistributeSimdDirective:
5542 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005543 case CXCursor_OMPTargetParallelForSimdDirective:
5544 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005545 case CXCursor_OMPTargetSimdDirective:
5546 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005547 case CXCursor_OMPTeamsDistributeDirective:
5548 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005549 case CXCursor_OMPTeamsDistributeSimdDirective:
5550 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005551 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5552 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005553 case CXCursor_OMPTeamsDistributeParallelForDirective:
5554 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005555 case CXCursor_OMPTargetTeamsDirective:
5556 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005557 case CXCursor_OMPTargetTeamsDistributeDirective:
5558 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005559 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5560 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005561 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5562 return cxstring::createRef(
5563 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005564 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5565 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005566 case CXCursor_OverloadCandidate:
5567 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005568 case CXCursor_TypeAliasTemplateDecl:
5569 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005570 case CXCursor_StaticAssert:
5571 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005572 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005573 return cxstring::createRef("FriendDecl");
5574 case CXCursor_ConvergentAttr:
5575 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005576 case CXCursor_WarnUnusedAttr:
5577 return cxstring::createRef("attribute(warn_unused)");
5578 case CXCursor_WarnUnusedResultAttr:
5579 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005580 case CXCursor_AlignedAttr:
5581 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005582 }
5583
5584 llvm_unreachable("Unhandled CXCursorKind");
5585}
5586
5587struct GetCursorData {
5588 SourceLocation TokenBeginLoc;
5589 bool PointsAtMacroArgExpansion;
5590 bool VisitedObjCPropertyImplDecl;
5591 SourceLocation VisitedDeclaratorDeclStartLoc;
5592 CXCursor &BestCursor;
5593
5594 GetCursorData(SourceManager &SM,
5595 SourceLocation tokenBegin, CXCursor &outputCursor)
5596 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5597 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5598 VisitedObjCPropertyImplDecl = false;
5599 }
5600};
5601
5602static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5603 CXCursor parent,
5604 CXClientData client_data) {
5605 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5606 CXCursor *BestCursor = &Data->BestCursor;
5607
5608 // If we point inside a macro argument we should provide info of what the
5609 // token is so use the actual cursor, don't replace it with a macro expansion
5610 // cursor.
5611 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5612 return CXChildVisit_Recurse;
5613
5614 if (clang_isDeclaration(cursor.kind)) {
5615 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005616 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005617 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5618 if (MD->isImplicit())
5619 return CXChildVisit_Break;
5620
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005621 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005622 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5623 // Check that when we have multiple @class references in the same line,
5624 // that later ones do not override the previous ones.
5625 // If we have:
5626 // @class Foo, Bar;
5627 // source ranges for both start at '@', so 'Bar' will end up overriding
5628 // 'Foo' even though the cursor location was at 'Foo'.
5629 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5630 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005631 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005632 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5633 if (PrevID != ID &&
5634 !PrevID->isThisDeclarationADefinition() &&
5635 !ID->isThisDeclarationADefinition())
5636 return CXChildVisit_Break;
5637 }
5638
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005639 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005640 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5641 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5642 // Check that when we have multiple declarators in the same line,
5643 // that later ones do not override the previous ones.
5644 // If we have:
5645 // int Foo, Bar;
5646 // source ranges for both start at 'int', so 'Bar' will end up overriding
5647 // 'Foo' even though the cursor location was at 'Foo'.
5648 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5649 return CXChildVisit_Break;
5650 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5651
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005652 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005653 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5654 (void)PropImp;
5655 // Check that when we have multiple @synthesize in the same line,
5656 // that later ones do not override the previous ones.
5657 // If we have:
5658 // @synthesize Foo, Bar;
5659 // source ranges for both start at '@', so 'Bar' will end up overriding
5660 // 'Foo' even though the cursor location was at 'Foo'.
5661 if (Data->VisitedObjCPropertyImplDecl)
5662 return CXChildVisit_Break;
5663 Data->VisitedObjCPropertyImplDecl = true;
5664 }
5665 }
5666
5667 if (clang_isExpression(cursor.kind) &&
5668 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005669 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005670 // Avoid having the cursor of an expression replace the declaration cursor
5671 // when the expression source range overlaps the declaration range.
5672 // This can happen for C++ constructor expressions whose range generally
5673 // include the variable declaration, e.g.:
5674 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5675 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5676 D->getLocation() == Data->TokenBeginLoc)
5677 return CXChildVisit_Break;
5678 }
5679 }
5680
5681 // If our current best cursor is the construction of a temporary object,
5682 // don't replace that cursor with a type reference, because we want
5683 // clang_getCursor() to point at the constructor.
5684 if (clang_isExpression(BestCursor->kind) &&
5685 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5686 cursor.kind == CXCursor_TypeRef) {
5687 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5688 // as having the actual point on the type reference.
5689 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5690 return CXChildVisit_Recurse;
5691 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005692
5693 // If we already have an Objective-C superclass reference, don't
5694 // update it further.
5695 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5696 return CXChildVisit_Break;
5697
Guy Benyei11169dd2012-12-18 14:30:41 +00005698 *BestCursor = cursor;
5699 return CXChildVisit_Recurse;
5700}
5701
5702CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005703 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005704 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005705 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005706 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005707
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005708 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005709 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5710
5711 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5712 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5713
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005714 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005715 CXFile SearchFile;
5716 unsigned SearchLine, SearchColumn;
5717 CXFile ResultFile;
5718 unsigned ResultLine, ResultColumn;
5719 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5720 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5721 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005722
5723 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5724 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005725 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005726 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005727 SearchFileName = clang_getFileName(SearchFile);
5728 ResultFileName = clang_getFileName(ResultFile);
5729 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5730 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005731 *Log << llvm::format("(%s:%d:%d) = %s",
5732 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5733 clang_getCString(KindSpelling))
5734 << llvm::format("(%s:%d:%d):%s%s",
5735 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5736 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005737 clang_disposeString(SearchFileName);
5738 clang_disposeString(ResultFileName);
5739 clang_disposeString(KindSpelling);
5740 clang_disposeString(USR);
5741
5742 CXCursor Definition = clang_getCursorDefinition(Result);
5743 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5744 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5745 CXString DefinitionKindSpelling
5746 = clang_getCursorKindSpelling(Definition.kind);
5747 CXFile DefinitionFile;
5748 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005749 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005750 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005751 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005752 *Log << llvm::format(" -> %s(%s:%d:%d)",
5753 clang_getCString(DefinitionKindSpelling),
5754 clang_getCString(DefinitionFileName),
5755 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005756 clang_disposeString(DefinitionFileName);
5757 clang_disposeString(DefinitionKindSpelling);
5758 }
5759 }
5760
5761 return Result;
5762}
5763
5764CXCursor clang_getNullCursor(void) {
5765 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5766}
5767
5768unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005769 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5770 // can't set consistently. For example, when visiting a DeclStmt we will set
5771 // it but we don't set it on the result of clang_getCursorDefinition for
5772 // a reference of the same declaration.
5773 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5774 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5775 // to provide that kind of info.
5776 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005777 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005778 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005779 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005780
Guy Benyei11169dd2012-12-18 14:30:41 +00005781 return X == Y;
5782}
5783
5784unsigned clang_hashCursor(CXCursor C) {
5785 unsigned Index = 0;
5786 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5787 Index = 1;
5788
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005789 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005790 std::make_pair(C.kind, C.data[Index]));
5791}
5792
5793unsigned clang_isInvalid(enum CXCursorKind K) {
5794 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5795}
5796
5797unsigned clang_isDeclaration(enum CXCursorKind K) {
5798 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005799 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5800}
5801
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005802unsigned clang_isInvalidDeclaration(CXCursor C) {
5803 if (clang_isDeclaration(C.kind)) {
5804 if (const Decl *D = getCursorDecl(C))
5805 return D->isInvalidDecl();
5806 }
5807
5808 return 0;
5809}
5810
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005811unsigned clang_isReference(enum CXCursorKind K) {
5812 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5813}
Guy Benyei11169dd2012-12-18 14:30:41 +00005814
5815unsigned clang_isExpression(enum CXCursorKind K) {
5816 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5817}
5818
5819unsigned clang_isStatement(enum CXCursorKind K) {
5820 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5821}
5822
5823unsigned clang_isAttribute(enum CXCursorKind K) {
5824 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5825}
5826
5827unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5828 return K == CXCursor_TranslationUnit;
5829}
5830
5831unsigned clang_isPreprocessing(enum CXCursorKind K) {
5832 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5833}
5834
5835unsigned clang_isUnexposed(enum CXCursorKind K) {
5836 switch (K) {
5837 case CXCursor_UnexposedDecl:
5838 case CXCursor_UnexposedExpr:
5839 case CXCursor_UnexposedStmt:
5840 case CXCursor_UnexposedAttr:
5841 return true;
5842 default:
5843 return false;
5844 }
5845}
5846
5847CXCursorKind clang_getCursorKind(CXCursor C) {
5848 return C.kind;
5849}
5850
5851CXSourceLocation clang_getCursorLocation(CXCursor C) {
5852 if (clang_isReference(C.kind)) {
5853 switch (C.kind) {
5854 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005855 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005856 = getCursorObjCSuperClassRef(C);
5857 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5858 }
5859
5860 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005861 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005862 = getCursorObjCProtocolRef(C);
5863 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5864 }
5865
5866 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005867 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005868 = getCursorObjCClassRef(C);
5869 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5870 }
5871
5872 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005873 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005874 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5875 }
5876
5877 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005878 std::pair<const TemplateDecl *, SourceLocation> P =
5879 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005880 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5881 }
5882
5883 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005884 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005885 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5886 }
5887
5888 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005889 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005890 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5891 }
5892
5893 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005894 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005895 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5896 }
5897
5898 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005899 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005900 if (!BaseSpec)
5901 return clang_getNullLocation();
5902
5903 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5904 return cxloc::translateSourceLocation(getCursorContext(C),
5905 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005906
Guy Benyei11169dd2012-12-18 14:30:41 +00005907 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005908 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005909 }
5910
5911 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005912 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005913 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5914 }
5915
5916 case CXCursor_OverloadedDeclRef:
5917 return cxloc::translateSourceLocation(getCursorContext(C),
5918 getCursorOverloadedDeclRef(C).second);
5919
5920 default:
5921 // FIXME: Need a way to enumerate all non-reference cases.
5922 llvm_unreachable("Missed a reference kind");
5923 }
5924 }
5925
5926 if (clang_isExpression(C.kind))
5927 return cxloc::translateSourceLocation(getCursorContext(C),
5928 getLocationFromExpr(getCursorExpr(C)));
5929
5930 if (clang_isStatement(C.kind))
5931 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005932 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005933
5934 if (C.kind == CXCursor_PreprocessingDirective) {
5935 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5936 return cxloc::translateSourceLocation(getCursorContext(C), L);
5937 }
5938
5939 if (C.kind == CXCursor_MacroExpansion) {
5940 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005941 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005942 return cxloc::translateSourceLocation(getCursorContext(C), L);
5943 }
5944
5945 if (C.kind == CXCursor_MacroDefinition) {
5946 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5947 return cxloc::translateSourceLocation(getCursorContext(C), L);
5948 }
5949
5950 if (C.kind == CXCursor_InclusionDirective) {
5951 SourceLocation L
5952 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5953 return cxloc::translateSourceLocation(getCursorContext(C), L);
5954 }
5955
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005956 if (clang_isAttribute(C.kind)) {
5957 SourceLocation L
5958 = cxcursor::getCursorAttr(C)->getLocation();
5959 return cxloc::translateSourceLocation(getCursorContext(C), L);
5960 }
5961
Guy Benyei11169dd2012-12-18 14:30:41 +00005962 if (!clang_isDeclaration(C.kind))
5963 return clang_getNullLocation();
5964
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005965 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005966 if (!D)
5967 return clang_getNullLocation();
5968
5969 SourceLocation Loc = D->getLocation();
5970 // FIXME: Multiple variables declared in a single declaration
5971 // currently lack the information needed to correctly determine their
5972 // ranges when accounting for the type-specifier. We use context
5973 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5974 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005975 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 if (!cxcursor::isFirstInDeclGroup(C))
5977 Loc = VD->getLocation();
5978 }
5979
5980 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005981 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005982 Loc = MD->getSelectorStartLoc();
5983
5984 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5985}
5986
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005987} // end extern "C"
5988
Guy Benyei11169dd2012-12-18 14:30:41 +00005989CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5990 assert(TU);
5991
5992 // Guard against an invalid SourceLocation, or we may assert in one
5993 // of the following calls.
5994 if (SLoc.isInvalid())
5995 return clang_getNullCursor();
5996
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005997 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005998
5999 // Translate the given source location to make it point at the beginning of
6000 // the token under the cursor.
6001 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
6002 CXXUnit->getASTContext().getLangOpts());
6003
6004 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
6005 if (SLoc.isValid()) {
6006 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
6007 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
6008 /*VisitPreprocessorLast=*/true,
6009 /*VisitIncludedEntities=*/false,
6010 SourceLocation(SLoc));
6011 CursorVis.visitFileRegion();
6012 }
6013
6014 return Result;
6015}
6016
6017static SourceRange getRawCursorExtent(CXCursor C) {
6018 if (clang_isReference(C.kind)) {
6019 switch (C.kind) {
6020 case CXCursor_ObjCSuperClassRef:
6021 return getCursorObjCSuperClassRef(C).second;
6022
6023 case CXCursor_ObjCProtocolRef:
6024 return getCursorObjCProtocolRef(C).second;
6025
6026 case CXCursor_ObjCClassRef:
6027 return getCursorObjCClassRef(C).second;
6028
6029 case CXCursor_TypeRef:
6030 return getCursorTypeRef(C).second;
6031
6032 case CXCursor_TemplateRef:
6033 return getCursorTemplateRef(C).second;
6034
6035 case CXCursor_NamespaceRef:
6036 return getCursorNamespaceRef(C).second;
6037
6038 case CXCursor_MemberRef:
6039 return getCursorMemberRef(C).second;
6040
6041 case CXCursor_CXXBaseSpecifier:
6042 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6043
6044 case CXCursor_LabelRef:
6045 return getCursorLabelRef(C).second;
6046
6047 case CXCursor_OverloadedDeclRef:
6048 return getCursorOverloadedDeclRef(C).second;
6049
6050 case CXCursor_VariableRef:
6051 return getCursorVariableRef(C).second;
6052
6053 default:
6054 // FIXME: Need a way to enumerate all non-reference cases.
6055 llvm_unreachable("Missed a reference kind");
6056 }
6057 }
6058
6059 if (clang_isExpression(C.kind))
6060 return getCursorExpr(C)->getSourceRange();
6061
6062 if (clang_isStatement(C.kind))
6063 return getCursorStmt(C)->getSourceRange();
6064
6065 if (clang_isAttribute(C.kind))
6066 return getCursorAttr(C)->getRange();
6067
6068 if (C.kind == CXCursor_PreprocessingDirective)
6069 return cxcursor::getCursorPreprocessingDirective(C);
6070
6071 if (C.kind == CXCursor_MacroExpansion) {
6072 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006073 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 return TU->mapRangeFromPreamble(Range);
6075 }
6076
6077 if (C.kind == CXCursor_MacroDefinition) {
6078 ASTUnit *TU = getCursorASTUnit(C);
6079 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6080 return TU->mapRangeFromPreamble(Range);
6081 }
6082
6083 if (C.kind == CXCursor_InclusionDirective) {
6084 ASTUnit *TU = getCursorASTUnit(C);
6085 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6086 return TU->mapRangeFromPreamble(Range);
6087 }
6088
6089 if (C.kind == CXCursor_TranslationUnit) {
6090 ASTUnit *TU = getCursorASTUnit(C);
6091 FileID MainID = TU->getSourceManager().getMainFileID();
6092 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6093 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6094 return SourceRange(Start, End);
6095 }
6096
6097 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006098 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006099 if (!D)
6100 return SourceRange();
6101
6102 SourceRange R = D->getSourceRange();
6103 // FIXME: Multiple variables declared in a single declaration
6104 // currently lack the information needed to correctly determine their
6105 // ranges when accounting for the type-specifier. We use context
6106 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6107 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006108 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006109 if (!cxcursor::isFirstInDeclGroup(C))
6110 R.setBegin(VD->getLocation());
6111 }
6112 return R;
6113 }
6114 return SourceRange();
6115}
6116
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006117/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006118/// the decl-specifier-seq for declarations.
6119static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6120 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006121 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 if (!D)
6123 return SourceRange();
6124
6125 SourceRange R = D->getSourceRange();
6126
6127 // Adjust the start of the location for declarations preceded by
6128 // declaration specifiers.
6129 SourceLocation StartLoc;
6130 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6131 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006132 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006133 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006134 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006135 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 }
6137
6138 if (StartLoc.isValid() && R.getBegin().isValid() &&
6139 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6140 R.setBegin(StartLoc);
6141
6142 // FIXME: Multiple variables declared in a single declaration
6143 // currently lack the information needed to correctly determine their
6144 // ranges when accounting for the type-specifier. We use context
6145 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6146 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006147 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006148 if (!cxcursor::isFirstInDeclGroup(C))
6149 R.setBegin(VD->getLocation());
6150 }
6151
6152 return R;
6153 }
6154
6155 return getRawCursorExtent(C);
6156}
6157
Guy Benyei11169dd2012-12-18 14:30:41 +00006158CXSourceRange clang_getCursorExtent(CXCursor C) {
6159 SourceRange R = getRawCursorExtent(C);
6160 if (R.isInvalid())
6161 return clang_getNullRange();
6162
6163 return cxloc::translateSourceRange(getCursorContext(C), R);
6164}
6165
6166CXCursor clang_getCursorReferenced(CXCursor C) {
6167 if (clang_isInvalid(C.kind))
6168 return clang_getNullCursor();
6169
6170 CXTranslationUnit tu = getCursorTU(C);
6171 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006172 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006173 if (!D)
6174 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006175 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006176 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006177 if (const ObjCPropertyImplDecl *PropImpl =
6178 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006179 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6180 return MakeCXCursor(Property, tu);
6181
6182 return C;
6183 }
6184
6185 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006186 const Expr *E = getCursorExpr(C);
6187 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006188 if (D) {
6189 CXCursor declCursor = MakeCXCursor(D, tu);
6190 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6191 declCursor);
6192 return declCursor;
6193 }
6194
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006195 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 return MakeCursorOverloadedDeclRef(Ovl, tu);
6197
6198 return clang_getNullCursor();
6199 }
6200
6201 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006202 const Stmt *S = getCursorStmt(C);
6203 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006204 if (LabelDecl *label = Goto->getLabel())
6205 if (LabelStmt *labelS = label->getStmt())
6206 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6207
6208 return clang_getNullCursor();
6209 }
Richard Smith66a81862015-05-04 02:25:31 +00006210
Guy Benyei11169dd2012-12-18 14:30:41 +00006211 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006212 if (const MacroDefinitionRecord *Def =
6213 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 return MakeMacroDefinitionCursor(Def, tu);
6215 }
6216
6217 if (!clang_isReference(C.kind))
6218 return clang_getNullCursor();
6219
6220 switch (C.kind) {
6221 case CXCursor_ObjCSuperClassRef:
6222 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6223
6224 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006225 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6226 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006227 return MakeCXCursor(Def, tu);
6228
6229 return MakeCXCursor(Prot, tu);
6230 }
6231
6232 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006233 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6234 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 return MakeCXCursor(Def, tu);
6236
6237 return MakeCXCursor(Class, tu);
6238 }
6239
6240 case CXCursor_TypeRef:
6241 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6242
6243 case CXCursor_TemplateRef:
6244 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6245
6246 case CXCursor_NamespaceRef:
6247 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6248
6249 case CXCursor_MemberRef:
6250 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6251
6252 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006253 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006254 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6255 tu ));
6256 }
6257
6258 case CXCursor_LabelRef:
6259 // FIXME: We end up faking the "parent" declaration here because we
6260 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006261 return MakeCXCursor(getCursorLabelRef(C).first,
6262 cxtu::getASTUnit(tu)->getASTContext()
6263 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006264 tu);
6265
6266 case CXCursor_OverloadedDeclRef:
6267 return C;
6268
6269 case CXCursor_VariableRef:
6270 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6271
6272 default:
6273 // We would prefer to enumerate all non-reference cursor kinds here.
6274 llvm_unreachable("Unhandled reference cursor kind");
6275 }
6276}
6277
6278CXCursor clang_getCursorDefinition(CXCursor C) {
6279 if (clang_isInvalid(C.kind))
6280 return clang_getNullCursor();
6281
6282 CXTranslationUnit TU = getCursorTU(C);
6283
6284 bool WasReference = false;
6285 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6286 C = clang_getCursorReferenced(C);
6287 WasReference = true;
6288 }
6289
6290 if (C.kind == CXCursor_MacroExpansion)
6291 return clang_getCursorReferenced(C);
6292
6293 if (!clang_isDeclaration(C.kind))
6294 return clang_getNullCursor();
6295
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006296 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006297 if (!D)
6298 return clang_getNullCursor();
6299
6300 switch (D->getKind()) {
6301 // Declaration kinds that don't really separate the notions of
6302 // declaration and definition.
6303 case Decl::Namespace:
6304 case Decl::Typedef:
6305 case Decl::TypeAlias:
6306 case Decl::TypeAliasTemplate:
6307 case Decl::TemplateTypeParm:
6308 case Decl::EnumConstant:
6309 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006310 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006311 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006312 case Decl::IndirectField:
6313 case Decl::ObjCIvar:
6314 case Decl::ObjCAtDefsField:
6315 case Decl::ImplicitParam:
6316 case Decl::ParmVar:
6317 case Decl::NonTypeTemplateParm:
6318 case Decl::TemplateTemplateParm:
6319 case Decl::ObjCCategoryImpl:
6320 case Decl::ObjCImplementation:
6321 case Decl::AccessSpec:
6322 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006323 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006324 case Decl::ObjCPropertyImpl:
6325 case Decl::FileScopeAsm:
6326 case Decl::StaticAssert:
6327 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006328 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006329 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 case Decl::Label: // FIXME: Is this right??
6331 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006332 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006333 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006334 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006335 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006336 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006337 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006338 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006339 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006340 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006341 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006342 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006343 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006344 case Decl::Concept:
Tykerb0561b32019-11-17 11:41:55 +01006345 case Decl::LifetimeExtendedTemporary:
Saar Raza0f50d72020-01-18 09:11:43 +02006346 case Decl::RequiresExprBody:
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 return C;
6348
6349 // Declaration kinds that don't make any sense here, but are
6350 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006351 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006353 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006354 break;
6355
6356 // Declaration kinds for which the definition is not resolvable.
6357 case Decl::UnresolvedUsingTypename:
6358 case Decl::UnresolvedUsingValue:
6359 break;
6360
6361 case Decl::UsingDirective:
6362 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6363 TU);
6364
6365 case Decl::NamespaceAlias:
6366 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6367
6368 case Decl::Enum:
6369 case Decl::Record:
6370 case Decl::CXXRecord:
6371 case Decl::ClassTemplateSpecialization:
6372 case Decl::ClassTemplatePartialSpecialization:
6373 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6374 return MakeCXCursor(Def, TU);
6375 return clang_getNullCursor();
6376
6377 case Decl::Function:
6378 case Decl::CXXMethod:
6379 case Decl::CXXConstructor:
6380 case Decl::CXXDestructor:
6381 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006382 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006383 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006384 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006385 return clang_getNullCursor();
6386 }
6387
Larisse Voufo39a1e502013-08-06 01:03:05 +00006388 case Decl::Var:
6389 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006390 case Decl::VarTemplatePartialSpecialization:
6391 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006392 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006393 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 return MakeCXCursor(Def, TU);
6395 return clang_getNullCursor();
6396 }
6397
6398 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006399 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006400 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6401 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6402 return clang_getNullCursor();
6403 }
6404
6405 case Decl::ClassTemplate: {
6406 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6407 ->getDefinition())
6408 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6409 TU);
6410 return clang_getNullCursor();
6411 }
6412
Larisse Voufo39a1e502013-08-06 01:03:05 +00006413 case Decl::VarTemplate: {
6414 if (VarDecl *Def =
6415 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6416 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6417 return clang_getNullCursor();
6418 }
6419
Guy Benyei11169dd2012-12-18 14:30:41 +00006420 case Decl::Using:
6421 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6422 D->getLocation(), TU);
6423
6424 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006425 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006426 return clang_getCursorDefinition(
6427 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6428 TU));
6429
6430 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006431 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 if (Method->isThisDeclarationADefinition())
6433 return C;
6434
6435 // Dig out the method definition in the associated
6436 // @implementation, if we have it.
6437 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006438 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6440 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6441 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6442 Method->isInstanceMethod()))
6443 if (Def->isThisDeclarationADefinition())
6444 return MakeCXCursor(Def, TU);
6445
6446 return clang_getNullCursor();
6447 }
6448
6449 case Decl::ObjCCategory:
6450 if (ObjCCategoryImplDecl *Impl
6451 = cast<ObjCCategoryDecl>(D)->getImplementation())
6452 return MakeCXCursor(Impl, TU);
6453 return clang_getNullCursor();
6454
6455 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006456 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 return MakeCXCursor(Def, TU);
6458 return clang_getNullCursor();
6459
6460 case Decl::ObjCInterface: {
6461 // There are two notions of a "definition" for an Objective-C
6462 // class: the interface and its implementation. When we resolved a
6463 // reference to an Objective-C class, produce the @interface as
6464 // the definition; when we were provided with the interface,
6465 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006466 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006467 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006468 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006469 return MakeCXCursor(Def, TU);
6470 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6471 return MakeCXCursor(Impl, TU);
6472 return clang_getNullCursor();
6473 }
6474
6475 case Decl::ObjCProperty:
6476 // FIXME: We don't really know where to find the
6477 // ObjCPropertyImplDecls that implement this property.
6478 return clang_getNullCursor();
6479
6480 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006481 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006482 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006483 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 return MakeCXCursor(Def, TU);
6485
6486 return clang_getNullCursor();
6487
6488 case Decl::Friend:
6489 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6490 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6491 return clang_getNullCursor();
6492
6493 case Decl::FriendTemplate:
6494 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6495 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6496 return clang_getNullCursor();
6497 }
6498
6499 return clang_getNullCursor();
6500}
6501
6502unsigned clang_isCursorDefinition(CXCursor C) {
6503 if (!clang_isDeclaration(C.kind))
6504 return 0;
6505
6506 return clang_getCursorDefinition(C) == C;
6507}
6508
6509CXCursor clang_getCanonicalCursor(CXCursor C) {
6510 if (!clang_isDeclaration(C.kind))
6511 return C;
6512
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006513 if (const Decl *D = getCursorDecl(C)) {
6514 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006515 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6516 return MakeCXCursor(CatD, getCursorTU(C));
6517
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006518 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6519 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006520 return MakeCXCursor(IFD, getCursorTU(C));
6521
6522 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6523 }
6524
6525 return C;
6526}
6527
6528int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6529 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6530}
6531
6532unsigned clang_getNumOverloadedDecls(CXCursor C) {
6533 if (C.kind != CXCursor_OverloadedDeclRef)
6534 return 0;
6535
6536 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006537 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006538 return E->getNumDecls();
6539
6540 if (OverloadedTemplateStorage *S
6541 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6542 return S->size();
6543
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006544 const Decl *D = Storage.get<const Decl *>();
6545 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006546 return Using->shadow_size();
6547
6548 return 0;
6549}
6550
6551CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6552 if (cursor.kind != CXCursor_OverloadedDeclRef)
6553 return clang_getNullCursor();
6554
6555 if (index >= clang_getNumOverloadedDecls(cursor))
6556 return clang_getNullCursor();
6557
6558 CXTranslationUnit TU = getCursorTU(cursor);
6559 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006560 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006561 return MakeCXCursor(E->decls_begin()[index], TU);
6562
6563 if (OverloadedTemplateStorage *S
6564 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6565 return MakeCXCursor(S->begin()[index], TU);
6566
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006567 const Decl *D = Storage.get<const Decl *>();
6568 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006569 // FIXME: This is, unfortunately, linear time.
6570 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6571 std::advance(Pos, index);
6572 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6573 }
6574
6575 return clang_getNullCursor();
6576}
6577
6578void clang_getDefinitionSpellingAndExtent(CXCursor C,
6579 const char **startBuf,
6580 const char **endBuf,
6581 unsigned *startLine,
6582 unsigned *startColumn,
6583 unsigned *endLine,
6584 unsigned *endColumn) {
6585 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006586 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006587 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6588
6589 SourceManager &SM = FD->getASTContext().getSourceManager();
6590 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6591 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6592 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6593 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6594 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6595 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6596}
6597
6598
6599CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6600 unsigned PieceIndex) {
6601 RefNamePieces Pieces;
6602
6603 switch (C.kind) {
6604 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006605 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006606 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6607 E->getQualifierLoc().getSourceRange());
6608 break;
6609
6610 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006611 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6612 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6613 Pieces =
6614 buildPieces(NameFlags, false, E->getNameInfo(),
6615 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6616 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006617 break;
6618
6619 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006620 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006622 const Expr *Callee = OCE->getCallee();
6623 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006624 Callee = ICE->getSubExpr();
6625
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006626 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006627 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6628 DRE->getQualifierLoc().getSourceRange());
6629 }
6630 break;
6631
6632 default:
6633 break;
6634 }
6635
6636 if (Pieces.empty()) {
6637 if (PieceIndex == 0)
6638 return clang_getCursorExtent(C);
6639 } else if (PieceIndex < Pieces.size()) {
6640 SourceRange R = Pieces[PieceIndex];
6641 if (R.isValid())
6642 return cxloc::translateSourceRange(getCursorContext(C), R);
6643 }
6644
6645 return clang_getNullRange();
6646}
6647
6648void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006649 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6650 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006651}
6652
6653void clang_executeOnThread(void (*fn)(void*), void *user_data,
6654 unsigned stack_size) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05006655 llvm::llvm_execute_on_thread(fn, user_data,
6656 stack_size == 0
6657 ? clang::DesiredStackSize
6658 : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006659}
6660
Guy Benyei11169dd2012-12-18 14:30:41 +00006661//===----------------------------------------------------------------------===//
6662// Token-based Operations.
6663//===----------------------------------------------------------------------===//
6664
6665/* CXToken layout:
6666 * int_data[0]: a CXTokenKind
6667 * int_data[1]: starting token location
6668 * int_data[2]: token length
6669 * int_data[3]: reserved
6670 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6671 * otherwise unused.
6672 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006673CXTokenKind clang_getTokenKind(CXToken CXTok) {
6674 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6675}
6676
6677CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6678 switch (clang_getTokenKind(CXTok)) {
6679 case CXToken_Identifier:
6680 case CXToken_Keyword:
6681 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006682 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 ->getNameStart());
6684
6685 case CXToken_Literal: {
6686 // We have stashed the starting pointer in the ptr_data field. Use it.
6687 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006688 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006689 }
6690
6691 case CXToken_Punctuation:
6692 case CXToken_Comment:
6693 break;
6694 }
6695
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006696 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006697 LOG_BAD_TU(TU);
6698 return cxstring::createEmpty();
6699 }
6700
Guy Benyei11169dd2012-12-18 14:30:41 +00006701 // We have to find the starting buffer pointer the hard way, by
6702 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006703 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006704 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006705 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006706
6707 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6708 std::pair<FileID, unsigned> LocInfo
6709 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6710 bool Invalid = false;
6711 StringRef Buffer
6712 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6713 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006714 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006715
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006716 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006717}
6718
6719CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006720 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006721 LOG_BAD_TU(TU);
6722 return clang_getNullLocation();
6723 }
6724
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006725 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 if (!CXXUnit)
6727 return clang_getNullLocation();
6728
6729 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6730 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6731}
6732
6733CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006734 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006735 LOG_BAD_TU(TU);
6736 return clang_getNullRange();
6737 }
6738
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006739 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006740 if (!CXXUnit)
6741 return clang_getNullRange();
6742
6743 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6744 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6745}
6746
6747static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6748 SmallVectorImpl<CXToken> &CXTokens) {
6749 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6750 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006751 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006752 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006753 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006754
6755 // Cannot tokenize across files.
6756 if (BeginLocInfo.first != EndLocInfo.first)
6757 return;
6758
6759 // Create a lexer
6760 bool Invalid = false;
6761 StringRef Buffer
6762 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6763 if (Invalid)
6764 return;
6765
6766 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6767 CXXUnit->getASTContext().getLangOpts(),
6768 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6769 Lex.SetCommentRetentionState(true);
6770
6771 // Lex tokens until we hit the end of the range.
6772 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6773 Token Tok;
6774 bool previousWasAt = false;
6775 do {
6776 // Lex the next token
6777 Lex.LexFromRawLexer(Tok);
6778 if (Tok.is(tok::eof))
6779 break;
6780
6781 // Initialize the CXToken.
6782 CXToken CXTok;
6783
6784 // - Common fields
6785 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6786 CXTok.int_data[2] = Tok.getLength();
6787 CXTok.int_data[3] = 0;
6788
6789 // - Kind-specific fields
6790 if (Tok.isLiteral()) {
6791 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006792 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006793 } else if (Tok.is(tok::raw_identifier)) {
6794 // Lookup the identifier to determine whether we have a keyword.
6795 IdentifierInfo *II
6796 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6797
6798 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6799 CXTok.int_data[0] = CXToken_Keyword;
6800 }
6801 else {
6802 CXTok.int_data[0] = Tok.is(tok::identifier)
6803 ? CXToken_Identifier
6804 : CXToken_Keyword;
6805 }
6806 CXTok.ptr_data = II;
6807 } else if (Tok.is(tok::comment)) {
6808 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006809 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006810 } else {
6811 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006812 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006813 }
6814 CXTokens.push_back(CXTok);
6815 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006816 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006817}
6818
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006819CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6820 LOG_FUNC_SECTION {
6821 *Log << TU << ' ' << Location;
6822 }
6823
6824 if (isNotUsableTU(TU)) {
6825 LOG_BAD_TU(TU);
6826 return NULL;
6827 }
6828
6829 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6830 if (!CXXUnit)
6831 return NULL;
6832
6833 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6834 if (Begin.isInvalid())
6835 return NULL;
6836 SourceManager &SM = CXXUnit->getSourceManager();
6837 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6838 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6839
6840 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6841
6842 SmallVector<CXToken, 32> CXTokens;
6843 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6844
6845 if (CXTokens.empty())
6846 return NULL;
6847
6848 CXTokens.resize(1);
6849 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6850
6851 memmove(Token, CXTokens.data(), sizeof(CXToken));
6852 return Token;
6853}
6854
Guy Benyei11169dd2012-12-18 14:30:41 +00006855void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6856 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006857 LOG_FUNC_SECTION {
6858 *Log << TU << ' ' << Range;
6859 }
6860
Guy Benyei11169dd2012-12-18 14:30:41 +00006861 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006862 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006863 if (NumTokens)
6864 *NumTokens = 0;
6865
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006866 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006867 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006868 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006869 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006870
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006871 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006872 if (!CXXUnit || !Tokens || !NumTokens)
6873 return;
6874
6875 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6876
6877 SourceRange R = cxloc::translateCXSourceRange(Range);
6878 if (R.isInvalid())
6879 return;
6880
6881 SmallVector<CXToken, 32> CXTokens;
6882 getTokens(CXXUnit, R, CXTokens);
6883
6884 if (CXTokens.empty())
6885 return;
6886
Serge Pavlov52525732018-02-21 02:02:39 +00006887 *Tokens = static_cast<CXToken *>(
6888 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006889 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6890 *NumTokens = CXTokens.size();
6891}
6892
6893void clang_disposeTokens(CXTranslationUnit TU,
6894 CXToken *Tokens, unsigned NumTokens) {
6895 free(Tokens);
6896}
6897
Guy Benyei11169dd2012-12-18 14:30:41 +00006898//===----------------------------------------------------------------------===//
6899// Token annotation APIs.
6900//===----------------------------------------------------------------------===//
6901
Guy Benyei11169dd2012-12-18 14:30:41 +00006902static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6903 CXCursor parent,
6904 CXClientData client_data);
6905static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6906 CXClientData client_data);
6907
6908namespace {
6909class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 CXToken *Tokens;
6911 CXCursor *Cursors;
6912 unsigned NumTokens;
6913 unsigned TokIdx;
6914 unsigned PreprocessingTokIdx;
6915 CursorVisitor AnnotateVis;
6916 SourceManager &SrcMgr;
6917 bool HasContextSensitiveKeywords;
6918
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006919 struct PostChildrenAction {
6920 CXCursor cursor;
6921 enum Action { Invalid, Ignore, Postpone } action;
6922 };
6923 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6924
Guy Benyei11169dd2012-12-18 14:30:41 +00006925 struct PostChildrenInfo {
6926 CXCursor Cursor;
6927 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006928 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006929 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006930 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006931 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006932 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006933
6934 CXToken &getTok(unsigned Idx) {
6935 assert(Idx < NumTokens);
6936 return Tokens[Idx];
6937 }
6938 const CXToken &getTok(unsigned Idx) const {
6939 assert(Idx < NumTokens);
6940 return Tokens[Idx];
6941 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006942 bool MoreTokens() const { return TokIdx < NumTokens; }
6943 unsigned NextToken() const { return TokIdx; }
6944 void AdvanceToken() { ++TokIdx; }
6945 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006946 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 }
6948 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006949 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 }
6951 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006952 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006953 }
6954
6955 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006956 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006957 SourceRange);
6958
6959public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006960 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006961 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006962 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006964 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006965 AnnotateTokensVisitor, this,
6966 /*VisitPreprocessorLast=*/true,
6967 /*VisitIncludedEntities=*/false,
6968 RegionOfInterest,
6969 /*VisitDeclsOnly=*/false,
6970 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006971 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006972 HasContextSensitiveKeywords(false) { }
6973
6974 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6975 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006976 bool IsIgnoredChildCursor(CXCursor cursor) const;
6977 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6978
Guy Benyei11169dd2012-12-18 14:30:41 +00006979 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006980 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6981 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6982
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 void AnnotateTokens();
6984
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006985 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006986 /// context-sensitive keywords.
6987 bool hasContextSensitiveKeywords() const {
6988 return HasContextSensitiveKeywords;
6989 }
6990
6991 ~AnnotateTokensWorker() {
6992 assert(PostChildrenInfos.empty());
6993 }
6994};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006995}
Guy Benyei11169dd2012-12-18 14:30:41 +00006996
6997void AnnotateTokensWorker::AnnotateTokens() {
6998 // Walk the AST within the region of interest, annotating tokens
6999 // along the way.
7000 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007001}
Guy Benyei11169dd2012-12-18 14:30:41 +00007002
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007003bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
7004 if (PostChildrenInfos.empty())
7005 return false;
7006
7007 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
7008 if (ChildAction.cursor == cursor &&
7009 ChildAction.action == PostChildrenAction::Ignore) {
7010 return true;
7011 }
7012 }
7013
7014 return false;
7015}
7016
7017const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
7018 if (!clang_isExpression(Cursor.kind))
7019 return nullptr;
7020
7021 const Expr *E = getCursorExpr(Cursor);
7022 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7023 const OverloadedOperatorKind Kind = OCE->getOperator();
7024 if (Kind == OO_Call || Kind == OO_Subscript)
7025 return OCE;
7026 }
7027
7028 return nullptr;
7029}
7030
7031AnnotateTokensWorker::PostChildrenActions
7032AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7033 PostChildrenActions actions;
7034
7035 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
7036 // visited before the arguments to the operator call. For the Call and
7037 // Subscript operator the range of this DeclRefExpr includes the whole call
7038 // expression, so that all tokens in that range would be mapped to the
7039 // operator function, including the tokens of the arguments. To avoid that,
7040 // ensure to visit this DeclRefExpr as last node.
7041 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7042 const Expr *Callee = OCE->getCallee();
7043 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7044 const Expr *SubExpr = ICE->getSubExpr();
7045 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007046 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007047 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7048
7049 // Visit the DeclRefExpr as last.
7050 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7051 actions.push_back({cxChild, PostChildrenAction::Postpone});
7052
7053 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7054 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7055 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7056 actions.push_back({cxChild, PostChildrenAction::Ignore});
7057 }
7058 }
7059 }
7060
7061 return actions;
7062}
7063
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007064static inline void updateCursorAnnotation(CXCursor &Cursor,
7065 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007066 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007067 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007068 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007069}
7070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007071/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007072//// between the cursor location and the source range is the same as
7073/// \arg compResult.
7074///
7075/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7076/// Pass RangeOverlap to annotate tokens inside a range.
7077void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7078 RangeComparisonResult compResult,
7079 SourceRange range) {
7080 while (MoreTokens()) {
7081 const unsigned I = NextToken();
7082 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007083 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7084 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007085
7086 SourceLocation TokLoc = GetTokenLoc(I);
7087 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007088 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007089 AdvanceToken();
7090 continue;
7091 }
7092 break;
7093 }
7094}
7095
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007096/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007097/// \returns true if it advanced beyond all macro tokens, false otherwise.
7098bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007099 CXCursor updateC,
7100 RangeComparisonResult compResult,
7101 SourceRange range) {
7102 assert(MoreTokens());
7103 assert(isFunctionMacroToken(NextToken()) &&
7104 "Should be called only for macro arg tokens");
7105
7106 // This works differently than annotateAndAdvanceTokens; because expanded
7107 // macro arguments can have arbitrary translation-unit source order, we do not
7108 // advance the token index one by one until a token fails the range test.
7109 // We only advance once past all of the macro arg tokens if all of them
7110 // pass the range test. If one of them fails we keep the token index pointing
7111 // at the start of the macro arg tokens so that the failing token will be
7112 // annotated by a subsequent annotation try.
7113
7114 bool atLeastOneCompFail = false;
7115
7116 unsigned I = NextToken();
7117 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7118 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7119 if (TokLoc.isFileID())
7120 continue; // not macro arg token, it's parens or comma.
7121 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7122 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7123 Cursors[I] = updateC;
7124 } else
7125 atLeastOneCompFail = true;
7126 }
7127
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007128 if (atLeastOneCompFail)
7129 return false;
7130
7131 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7132 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007133}
7134
7135enum CXChildVisitResult
7136AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007137 SourceRange cursorRange = getRawCursorExtent(cursor);
7138 if (cursorRange.isInvalid())
7139 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007140
7141 if (IsIgnoredChildCursor(cursor))
7142 return CXChildVisit_Continue;
7143
Guy Benyei11169dd2012-12-18 14:30:41 +00007144 if (!HasContextSensitiveKeywords) {
7145 // Objective-C properties can have context-sensitive keywords.
7146 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007147 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007148 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7149 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7150 }
7151 // Objective-C methods can have context-sensitive keywords.
7152 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7153 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007154 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007155 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7156 if (Method->getObjCDeclQualifier())
7157 HasContextSensitiveKeywords = true;
7158 else {
David Majnemer59f77922016-06-24 04:05:48 +00007159 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007160 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007161 HasContextSensitiveKeywords = true;
7162 break;
7163 }
7164 }
7165 }
7166 }
7167 }
7168 // C++ methods can have context-sensitive keywords.
7169 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007170 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007171 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7172 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7173 HasContextSensitiveKeywords = true;
7174 }
7175 }
7176 // C++ classes can have context-sensitive keywords.
7177 else if (cursor.kind == CXCursor_StructDecl ||
7178 cursor.kind == CXCursor_ClassDecl ||
7179 cursor.kind == CXCursor_ClassTemplate ||
7180 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007181 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007182 if (D->hasAttr<FinalAttr>())
7183 HasContextSensitiveKeywords = true;
7184 }
7185 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007186
7187 // Don't override a property annotation with its getter/setter method.
7188 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7189 parent.kind == CXCursor_ObjCPropertyDecl)
7190 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007191
7192 if (clang_isPreprocessing(cursor.kind)) {
7193 // Items in the preprocessing record are kept separate from items in
7194 // declarations, so we keep a separate token index.
7195 unsigned SavedTokIdx = TokIdx;
7196 TokIdx = PreprocessingTokIdx;
7197
7198 // Skip tokens up until we catch up to the beginning of the preprocessing
7199 // entry.
7200 while (MoreTokens()) {
7201 const unsigned I = NextToken();
7202 SourceLocation TokLoc = GetTokenLoc(I);
7203 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7204 case RangeBefore:
7205 AdvanceToken();
7206 continue;
7207 case RangeAfter:
7208 case RangeOverlap:
7209 break;
7210 }
7211 break;
7212 }
7213
7214 // Look at all of the tokens within this range.
7215 while (MoreTokens()) {
7216 const unsigned I = NextToken();
7217 SourceLocation TokLoc = GetTokenLoc(I);
7218 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7219 case RangeBefore:
7220 llvm_unreachable("Infeasible");
7221 case RangeAfter:
7222 break;
7223 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007224 // For macro expansions, just note where the beginning of the macro
7225 // expansion occurs.
7226 if (cursor.kind == CXCursor_MacroExpansion) {
7227 if (TokLoc == cursorRange.getBegin())
7228 Cursors[I] = cursor;
7229 AdvanceToken();
7230 break;
7231 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007232 // We may have already annotated macro names inside macro definitions.
7233 if (Cursors[I].kind != CXCursor_MacroExpansion)
7234 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007235 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007236 continue;
7237 }
7238 break;
7239 }
7240
7241 // Save the preprocessing token index; restore the non-preprocessing
7242 // token index.
7243 PreprocessingTokIdx = TokIdx;
7244 TokIdx = SavedTokIdx;
7245 return CXChildVisit_Recurse;
7246 }
7247
7248 if (cursorRange.isInvalid())
7249 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007250
7251 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007252 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007253 const enum CXCursorKind K = clang_getCursorKind(parent);
7254 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007255 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7256 // Attributes are annotated out-of-order, skip tokens until we reach it.
7257 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 ? clang_getNullCursor() : parent;
7259
7260 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7261
7262 // Avoid having the cursor of an expression "overwrite" the annotation of the
7263 // variable declaration that it belongs to.
7264 // This can happen for C++ constructor expressions whose range generally
7265 // include the variable declaration, e.g.:
7266 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007267 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007268 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007269 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007270 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007271 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7272 E->getBeginLoc() == D->getLocation() &&
7273 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007274 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007275 AdvanceToken();
7276 }
7277 }
7278 }
7279
7280 // Before recursing into the children keep some state that we are going
7281 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7282 // extra work after the child nodes are visited.
7283 // Note that we don't call VisitChildren here to avoid traversing statements
7284 // code-recursively which can blow the stack.
7285
7286 PostChildrenInfo Info;
7287 Info.Cursor = cursor;
7288 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007289 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007290 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007291 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007292 PostChildrenInfos.push_back(Info);
7293
7294 return CXChildVisit_Recurse;
7295}
7296
7297bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7298 if (PostChildrenInfos.empty())
7299 return false;
7300 const PostChildrenInfo &Info = PostChildrenInfos.back();
7301 if (!clang_equalCursors(Info.Cursor, cursor))
7302 return false;
7303
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007304 HandlePostPonedChildCursors(Info);
7305
Guy Benyei11169dd2012-12-18 14:30:41 +00007306 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7307 const unsigned AfterChildren = NextToken();
7308 SourceRange cursorRange = Info.CursorRange;
7309
7310 // Scan the tokens that are at the end of the cursor, but are not captured
7311 // but the child cursors.
7312 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7313
7314 // Scan the tokens that are at the beginning of the cursor, but are not
7315 // capture by the child cursors.
7316 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7317 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7318 break;
7319
7320 Cursors[I] = cursor;
7321 }
7322
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007323 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7324 // encountered the attribute cursor.
7325 if (clang_isAttribute(cursor.kind))
7326 TokIdx = Info.BeforeReachingCursorIdx;
7327
Guy Benyei11169dd2012-12-18 14:30:41 +00007328 PostChildrenInfos.pop_back();
7329 return false;
7330}
7331
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007332void AnnotateTokensWorker::HandlePostPonedChildCursors(
7333 const PostChildrenInfo &Info) {
7334 for (const auto &ChildAction : Info.ChildActions) {
7335 if (ChildAction.action == PostChildrenAction::Postpone) {
7336 HandlePostPonedChildCursor(ChildAction.cursor,
7337 Info.BeforeChildrenTokenIdx);
7338 }
7339 }
7340}
7341
7342void AnnotateTokensWorker::HandlePostPonedChildCursor(
7343 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007344 unsigned I = StartTokenIndex;
7345
7346 // The bracket tokens of a Call or Subscript operator are mapped to
7347 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7348 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7349 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007350 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7351 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007352 if (clang_Range_isNull(CXRefNameRange))
7353 break; // All ranges handled.
7354
7355 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7356 while (I < NumTokens) {
7357 const SourceLocation TokenLocation = GetTokenLoc(I);
7358 if (!TokenLocation.isValid())
7359 break;
7360
7361 // Adapt the end range, because LocationCompare() reports
7362 // RangeOverlap even for the not-inclusive end location.
7363 const SourceLocation fixedEnd =
7364 RefNameRange.getEnd().getLocWithOffset(-1);
7365 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7366
7367 const RangeComparisonResult ComparisonResult =
7368 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7369
7370 if (ComparisonResult == RangeOverlap) {
7371 Cursors[I++] = Cursor;
7372 } else if (ComparisonResult == RangeBefore) {
7373 ++I; // Not relevant token, check next one.
7374 } else if (ComparisonResult == RangeAfter) {
7375 break; // All tokens updated for current range, check next.
7376 }
7377 }
7378 }
7379}
7380
Guy Benyei11169dd2012-12-18 14:30:41 +00007381static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7382 CXCursor parent,
7383 CXClientData client_data) {
7384 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7385}
7386
7387static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7388 CXClientData client_data) {
7389 return static_cast<AnnotateTokensWorker*>(client_data)->
7390 postVisitChildren(cursor);
7391}
7392
7393namespace {
7394
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007395/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007396/// and mark tokens that are macro arguments. This info is used by the
7397/// AnnotateTokensWorker.
7398class MarkMacroArgTokensVisitor {
7399 SourceManager &SM;
7400 CXToken *Tokens;
7401 unsigned NumTokens;
7402 unsigned CurIdx;
7403
7404public:
7405 MarkMacroArgTokensVisitor(SourceManager &SM,
7406 CXToken *tokens, unsigned numTokens)
7407 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7408
7409 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7410 if (cursor.kind != CXCursor_MacroExpansion)
7411 return CXChildVisit_Continue;
7412
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007413 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 if (macroRange.getBegin() == macroRange.getEnd())
7415 return CXChildVisit_Continue; // it's not a function macro.
7416
7417 for (; CurIdx < NumTokens; ++CurIdx) {
7418 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7419 macroRange.getBegin()))
7420 break;
7421 }
7422
7423 if (CurIdx == NumTokens)
7424 return CXChildVisit_Break;
7425
7426 for (; CurIdx < NumTokens; ++CurIdx) {
7427 SourceLocation tokLoc = getTokenLoc(CurIdx);
7428 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7429 break;
7430
7431 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7432 }
7433
7434 if (CurIdx == NumTokens)
7435 return CXChildVisit_Break;
7436
7437 return CXChildVisit_Continue;
7438 }
7439
7440private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007441 CXToken &getTok(unsigned Idx) {
7442 assert(Idx < NumTokens);
7443 return Tokens[Idx];
7444 }
7445 const CXToken &getTok(unsigned Idx) const {
7446 assert(Idx < NumTokens);
7447 return Tokens[Idx];
7448 }
7449
Guy Benyei11169dd2012-12-18 14:30:41 +00007450 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007451 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007452 }
7453
7454 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7455 // The third field is reserved and currently not used. Use it here
7456 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007457 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007458 }
7459};
7460
7461} // end anonymous namespace
7462
7463static CXChildVisitResult
7464MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7465 CXClientData client_data) {
7466 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7467 parent);
7468}
7469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007470/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007471/// \returns true if lexing was finished, false otherwise.
7472static bool lexNext(Lexer &Lex, Token &Tok,
7473 unsigned &NextIdx, unsigned NumTokens) {
7474 if (NextIdx >= NumTokens)
7475 return true;
7476
7477 ++NextIdx;
7478 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007479 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007480}
7481
Guy Benyei11169dd2012-12-18 14:30:41 +00007482static void annotatePreprocessorTokens(CXTranslationUnit TU,
7483 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007484 CXCursor *Cursors,
7485 CXToken *Tokens,
7486 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007487 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007488
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007489 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007490 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7491 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007492 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007493 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007494 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007495
7496 if (BeginLocInfo.first != EndLocInfo.first)
7497 return;
7498
7499 StringRef Buffer;
7500 bool Invalid = false;
7501 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7502 if (Buffer.empty() || Invalid)
7503 return;
7504
7505 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7506 CXXUnit->getASTContext().getLangOpts(),
7507 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7508 Buffer.end());
7509 Lex.SetCommentRetentionState(true);
7510
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007511 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007512 // Lex tokens in raw mode until we hit the end of the range, to avoid
7513 // entering #includes or expanding macros.
7514 while (true) {
7515 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007516 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7517 break;
7518 unsigned TokIdx = NextIdx-1;
7519 assert(Tok.getLocation() ==
7520 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007521
7522 reprocess:
7523 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007524 // We have found a preprocessing directive. Annotate the tokens
7525 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007526 //
7527 // FIXME: Some simple tests here could identify macro definitions and
7528 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007529
7530 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007531 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7532 break;
7533
Craig Topper69186e72014-06-08 08:38:04 +00007534 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007535 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007536 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7537 break;
7538
7539 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007540 IdentifierInfo &II =
7541 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007542 SourceLocation MappedTokLoc =
7543 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7544 MI = getMacroInfo(II, MappedTokLoc, TU);
7545 }
7546 }
7547
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007548 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007549 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007550 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7551 finished = true;
7552 break;
7553 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007554 // If we are in a macro definition, check if the token was ever a
7555 // macro name and annotate it if that's the case.
7556 if (MI) {
7557 SourceLocation SaveLoc = Tok.getLocation();
7558 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007559 MacroDefinitionRecord *MacroDef =
7560 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007561 Tok.setLocation(SaveLoc);
7562 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007563 Cursors[NextIdx - 1] =
7564 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007565 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007566 } while (!Tok.isAtStartOfLine());
7567
7568 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7569 assert(TokIdx <= LastIdx);
7570 SourceLocation EndLoc =
7571 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7572 CXCursor Cursor =
7573 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7574
7575 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007576 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007577
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007578 if (finished)
7579 break;
7580 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007581 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007582 }
7583}
7584
7585// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007586static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7587 CXToken *Tokens, unsigned NumTokens,
7588 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007589 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007590 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7591 setThreadBackgroundPriority();
7592
7593 // Determine the region of interest, which contains all of the tokens.
7594 SourceRange RegionOfInterest;
7595 RegionOfInterest.setBegin(
7596 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7597 RegionOfInterest.setEnd(
7598 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7599 Tokens[NumTokens-1])));
7600
Guy Benyei11169dd2012-12-18 14:30:41 +00007601 // Relex the tokens within the source range to look for preprocessing
7602 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007603 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007604
7605 // If begin location points inside a macro argument, set it to the expansion
7606 // location so we can have the full context when annotating semantically.
7607 {
7608 SourceManager &SM = CXXUnit->getSourceManager();
7609 SourceLocation Loc =
7610 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7611 if (Loc.isMacroID())
7612 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7613 }
7614
Guy Benyei11169dd2012-12-18 14:30:41 +00007615 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7616 // Search and mark tokens that are macro argument expansions.
7617 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7618 Tokens, NumTokens);
7619 CursorVisitor MacroArgMarker(TU,
7620 MarkMacroArgTokensVisitorDelegate, &Visitor,
7621 /*VisitPreprocessorLast=*/true,
7622 /*VisitIncludedEntities=*/false,
7623 RegionOfInterest);
7624 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7625 }
7626
7627 // Annotate all of the source locations in the region of interest that map to
7628 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007629 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007630
7631 // FIXME: We use a ridiculous stack size here because the data-recursion
7632 // algorithm uses a large stack frame than the non-data recursive version,
7633 // and AnnotationTokensWorker currently transforms the data-recursion
7634 // algorithm back into a traditional recursion by explicitly calling
7635 // VisitChildren(). We will need to remove this explicit recursive call.
7636 W.AnnotateTokens();
7637
7638 // If we ran into any entities that involve context-sensitive keywords,
7639 // take another pass through the tokens to mark them as such.
7640 if (W.hasContextSensitiveKeywords()) {
7641 for (unsigned I = 0; I != NumTokens; ++I) {
7642 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7643 continue;
7644
7645 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7646 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007647 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007648 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7649 if (Property->getPropertyAttributesAsWritten() != 0 &&
7650 llvm::StringSwitch<bool>(II->getName())
7651 .Case("readonly", true)
7652 .Case("assign", true)
7653 .Case("unsafe_unretained", true)
7654 .Case("readwrite", true)
7655 .Case("retain", true)
7656 .Case("copy", true)
7657 .Case("nonatomic", true)
7658 .Case("atomic", true)
7659 .Case("getter", true)
7660 .Case("setter", true)
7661 .Case("strong", true)
7662 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007663 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007664 .Default(false))
7665 Tokens[I].int_data[0] = CXToken_Keyword;
7666 }
7667 continue;
7668 }
7669
7670 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7671 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7672 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7673 if (llvm::StringSwitch<bool>(II->getName())
7674 .Case("in", true)
7675 .Case("out", true)
7676 .Case("inout", true)
7677 .Case("oneway", true)
7678 .Case("bycopy", true)
7679 .Case("byref", true)
7680 .Default(false))
7681 Tokens[I].int_data[0] = CXToken_Keyword;
7682 continue;
7683 }
7684
7685 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7686 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7687 Tokens[I].int_data[0] = CXToken_Keyword;
7688 continue;
7689 }
7690 }
7691 }
7692}
7693
Guy Benyei11169dd2012-12-18 14:30:41 +00007694void clang_annotateTokens(CXTranslationUnit TU,
7695 CXToken *Tokens, unsigned NumTokens,
7696 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007697 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007698 LOG_BAD_TU(TU);
7699 return;
7700 }
7701 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007702 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007703 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007704 }
7705
7706 LOG_FUNC_SECTION {
7707 *Log << TU << ' ';
7708 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7709 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7710 *Log << clang_getRange(bloc, eloc);
7711 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007712
7713 // Any token we don't specifically annotate will have a NULL cursor.
7714 CXCursor C = clang_getNullCursor();
7715 for (unsigned I = 0; I != NumTokens; ++I)
7716 Cursors[I] = C;
7717
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007718 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007719 if (!CXXUnit)
7720 return;
7721
7722 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007723
7724 auto AnnotateTokensImpl = [=]() {
7725 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7726 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007727 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007728 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007729 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7730 }
7731}
7732
Guy Benyei11169dd2012-12-18 14:30:41 +00007733//===----------------------------------------------------------------------===//
7734// Operations for querying linkage of a cursor.
7735//===----------------------------------------------------------------------===//
7736
Guy Benyei11169dd2012-12-18 14:30:41 +00007737CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7738 if (!clang_isDeclaration(cursor.kind))
7739 return CXLinkage_Invalid;
7740
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007741 const Decl *D = cxcursor::getCursorDecl(cursor);
7742 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007743 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007744 case NoLinkage:
7745 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007746 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007747 case InternalLinkage: return CXLinkage_Internal;
7748 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007749 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007750 case ExternalLinkage: return CXLinkage_External;
7751 };
7752
7753 return CXLinkage_Invalid;
7754}
Guy Benyei11169dd2012-12-18 14:30:41 +00007755
7756//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007757// Operations for querying visibility of a cursor.
7758//===----------------------------------------------------------------------===//
7759
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007760CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7761 if (!clang_isDeclaration(cursor.kind))
7762 return CXVisibility_Invalid;
7763
7764 const Decl *D = cxcursor::getCursorDecl(cursor);
7765 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7766 switch (ND->getVisibility()) {
7767 case HiddenVisibility: return CXVisibility_Hidden;
7768 case ProtectedVisibility: return CXVisibility_Protected;
7769 case DefaultVisibility: return CXVisibility_Default;
7770 };
7771
7772 return CXVisibility_Invalid;
7773}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007774
7775//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007776// Operations for querying language of a cursor.
7777//===----------------------------------------------------------------------===//
7778
7779static CXLanguageKind getDeclLanguage(const Decl *D) {
7780 if (!D)
7781 return CXLanguage_C;
7782
7783 switch (D->getKind()) {
7784 default:
7785 break;
7786 case Decl::ImplicitParam:
7787 case Decl::ObjCAtDefsField:
7788 case Decl::ObjCCategory:
7789 case Decl::ObjCCategoryImpl:
7790 case Decl::ObjCCompatibleAlias:
7791 case Decl::ObjCImplementation:
7792 case Decl::ObjCInterface:
7793 case Decl::ObjCIvar:
7794 case Decl::ObjCMethod:
7795 case Decl::ObjCProperty:
7796 case Decl::ObjCPropertyImpl:
7797 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007798 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007799 return CXLanguage_ObjC;
7800 case Decl::CXXConstructor:
7801 case Decl::CXXConversion:
7802 case Decl::CXXDestructor:
7803 case Decl::CXXMethod:
7804 case Decl::CXXRecord:
7805 case Decl::ClassTemplate:
7806 case Decl::ClassTemplatePartialSpecialization:
7807 case Decl::ClassTemplateSpecialization:
7808 case Decl::Friend:
7809 case Decl::FriendTemplate:
7810 case Decl::FunctionTemplate:
7811 case Decl::LinkageSpec:
7812 case Decl::Namespace:
7813 case Decl::NamespaceAlias:
7814 case Decl::NonTypeTemplateParm:
7815 case Decl::StaticAssert:
7816 case Decl::TemplateTemplateParm:
7817 case Decl::TemplateTypeParm:
7818 case Decl::UnresolvedUsingTypename:
7819 case Decl::UnresolvedUsingValue:
7820 case Decl::Using:
7821 case Decl::UsingDirective:
7822 case Decl::UsingShadow:
7823 return CXLanguage_CPlusPlus;
7824 }
7825
7826 return CXLanguage_C;
7827}
7828
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007829static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7830 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007831 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007832
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007833 switch (D->getAvailability()) {
7834 case AR_Available:
7835 case AR_NotYetIntroduced:
7836 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007837 return getCursorAvailabilityForDecl(
7838 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007839 return CXAvailability_Available;
7840
7841 case AR_Deprecated:
7842 return CXAvailability_Deprecated;
7843
7844 case AR_Unavailable:
7845 return CXAvailability_NotAvailable;
7846 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007847
7848 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007849}
7850
Guy Benyei11169dd2012-12-18 14:30:41 +00007851enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7852 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007853 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7854 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007855
7856 return CXAvailability_Available;
7857}
7858
7859static CXVersion convertVersion(VersionTuple In) {
7860 CXVersion Out = { -1, -1, -1 };
7861 if (In.empty())
7862 return Out;
7863
7864 Out.Major = In.getMajor();
7865
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007866 Optional<unsigned> Minor = In.getMinor();
7867 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007868 Out.Minor = *Minor;
7869 else
7870 return Out;
7871
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007872 Optional<unsigned> Subminor = In.getSubminor();
7873 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007874 Out.Subminor = *Subminor;
7875
7876 return Out;
7877}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007878
Alex Lorenz1345ea22017-06-12 19:06:30 +00007879static void getCursorPlatformAvailabilityForDecl(
7880 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7881 int *always_unavailable, CXString *unavailable_message,
7882 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007883 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007884 for (auto A : D->attrs()) {
7885 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007886 HadAvailAttr = true;
7887 if (always_deprecated)
7888 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007889 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007890 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007891 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007892 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007893 continue;
7894 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007895
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007896 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007897 HadAvailAttr = true;
7898 if (always_unavailable)
7899 *always_unavailable = 1;
7900 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007901 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007902 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7903 }
7904 continue;
7905 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007906
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007907 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007908 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007909 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007910 }
7911 }
7912
7913 if (!HadAvailAttr)
7914 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7915 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007916 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7917 deprecated_message, always_unavailable, unavailable_message,
7918 AvailabilityAttrs);
7919
7920 if (AvailabilityAttrs.empty())
7921 return;
7922
Fangrui Song55fab262018-09-26 22:16:28 +00007923 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007924 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7925 return LHS->getPlatform()->getName() <
7926 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007927 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007928 ASTContext &Ctx = D->getASTContext();
7929 auto It = std::unique(
7930 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7931 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7932 if (LHS->getPlatform() != RHS->getPlatform())
7933 return false;
7934
7935 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7936 LHS->getDeprecated() == RHS->getDeprecated() &&
7937 LHS->getObsoleted() == RHS->getObsoleted() &&
7938 LHS->getMessage() == RHS->getMessage() &&
7939 LHS->getReplacement() == RHS->getReplacement())
7940 return true;
7941
7942 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7943 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7944 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7945 return false;
7946
7947 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7948 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7949
7950 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7951 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7952 if (LHS->getMessage().empty())
7953 LHS->setMessage(Ctx, RHS->getMessage());
7954 if (LHS->getReplacement().empty())
7955 LHS->setReplacement(Ctx, RHS->getReplacement());
7956 }
7957
7958 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7959 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7960 if (LHS->getMessage().empty())
7961 LHS->setMessage(Ctx, RHS->getMessage());
7962 if (LHS->getReplacement().empty())
7963 LHS->setReplacement(Ctx, RHS->getReplacement());
7964 }
7965
7966 return true;
7967 });
7968 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007969}
7970
Alex Lorenz1345ea22017-06-12 19:06:30 +00007971int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 CXString *deprecated_message,
7973 int *always_unavailable,
7974 CXString *unavailable_message,
7975 CXPlatformAvailability *availability,
7976 int availability_size) {
7977 if (always_deprecated)
7978 *always_deprecated = 0;
7979 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007980 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 if (always_unavailable)
7982 *always_unavailable = 0;
7983 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007984 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007985
Guy Benyei11169dd2012-12-18 14:30:41 +00007986 if (!clang_isDeclaration(cursor.kind))
7987 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007988
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007989 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007990 if (!D)
7991 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007992
Alex Lorenz1345ea22017-06-12 19:06:30 +00007993 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7994 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7995 always_unavailable, unavailable_message,
7996 AvailabilityAttrs);
7997 for (const auto &Avail :
7998 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7999 .take_front(availability_size))) {
8000 availability[Avail.index()].Platform =
8001 cxstring::createDup(Avail.value()->getPlatform()->getName());
8002 availability[Avail.index()].Introduced =
8003 convertVersion(Avail.value()->getIntroduced());
8004 availability[Avail.index()].Deprecated =
8005 convertVersion(Avail.value()->getDeprecated());
8006 availability[Avail.index()].Obsoleted =
8007 convertVersion(Avail.value()->getObsoleted());
8008 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
8009 availability[Avail.index()].Message =
8010 cxstring::createDup(Avail.value()->getMessage());
8011 }
8012
8013 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008014}
Alex Lorenz1345ea22017-06-12 19:06:30 +00008015
Guy Benyei11169dd2012-12-18 14:30:41 +00008016void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
8017 clang_disposeString(availability->Platform);
8018 clang_disposeString(availability->Message);
8019}
8020
8021CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
8022 if (clang_isDeclaration(cursor.kind))
8023 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
8024
8025 return CXLanguage_Invalid;
8026}
8027
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00008028CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
8029 const Decl *D = cxcursor::getCursorDecl(cursor);
8030 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8031 switch (VD->getTLSKind()) {
8032 case VarDecl::TLS_None:
8033 return CXTLS_None;
8034 case VarDecl::TLS_Dynamic:
8035 return CXTLS_Dynamic;
8036 case VarDecl::TLS_Static:
8037 return CXTLS_Static;
8038 }
8039 }
8040
8041 return CXTLS_None;
8042}
8043
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008044 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008045 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008046 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008047static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008049 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008050
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008051 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008052 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8053 return FunTmpl;
8054
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008055 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008056 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8057 return ClassTmpl;
8058
8059 return D;
8060}
8061
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008062
8063enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8064 StorageClass sc = SC_None;
8065 const Decl *D = getCursorDecl(C);
8066 if (D) {
8067 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8068 sc = FD->getStorageClass();
8069 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8070 sc = VD->getStorageClass();
8071 } else {
8072 return CX_SC_Invalid;
8073 }
8074 } else {
8075 return CX_SC_Invalid;
8076 }
8077 switch (sc) {
8078 case SC_None:
8079 return CX_SC_None;
8080 case SC_Extern:
8081 return CX_SC_Extern;
8082 case SC_Static:
8083 return CX_SC_Static;
8084 case SC_PrivateExtern:
8085 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008086 case SC_Auto:
8087 return CX_SC_Auto;
8088 case SC_Register:
8089 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008090 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008091 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008092}
8093
Guy Benyei11169dd2012-12-18 14:30:41 +00008094CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8095 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008096 if (const Decl *D = getCursorDecl(cursor)) {
8097 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008098 if (!DC)
8099 return clang_getNullCursor();
8100
8101 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8102 getCursorTU(cursor));
8103 }
8104 }
8105
8106 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008107 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008108 return MakeCXCursor(D, getCursorTU(cursor));
8109 }
8110
8111 return clang_getNullCursor();
8112}
8113
8114CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8115 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008116 if (const Decl *D = getCursorDecl(cursor)) {
8117 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008118 if (!DC)
8119 return clang_getNullCursor();
8120
8121 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8122 getCursorTU(cursor));
8123 }
8124 }
8125
8126 // FIXME: Note that we can't easily compute the lexical context of a
8127 // statement or expression, so we return nothing.
8128 return clang_getNullCursor();
8129}
8130
8131CXFile clang_getIncludedFile(CXCursor cursor) {
8132 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008133 return nullptr;
8134
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008135 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008136 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008137}
8138
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008139unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8140 if (C.kind != CXCursor_ObjCPropertyDecl)
8141 return CXObjCPropertyAttr_noattr;
8142
8143 unsigned Result = CXObjCPropertyAttr_noattr;
8144 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8145 ObjCPropertyDecl::PropertyAttributeKind Attr =
8146 PD->getPropertyAttributesAsWritten();
8147
8148#define SET_CXOBJCPROP_ATTR(A) \
8149 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8150 Result |= CXObjCPropertyAttr_##A
8151 SET_CXOBJCPROP_ATTR(readonly);
8152 SET_CXOBJCPROP_ATTR(getter);
8153 SET_CXOBJCPROP_ATTR(assign);
8154 SET_CXOBJCPROP_ATTR(readwrite);
8155 SET_CXOBJCPROP_ATTR(retain);
8156 SET_CXOBJCPROP_ATTR(copy);
8157 SET_CXOBJCPROP_ATTR(nonatomic);
8158 SET_CXOBJCPROP_ATTR(setter);
8159 SET_CXOBJCPROP_ATTR(atomic);
8160 SET_CXOBJCPROP_ATTR(weak);
8161 SET_CXOBJCPROP_ATTR(strong);
8162 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008163 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008164#undef SET_CXOBJCPROP_ATTR
8165
8166 return Result;
8167}
8168
Michael Wu6e88f532018-08-03 05:38:29 +00008169CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8170 if (C.kind != CXCursor_ObjCPropertyDecl)
8171 return cxstring::createNull();
8172
8173 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8174 Selector sel = PD->getGetterName();
8175 if (sel.isNull())
8176 return cxstring::createNull();
8177
8178 return cxstring::createDup(sel.getAsString());
8179}
8180
8181CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8182 if (C.kind != CXCursor_ObjCPropertyDecl)
8183 return cxstring::createNull();
8184
8185 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8186 Selector sel = PD->getSetterName();
8187 if (sel.isNull())
8188 return cxstring::createNull();
8189
8190 return cxstring::createDup(sel.getAsString());
8191}
8192
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008193unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8194 if (!clang_isDeclaration(C.kind))
8195 return CXObjCDeclQualifier_None;
8196
8197 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8198 const Decl *D = getCursorDecl(C);
8199 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8200 QT = MD->getObjCDeclQualifier();
8201 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8202 QT = PD->getObjCDeclQualifier();
8203 if (QT == Decl::OBJC_TQ_None)
8204 return CXObjCDeclQualifier_None;
8205
8206 unsigned Result = CXObjCDeclQualifier_None;
8207 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8208 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8209 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8210 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8211 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8212 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8213
8214 return Result;
8215}
8216
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008217unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8218 if (!clang_isDeclaration(C.kind))
8219 return 0;
8220
8221 const Decl *D = getCursorDecl(C);
8222 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8223 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8224 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8225 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8226
8227 return 0;
8228}
8229
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008230unsigned clang_Cursor_isVariadic(CXCursor C) {
8231 if (!clang_isDeclaration(C.kind))
8232 return 0;
8233
8234 const Decl *D = getCursorDecl(C);
8235 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8236 return FD->isVariadic();
8237 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8238 return MD->isVariadic();
8239
8240 return 0;
8241}
8242
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008243unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8244 CXString *language, CXString *definedIn,
8245 unsigned *isGenerated) {
8246 if (!clang_isDeclaration(C.kind))
8247 return 0;
8248
8249 const Decl *D = getCursorDecl(C);
8250
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008251 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008252 if (language)
8253 *language = cxstring::createDup(attr->getLanguage());
8254 if (definedIn)
8255 *definedIn = cxstring::createDup(attr->getDefinedIn());
8256 if (isGenerated)
8257 *isGenerated = attr->getGeneratedDeclaration();
8258 return 1;
8259 }
8260 return 0;
8261}
8262
Guy Benyei11169dd2012-12-18 14:30:41 +00008263CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8264 if (!clang_isDeclaration(C.kind))
8265 return clang_getNullRange();
8266
8267 const Decl *D = getCursorDecl(C);
8268 ASTContext &Context = getCursorContext(C);
8269 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8270 if (!RC)
8271 return clang_getNullRange();
8272
8273 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8274}
8275
8276CXString clang_Cursor_getRawCommentText(CXCursor C) {
8277 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008278 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008279
8280 const Decl *D = getCursorDecl(C);
8281 ASTContext &Context = getCursorContext(C);
8282 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8283 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8284 StringRef();
8285
8286 // Don't duplicate the string because RawText points directly into source
8287 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008288 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008289}
8290
8291CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8292 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008293 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008294
8295 const Decl *D = getCursorDecl(C);
8296 const ASTContext &Context = getCursorContext(C);
8297 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8298
8299 if (RC) {
8300 StringRef BriefText = RC->getBriefText(Context);
8301
8302 // Don't duplicate the string because RawComment ensures that this memory
8303 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008304 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008305 }
8306
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008307 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008308}
8309
Guy Benyei11169dd2012-12-18 14:30:41 +00008310CXModule clang_Cursor_getModule(CXCursor C) {
8311 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008312 if (const ImportDecl *ImportD =
8313 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008314 return ImportD->getImportedModule();
8315 }
8316
Craig Topper69186e72014-06-08 08:38:04 +00008317 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008318}
8319
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008320CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8321 if (isNotUsableTU(TU)) {
8322 LOG_BAD_TU(TU);
8323 return nullptr;
8324 }
8325 if (!File)
8326 return nullptr;
8327 FileEntry *FE = static_cast<FileEntry *>(File);
8328
8329 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8330 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8331 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8332
Richard Smithfeb54b62014-10-23 02:01:19 +00008333 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008334}
8335
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008336CXFile clang_Module_getASTFile(CXModule CXMod) {
8337 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008338 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008339 Module *Mod = static_cast<Module*>(CXMod);
8340 return const_cast<FileEntry *>(Mod->getASTFile());
8341}
8342
Guy Benyei11169dd2012-12-18 14:30:41 +00008343CXModule clang_Module_getParent(CXModule CXMod) {
8344 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008345 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008346 Module *Mod = static_cast<Module*>(CXMod);
8347 return Mod->Parent;
8348}
8349
8350CXString clang_Module_getName(CXModule CXMod) {
8351 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008352 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008353 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008354 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008355}
8356
8357CXString clang_Module_getFullName(CXModule CXMod) {
8358 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008359 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008360 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008361 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008362}
8363
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008364int clang_Module_isSystem(CXModule CXMod) {
8365 if (!CXMod)
8366 return 0;
8367 Module *Mod = static_cast<Module*>(CXMod);
8368 return Mod->IsSystem;
8369}
8370
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008371unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8372 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008373 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008374 LOG_BAD_TU(TU);
8375 return 0;
8376 }
8377 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008378 return 0;
8379 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008380 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8381 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8382 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008383}
8384
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008385CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8386 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008387 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008388 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008389 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008390 }
8391 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008392 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008393 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008394 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008395
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008396 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8397 if (Index < TopHeaders.size())
8398 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008399
Craig Topper69186e72014-06-08 08:38:04 +00008400 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008401}
8402
Guy Benyei11169dd2012-12-18 14:30:41 +00008403//===----------------------------------------------------------------------===//
8404// C++ AST instrospection.
8405//===----------------------------------------------------------------------===//
8406
Jonathan Coe29565352016-04-27 12:48:25 +00008407unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8408 if (!clang_isDeclaration(C.kind))
8409 return 0;
8410
8411 const Decl *D = cxcursor::getCursorDecl(C);
8412 const CXXConstructorDecl *Constructor =
8413 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8414 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8415}
8416
8417unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8418 if (!clang_isDeclaration(C.kind))
8419 return 0;
8420
8421 const Decl *D = cxcursor::getCursorDecl(C);
8422 const CXXConstructorDecl *Constructor =
8423 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8424 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8425}
8426
8427unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8428 if (!clang_isDeclaration(C.kind))
8429 return 0;
8430
8431 const Decl *D = cxcursor::getCursorDecl(C);
8432 const CXXConstructorDecl *Constructor =
8433 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8434 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8435}
8436
8437unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8438 if (!clang_isDeclaration(C.kind))
8439 return 0;
8440
8441 const Decl *D = cxcursor::getCursorDecl(C);
8442 const CXXConstructorDecl *Constructor =
8443 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8444 // Passing 'false' excludes constructors marked 'explicit'.
8445 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8446}
8447
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008448unsigned clang_CXXField_isMutable(CXCursor C) {
8449 if (!clang_isDeclaration(C.kind))
8450 return 0;
8451
8452 if (const auto D = cxcursor::getCursorDecl(C))
8453 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8454 return FD->isMutable() ? 1 : 0;
8455 return 0;
8456}
8457
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008458unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8459 if (!clang_isDeclaration(C.kind))
8460 return 0;
8461
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008462 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008463 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008464 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008465 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8466}
8467
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008468unsigned clang_CXXMethod_isConst(CXCursor C) {
8469 if (!clang_isDeclaration(C.kind))
8470 return 0;
8471
8472 const Decl *D = cxcursor::getCursorDecl(C);
8473 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008474 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008475 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008476}
8477
Jonathan Coe29565352016-04-27 12:48:25 +00008478unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8479 if (!clang_isDeclaration(C.kind))
8480 return 0;
8481
8482 const Decl *D = cxcursor::getCursorDecl(C);
8483 const CXXMethodDecl *Method =
8484 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8485 return (Method && Method->isDefaulted()) ? 1 : 0;
8486}
8487
Guy Benyei11169dd2012-12-18 14:30:41 +00008488unsigned clang_CXXMethod_isStatic(CXCursor C) {
8489 if (!clang_isDeclaration(C.kind))
8490 return 0;
8491
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008492 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008493 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008494 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008495 return (Method && Method->isStatic()) ? 1 : 0;
8496}
8497
8498unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8499 if (!clang_isDeclaration(C.kind))
8500 return 0;
8501
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008502 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008503 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008504 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008505 return (Method && Method->isVirtual()) ? 1 : 0;
8506}
Guy Benyei11169dd2012-12-18 14:30:41 +00008507
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008508unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8509 if (!clang_isDeclaration(C.kind))
8510 return 0;
8511
8512 const auto *D = cxcursor::getCursorDecl(C);
8513 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8514 if (RD)
8515 RD = RD->getDefinition();
8516 return (RD && RD->isAbstract()) ? 1 : 0;
8517}
8518
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008519unsigned clang_EnumDecl_isScoped(CXCursor C) {
8520 if (!clang_isDeclaration(C.kind))
8521 return 0;
8522
8523 const Decl *D = cxcursor::getCursorDecl(C);
8524 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8525 return (Enum && Enum->isScoped()) ? 1 : 0;
8526}
8527
Guy Benyei11169dd2012-12-18 14:30:41 +00008528//===----------------------------------------------------------------------===//
8529// Attribute introspection.
8530//===----------------------------------------------------------------------===//
8531
Guy Benyei11169dd2012-12-18 14:30:41 +00008532CXType clang_getIBOutletCollectionType(CXCursor C) {
8533 if (C.kind != CXCursor_IBOutletCollectionAttr)
8534 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8535
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008536 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008537 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8538
8539 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8540}
Guy Benyei11169dd2012-12-18 14:30:41 +00008541
8542//===----------------------------------------------------------------------===//
8543// Inspecting memory usage.
8544//===----------------------------------------------------------------------===//
8545
8546typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8547
8548static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8549 enum CXTUResourceUsageKind k,
8550 unsigned long amount) {
8551 CXTUResourceUsageEntry entry = { k, amount };
8552 entries.push_back(entry);
8553}
8554
Guy Benyei11169dd2012-12-18 14:30:41 +00008555const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8556 const char *str = "";
8557 switch (kind) {
8558 case CXTUResourceUsage_AST:
8559 str = "ASTContext: expressions, declarations, and types";
8560 break;
8561 case CXTUResourceUsage_Identifiers:
8562 str = "ASTContext: identifiers";
8563 break;
8564 case CXTUResourceUsage_Selectors:
8565 str = "ASTContext: selectors";
8566 break;
8567 case CXTUResourceUsage_GlobalCompletionResults:
8568 str = "Code completion: cached global results";
8569 break;
8570 case CXTUResourceUsage_SourceManagerContentCache:
8571 str = "SourceManager: content cache allocator";
8572 break;
8573 case CXTUResourceUsage_AST_SideTables:
8574 str = "ASTContext: side tables";
8575 break;
8576 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8577 str = "SourceManager: malloc'ed memory buffers";
8578 break;
8579 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8580 str = "SourceManager: mmap'ed memory buffers";
8581 break;
8582 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8583 str = "ExternalASTSource: malloc'ed memory buffers";
8584 break;
8585 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8586 str = "ExternalASTSource: mmap'ed memory buffers";
8587 break;
8588 case CXTUResourceUsage_Preprocessor:
8589 str = "Preprocessor: malloc'ed memory";
8590 break;
8591 case CXTUResourceUsage_PreprocessingRecord:
8592 str = "Preprocessor: PreprocessingRecord";
8593 break;
8594 case CXTUResourceUsage_SourceManager_DataStructures:
8595 str = "SourceManager: data structures and tables";
8596 break;
8597 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8598 str = "Preprocessor: header search tables";
8599 break;
8600 }
8601 return str;
8602}
8603
8604CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008605 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008606 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008607 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008608 return usage;
8609 }
8610
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008611 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008612 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008613 ASTContext &astContext = astUnit->getASTContext();
8614
8615 // How much memory is used by AST nodes and types?
8616 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8617 (unsigned long) astContext.getASTAllocatedMemory());
8618
8619 // How much memory is used by identifiers?
8620 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8621 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8622
8623 // How much memory is used for selectors?
8624 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8625 (unsigned long) astContext.Selectors.getTotalMemory());
8626
8627 // How much memory is used by ASTContext's side tables?
8628 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8629 (unsigned long) astContext.getSideTableAllocatedMemory());
8630
8631 // How much memory is used for caching global code completion results?
8632 unsigned long completionBytes = 0;
8633 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008634 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008635 completionBytes = completionAllocator->getTotalMemory();
8636 }
8637 createCXTUResourceUsageEntry(*entries,
8638 CXTUResourceUsage_GlobalCompletionResults,
8639 completionBytes);
8640
8641 // How much memory is being used by SourceManager's content cache?
8642 createCXTUResourceUsageEntry(*entries,
8643 CXTUResourceUsage_SourceManagerContentCache,
8644 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8645
8646 // How much memory is being used by the MemoryBuffer's in SourceManager?
8647 const SourceManager::MemoryBufferSizes &srcBufs =
8648 astUnit->getSourceManager().getMemoryBufferSizes();
8649
8650 createCXTUResourceUsageEntry(*entries,
8651 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8652 (unsigned long) srcBufs.malloc_bytes);
8653 createCXTUResourceUsageEntry(*entries,
8654 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8655 (unsigned long) srcBufs.mmap_bytes);
8656 createCXTUResourceUsageEntry(*entries,
8657 CXTUResourceUsage_SourceManager_DataStructures,
8658 (unsigned long) astContext.getSourceManager()
8659 .getDataStructureSizes());
8660
8661 // How much memory is being used by the ExternalASTSource?
8662 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8663 const ExternalASTSource::MemoryBufferSizes &sizes =
8664 esrc->getMemoryBufferSizes();
8665
8666 createCXTUResourceUsageEntry(*entries,
8667 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8668 (unsigned long) sizes.malloc_bytes);
8669 createCXTUResourceUsageEntry(*entries,
8670 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8671 (unsigned long) sizes.mmap_bytes);
8672 }
8673
8674 // How much memory is being used by the Preprocessor?
8675 Preprocessor &pp = astUnit->getPreprocessor();
8676 createCXTUResourceUsageEntry(*entries,
8677 CXTUResourceUsage_Preprocessor,
8678 pp.getTotalMemory());
8679
8680 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8681 createCXTUResourceUsageEntry(*entries,
8682 CXTUResourceUsage_PreprocessingRecord,
8683 pRec->getTotalMemory());
8684 }
8685
8686 createCXTUResourceUsageEntry(*entries,
8687 CXTUResourceUsage_Preprocessor_HeaderSearch,
8688 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008689
Guy Benyei11169dd2012-12-18 14:30:41 +00008690 CXTUResourceUsage usage = { (void*) entries.get(),
8691 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008692 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008693 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008694 return usage;
8695}
8696
8697void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8698 if (usage.data)
8699 delete (MemUsageEntries*) usage.data;
8700}
8701
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008702CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8703 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008704 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008705 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008706
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008707 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008708 LOG_BAD_TU(TU);
8709 return skipped;
8710 }
8711
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008712 if (!file)
8713 return skipped;
8714
8715 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8716 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8717 if (!ppRec)
8718 return skipped;
8719
8720 ASTContext &Ctx = astUnit->getASTContext();
8721 SourceManager &sm = Ctx.getSourceManager();
8722 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8723 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008724 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008725
8726 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8727 std::vector<SourceRange> wantedRanges;
8728 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8729 i != ei; ++i) {
8730 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8731 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008732 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8733 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008734 }
8735
8736 skipped->count = wantedRanges.size();
8737 skipped->ranges = new CXSourceRange[skipped->count];
8738 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8739 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8740
8741 return skipped;
8742}
8743
Cameron Desrochersd8091282016-08-18 15:43:55 +00008744CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8745 CXSourceRangeList *skipped = new CXSourceRangeList;
8746 skipped->count = 0;
8747 skipped->ranges = nullptr;
8748
8749 if (isNotUsableTU(TU)) {
8750 LOG_BAD_TU(TU);
8751 return skipped;
8752 }
8753
8754 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8755 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8756 if (!ppRec)
8757 return skipped;
8758
8759 ASTContext &Ctx = astUnit->getASTContext();
8760
8761 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8762
8763 skipped->count = SkippedRanges.size();
8764 skipped->ranges = new CXSourceRange[skipped->count];
8765 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8766 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8767
8768 return skipped;
8769}
8770
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008771void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8772 if (ranges) {
8773 delete[] ranges->ranges;
8774 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008775 }
8776}
8777
Guy Benyei11169dd2012-12-18 14:30:41 +00008778void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8779 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8780 for (unsigned I = 0; I != Usage.numEntries; ++I)
8781 fprintf(stderr, " %s: %lu\n",
8782 clang_getTUResourceUsageName(Usage.entries[I].kind),
8783 Usage.entries[I].amount);
8784
8785 clang_disposeCXTUResourceUsage(Usage);
8786}
8787
8788//===----------------------------------------------------------------------===//
8789// Misc. utility functions.
8790//===----------------------------------------------------------------------===//
8791
Richard Smith0a7b2972018-07-03 21:34:13 +00008792/// Default to using our desired 8 MB stack size on "safety" threads.
8793static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008794
8795namespace clang {
8796
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008797bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008798 unsigned Size) {
8799 if (!Size)
8800 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008801 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008802 return CRC.RunSafelyOnThread(Fn, Size);
8803 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008804}
8805
8806unsigned GetSafetyThreadStackSize() {
8807 return SafetyStackThreadSize;
8808}
8809
8810void SetSafetyThreadStackSize(unsigned Value) {
8811 SafetyStackThreadSize = Value;
8812}
8813
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008814}
Guy Benyei11169dd2012-12-18 14:30:41 +00008815
8816void clang::setThreadBackgroundPriority() {
8817 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8818 return;
8819
Nico Weber18cfd9f2019-04-21 19:18:41 +00008820#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008821 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008822#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008823}
8824
8825void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8826 if (!Unit)
8827 return;
8828
8829 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8830 DEnd = Unit->stored_diag_end();
8831 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008832 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008833 CXString Msg = clang_formatDiagnostic(&Diag,
8834 clang_defaultDiagnosticDisplayOptions());
8835 fprintf(stderr, "%s\n", clang_getCString(Msg));
8836 clang_disposeString(Msg);
8837 }
Nico Weber1865df42018-04-27 19:11:14 +00008838#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008839 // On Windows, force a flush, since there may be multiple copies of
8840 // stderr and stdout in the file system, all with different buffers
8841 // but writing to the same device.
8842 fflush(stderr);
8843#endif
8844}
8845
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008846MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8847 SourceLocation MacroDefLoc,
8848 CXTranslationUnit TU){
8849 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008850 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008851 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008852 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008853
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008854 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008855 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008856 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008857 if (MD) {
8858 for (MacroDirective::DefInfo
8859 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8860 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8861 return Def.getMacroInfo();
8862 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008863 }
8864
Craig Topper69186e72014-06-08 08:38:04 +00008865 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008866}
8867
Richard Smith66a81862015-05-04 02:25:31 +00008868const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008869 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008870 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008871 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008872 const IdentifierInfo *II = MacroDef->getName();
8873 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008874 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008875
8876 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8877}
8878
Richard Smith66a81862015-05-04 02:25:31 +00008879MacroDefinitionRecord *
8880cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8881 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008882 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008883 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008884 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008885 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008886
8887 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008888 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008889 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8890 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008891 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008892
8893 // Check that the token is inside the definition and not its argument list.
8894 SourceManager &SM = Unit->getSourceManager();
8895 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008896 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008897 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008898 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008899
8900 Preprocessor &PP = Unit->getPreprocessor();
8901 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8902 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008903 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008904
Alp Toker2d57cea2014-05-17 04:53:25 +00008905 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008906 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008907 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008908
8909 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008910 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008911 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008912
Richard Smith20e883e2015-04-29 23:20:19 +00008913 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008914 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008915 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008916
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008917 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008918}
8919
Richard Smith66a81862015-05-04 02:25:31 +00008920MacroDefinitionRecord *
8921cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8922 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008923 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008924 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008925
8926 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008927 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008928 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008929 Preprocessor &PP = Unit->getPreprocessor();
8930 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008931 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008932 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8933 Token Tok;
8934 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008935 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008936
8937 return checkForMacroInMacroDefinition(MI, Tok, TU);
8938}
8939
Guy Benyei11169dd2012-12-18 14:30:41 +00008940CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008941 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008942}
8943
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008944Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8945 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008946 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008947 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008948 if (Unit->isMainFileAST())
8949 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008950 return *this;
8951 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008952 } else {
8953 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008954 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008955 return *this;
8956}
8957
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008958Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8959 *this << FE->getName();
8960 return *this;
8961}
8962
8963Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8964 CXString cursorName = clang_getCursorDisplayName(cursor);
8965 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8966 clang_disposeString(cursorName);
8967 return *this;
8968}
8969
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008970Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8971 CXFile File;
8972 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008973 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008974 CXString FileName = clang_getFileName(File);
8975 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8976 clang_disposeString(FileName);
8977 return *this;
8978}
8979
8980Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8981 CXSourceLocation BLoc = clang_getRangeStart(range);
8982 CXSourceLocation ELoc = clang_getRangeEnd(range);
8983
8984 CXFile BFile;
8985 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008986 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008987
8988 CXFile EFile;
8989 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008990 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008991
8992 CXString BFileName = clang_getFileName(BFile);
8993 if (BFile == EFile) {
8994 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8995 BLine, BColumn, ELine, EColumn);
8996 } else {
8997 CXString EFileName = clang_getFileName(EFile);
8998 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8999 BLine, BColumn)
9000 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
9001 ELine, EColumn);
9002 clang_disposeString(EFileName);
9003 }
9004 clang_disposeString(BFileName);
9005 return *this;
9006}
9007
9008Logger &cxindex::Logger::operator<<(CXString Str) {
9009 *this << clang_getCString(Str);
9010 return *this;
9011}
9012
9013Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
9014 LogOS << Fmt;
9015 return *this;
9016}
9017
Benjamin Kramer762bc332019-08-07 14:44:40 +00009018static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00009019
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009020cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00009021 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009022
9023 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
9024
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009025 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009026 OS << "[libclang:" << Name << ':';
9027
Alp Toker1a86ad22014-07-06 06:24:00 +00009028#ifdef USE_DARWIN_THREADS
9029 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009030 mach_port_t tid = pthread_mach_thread_np(pthread_self());
9031 OS << tid << ':';
9032#endif
9033
9034 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
9035 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00009036 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009037
9038 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00009039 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009040 OS << "--------------------------------------------------\n";
9041 }
9042}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00009043
9044#ifdef CLANG_TOOL_EXTRA_BUILD
9045// This anchor is used to force the linker to link the clang-tidy plugin.
9046extern volatile int ClangTidyPluginAnchorSource;
9047static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9048 ClangTidyPluginAnchorSource;
9049
9050// This anchor is used to force the linker to link the clang-include-fixer
9051// plugin.
9052extern volatile int ClangIncludeFixerPluginAnchorSource;
9053static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9054 ClangIncludeFixerPluginAnchorSource;
9055#endif