blob: 5dc33bd445486f7388067029331f8e62e5b48402 [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 Bataev04a830f2020-02-10 14:30:39 -05002239void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
2240
Alexey Bataev346265e2015-09-25 10:37:12 +00002241void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2242
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002243void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2244
Alexey Bataevb825de12015-12-07 10:51:44 +00002245void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2246
Kelvin Li1408f912018-09-26 04:28:39 +00002247void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2248 const OMPUnifiedAddressClause *) {}
2249
Patrick Lyster4a370b92018-10-01 13:47:43 +00002250void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2251 const OMPUnifiedSharedMemoryClause *) {}
2252
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002253void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2254 const OMPReverseOffloadClause *) {}
2255
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002256void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2257 const OMPDynamicAllocatorsClause *) {}
2258
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002259void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2260 const OMPAtomicDefaultMemOrderClause *) {}
2261
Michael Wonge710d542015-08-07 16:16:36 +00002262void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2263 Visitor->AddStmt(C->getDevice());
2264}
2265
Kelvin Li099bb8c2015-11-24 20:50:12 +00002266void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002267 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002268 Visitor->AddStmt(C->getNumTeams());
2269}
2270
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002271void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002272 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002273 Visitor->AddStmt(C->getThreadLimit());
2274}
2275
Alexey Bataeva0569352015-12-01 10:17:31 +00002276void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2277 Visitor->AddStmt(C->getPriority());
2278}
2279
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002280void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2281 Visitor->AddStmt(C->getGrainsize());
2282}
2283
Alexey Bataev382967a2015-12-08 12:06:20 +00002284void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2285 Visitor->AddStmt(C->getNumTasks());
2286}
2287
Alexey Bataev28c75412015-12-15 08:19:24 +00002288void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2289 Visitor->AddStmt(C->getHint());
2290}
2291
Alexey Bataev756c1962013-09-24 03:17:45 +00002292template<typename T>
2293void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002294 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002295 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002296 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002297}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002298
Alexey Bataeve04483e2019-03-27 14:14:31 +00002299void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2300 VisitOMPClauseList(C);
2301 Visitor->AddStmt(C->getAllocator());
2302}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002303void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002304 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002305 for (const auto *E : C->private_copies()) {
2306 Visitor->AddStmt(E);
2307 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002308}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002309void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2310 const OMPFirstprivateClause *C) {
2311 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002312 VisitOMPClauseWithPreInit(C);
2313 for (const auto *E : C->private_copies()) {
2314 Visitor->AddStmt(E);
2315 }
2316 for (const auto *E : C->inits()) {
2317 Visitor->AddStmt(E);
2318 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002319}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002320void OMPClauseEnqueue::VisitOMPLastprivateClause(
2321 const OMPLastprivateClause *C) {
2322 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002323 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002324 for (auto *E : C->private_copies()) {
2325 Visitor->AddStmt(E);
2326 }
2327 for (auto *E : C->source_exprs()) {
2328 Visitor->AddStmt(E);
2329 }
2330 for (auto *E : C->destination_exprs()) {
2331 Visitor->AddStmt(E);
2332 }
2333 for (auto *E : C->assignment_ops()) {
2334 Visitor->AddStmt(E);
2335 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002336}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002337void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002338 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002339}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002340void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2341 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002342 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002343 for (auto *E : C->privates()) {
2344 Visitor->AddStmt(E);
2345 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002346 for (auto *E : C->lhs_exprs()) {
2347 Visitor->AddStmt(E);
2348 }
2349 for (auto *E : C->rhs_exprs()) {
2350 Visitor->AddStmt(E);
2351 }
2352 for (auto *E : C->reduction_ops()) {
2353 Visitor->AddStmt(E);
2354 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002355}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002356void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2357 const OMPTaskReductionClause *C) {
2358 VisitOMPClauseList(C);
2359 VisitOMPClauseWithPostUpdate(C);
2360 for (auto *E : C->privates()) {
2361 Visitor->AddStmt(E);
2362 }
2363 for (auto *E : C->lhs_exprs()) {
2364 Visitor->AddStmt(E);
2365 }
2366 for (auto *E : C->rhs_exprs()) {
2367 Visitor->AddStmt(E);
2368 }
2369 for (auto *E : C->reduction_ops()) {
2370 Visitor->AddStmt(E);
2371 }
2372}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002373void OMPClauseEnqueue::VisitOMPInReductionClause(
2374 const OMPInReductionClause *C) {
2375 VisitOMPClauseList(C);
2376 VisitOMPClauseWithPostUpdate(C);
2377 for (auto *E : C->privates()) {
2378 Visitor->AddStmt(E);
2379 }
2380 for (auto *E : C->lhs_exprs()) {
2381 Visitor->AddStmt(E);
2382 }
2383 for (auto *E : C->rhs_exprs()) {
2384 Visitor->AddStmt(E);
2385 }
2386 for (auto *E : C->reduction_ops()) {
2387 Visitor->AddStmt(E);
2388 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002389 for (auto *E : C->taskgroup_descriptors())
2390 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002391}
Alexander Musman8dba6642014-04-22 13:09:42 +00002392void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2393 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002394 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002395 for (const auto *E : C->privates()) {
2396 Visitor->AddStmt(E);
2397 }
Alexander Musman3276a272015-03-21 10:12:56 +00002398 for (const auto *E : C->inits()) {
2399 Visitor->AddStmt(E);
2400 }
2401 for (const auto *E : C->updates()) {
2402 Visitor->AddStmt(E);
2403 }
2404 for (const auto *E : C->finals()) {
2405 Visitor->AddStmt(E);
2406 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002407 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002408 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002409}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002410void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2411 VisitOMPClauseList(C);
2412 Visitor->AddStmt(C->getAlignment());
2413}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002414void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2415 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002416 for (auto *E : C->source_exprs()) {
2417 Visitor->AddStmt(E);
2418 }
2419 for (auto *E : C->destination_exprs()) {
2420 Visitor->AddStmt(E);
2421 }
2422 for (auto *E : C->assignment_ops()) {
2423 Visitor->AddStmt(E);
2424 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002425}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002426void
2427OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2428 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002429 for (auto *E : C->source_exprs()) {
2430 Visitor->AddStmt(E);
2431 }
2432 for (auto *E : C->destination_exprs()) {
2433 Visitor->AddStmt(E);
2434 }
2435 for (auto *E : C->assignment_ops()) {
2436 Visitor->AddStmt(E);
2437 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002438}
Alexey Bataev6125da92014-07-21 11:26:11 +00002439void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2440 VisitOMPClauseList(C);
2441}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002442void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2443 VisitOMPClauseList(C);
2444}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002445void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2446 VisitOMPClauseList(C);
2447}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002448void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2449 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002450 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002451 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002452}
Alexey Bataev3392d762016-02-16 11:18:12 +00002453void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2454 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002455void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2456 VisitOMPClauseList(C);
2457}
Samuel Antaoec172c62016-05-26 17:49:04 +00002458void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2459 VisitOMPClauseList(C);
2460}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002461void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2462 VisitOMPClauseList(C);
2463}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002464void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2465 VisitOMPClauseList(C);
2466}
Alexey Bataevb6e70842019-12-16 15:54:17 -05002467void OMPClauseEnqueue::VisitOMPNontemporalClause(
2468 const OMPNontemporalClause *C) {
2469 VisitOMPClauseList(C);
Alexey Bataev0860db92019-12-19 10:01:10 -05002470 for (const auto *E : C->private_refs())
2471 Visitor->AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05002472}
Alexey Bataevcb8e6912020-01-31 16:09:26 -05002473void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002474}
Alexey Bataev756c1962013-09-24 03:17:45 +00002475
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002476void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2477 unsigned size = WL.size();
2478 OMPClauseEnqueue Visitor(this);
2479 Visitor.Visit(S);
2480 if (size == WL.size())
2481 return;
2482 // Now reverse the entries we just added. This will match the DFS
2483 // ordering performed by the worklist.
2484 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2485 std::reverse(I, E);
2486}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002487void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2489}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002490void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 AddDecl(B->getBlockDecl());
2492}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002493void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 EnqueueChildren(E);
2495 AddTypeLoc(E->getTypeSourceInfo());
2496}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002497void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002498 for (auto &I : llvm::reverse(S->body()))
2499 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002500}
2501void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 AddStmt(S->getSubStmt());
2504 AddDeclarationNameInfo(S);
2505 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2506 AddNestedNameSpecifierLoc(QualifierLoc);
2507}
2508
2509void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002510VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002511 if (E->hasExplicitTemplateArgs())
2512 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 AddDeclarationNameInfo(E);
2514 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2515 AddNestedNameSpecifierLoc(QualifierLoc);
2516 if (!E->isImplicitAccess())
2517 AddStmt(E->getBase());
2518}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002519void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 // Enqueue the initializer , if any.
2521 AddStmt(E->getInitializer());
2522 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002523 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 // Enqueue the allocated type.
2525 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2526 // Enqueue the placement arguments.
2527 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2528 AddStmt(E->getPlacementArg(I-1));
2529}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002530void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2532 AddStmt(CE->getArg(I-1));
2533 AddStmt(CE->getCallee());
2534 AddStmt(CE->getArg(0));
2535}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002536void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2537 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 // Visit the name of the type being destroyed.
2539 AddTypeLoc(E->getDestroyedTypeInfo());
2540 // Visit the scope type that looks disturbingly like the nested-name-specifier
2541 // but isn't.
2542 AddTypeLoc(E->getScopeTypeInfo());
2543 // Visit the nested-name-specifier.
2544 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2545 AddNestedNameSpecifierLoc(QualifierLoc);
2546 // Visit base expression.
2547 AddStmt(E->getBase());
2548}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002549void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2550 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 AddTypeLoc(E->getTypeSourceInfo());
2552}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002553void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2554 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 EnqueueChildren(E);
2556 AddTypeLoc(E->getTypeSourceInfo());
2557}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002558void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 EnqueueChildren(E);
2560 if (E->isTypeOperand())
2561 AddTypeLoc(E->getTypeOperandSourceInfo());
2562}
2563
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002564void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2565 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 EnqueueChildren(E);
2567 AddTypeLoc(E->getTypeSourceInfo());
2568}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002569void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 EnqueueChildren(E);
2571 if (E->isTypeOperand())
2572 AddTypeLoc(E->getTypeOperandSourceInfo());
2573}
2574
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002575void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 EnqueueChildren(S);
2577 AddDecl(S->getExceptionDecl());
2578}
2579
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002580void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002581 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002582 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002583 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002584}
2585
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002586void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002587 if (DR->hasExplicitTemplateArgs())
2588 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 WL.push_back(DeclRefExprParts(DR, Parent));
2590}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002591void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2592 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002593 if (E->hasExplicitTemplateArgs())
2594 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 AddDeclarationNameInfo(E);
2596 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2597}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002598void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 unsigned size = WL.size();
2600 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002601 for (const auto *D : S->decls()) {
2602 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 isFirst = false;
2604 }
2605 if (size == WL.size())
2606 return;
2607 // Now reverse the entries we just added. This will match the DFS
2608 // ordering performed by the worklist.
2609 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2610 std::reverse(I, E);
2611}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002612void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002614 for (const DesignatedInitExpr::Designator &D :
2615 llvm::reverse(E->designators())) {
2616 if (D.isFieldDesignator()) {
2617 if (FieldDecl *Field = D.getField())
2618 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 continue;
2620 }
David Majnemerf7e36092016-06-23 00:15:04 +00002621 if (D.isArrayDesignator()) {
2622 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 continue;
2624 }
David Majnemerf7e36092016-06-23 00:15:04 +00002625 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2626 AddStmt(E->getArrayRangeEnd(D));
2627 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 }
2629}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002630void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 EnqueueChildren(E);
2632 AddTypeLoc(E->getTypeInfoAsWritten());
2633}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002634void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 AddStmt(FS->getBody());
2636 AddStmt(FS->getInc());
2637 AddStmt(FS->getCond());
2638 AddDecl(FS->getConditionVariable());
2639 AddStmt(FS->getInit());
2640}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002641void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2643}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002644void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 AddStmt(If->getElse());
2646 AddStmt(If->getThen());
2647 AddStmt(If->getCond());
2648 AddDecl(If->getConditionVariable());
2649}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002650void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 // We care about the syntactic form of the initializer list, only.
2652 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2653 IE = Syntactic;
2654 EnqueueChildren(IE);
2655}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002656void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 WL.push_back(MemberExprParts(M, Parent));
2658
2659 // If the base of the member access expression is an implicit 'this', don't
2660 // visit it.
2661 // FIXME: If we ever want to show these implicit accesses, this will be
2662 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002663 if (M->isImplicitAccess())
2664 return;
2665
2666 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002667 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002668 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2669 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2670 if (FD->isAnonymousStructOrUnion()) {
2671 AddStmt(SubME->getBase());
2672 return;
2673 }
2674 }
2675 }
2676
2677 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002678}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002679void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 AddTypeLoc(E->getEncodedTypeSourceInfo());
2681}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002682void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 EnqueueChildren(M);
2684 AddTypeLoc(M->getClassReceiverTypeInfo());
2685}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002686void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 // Visit the components of the offsetof expression.
2688 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 const OffsetOfNode &Node = E->getComponent(I-1);
2690 switch (Node.getKind()) {
2691 case OffsetOfNode::Array:
2692 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2693 break;
2694 case OffsetOfNode::Field:
2695 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2696 break;
2697 case OffsetOfNode::Identifier:
2698 case OffsetOfNode::Base:
2699 continue;
2700 }
2701 }
2702 // Visit the type into which we're computing the offset.
2703 AddTypeLoc(E->getTypeSourceInfo());
2704}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002705void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002706 if (E->hasExplicitTemplateArgs())
2707 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 WL.push_back(OverloadExprParts(E, Parent));
2709}
2710void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002711 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 EnqueueChildren(E);
2713 if (E->isArgumentType())
2714 AddTypeLoc(E->getArgumentTypeInfo());
2715}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002716void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 EnqueueChildren(S);
2718}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002719void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 AddStmt(S->getBody());
2721 AddStmt(S->getCond());
2722 AddDecl(S->getConditionVariable());
2723}
2724
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002725void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 AddStmt(W->getBody());
2727 AddStmt(W->getCond());
2728 AddDecl(W->getConditionVariable());
2729}
2730
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002731void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 for (unsigned I = E->getNumArgs(); I > 0; --I)
2733 AddTypeLoc(E->getArg(I-1));
2734}
2735
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002736void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 AddTypeLoc(E->getQueriedTypeSourceInfo());
2738}
2739
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002740void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 EnqueueChildren(E);
2742}
2743
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002744void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 VisitOverloadExpr(U);
2746 if (!U->isImplicitAccess())
2747 AddStmt(U->getBase());
2748}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002749void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002750 AddStmt(E->getSubExpr());
2751 AddTypeLoc(E->getWrittenTypeInfo());
2752}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002753void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 WL.push_back(SizeOfPackExprParts(E, Parent));
2755}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002756void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002757 // If the opaque value has a source expression, just transparently
2758 // visit that. This is useful for (e.g.) pseudo-object expressions.
2759 if (Expr *SourceExpr = E->getSourceExpr())
2760 return Visit(SourceExpr);
2761}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002762void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 AddStmt(E->getBody());
2764 WL.push_back(LambdaExprParts(E, Parent));
2765}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002766void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 // Treat the expression like its syntactic form.
2768 Visit(E->getSyntacticForm());
2769}
2770
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002771void EnqueueVisitor::VisitOMPExecutableDirective(
2772 const OMPExecutableDirective *D) {
2773 EnqueueChildren(D);
2774 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2775 E = D->clauses().end();
2776 I != E; ++I)
2777 EnqueueChildren(*I);
2778}
2779
Alexander Musman3aaab662014-08-19 11:27:13 +00002780void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2781 VisitOMPExecutableDirective(D);
2782}
2783
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002784void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2785 VisitOMPExecutableDirective(D);
2786}
2787
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002788void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002789 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002790}
2791
Alexey Bataevf29276e2014-06-18 04:14:57 +00002792void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002793 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002794}
2795
Alexander Musmanf82886e2014-09-18 05:12:34 +00002796void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2797 VisitOMPLoopDirective(D);
2798}
2799
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002800void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2801 VisitOMPExecutableDirective(D);
2802}
2803
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002804void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2805 VisitOMPExecutableDirective(D);
2806}
2807
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002808void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2809 VisitOMPExecutableDirective(D);
2810}
2811
Alexander Musman80c22892014-07-17 08:54:58 +00002812void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2813 VisitOMPExecutableDirective(D);
2814}
2815
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002816void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2817 VisitOMPExecutableDirective(D);
2818 AddDeclarationNameInfo(D);
2819}
2820
Alexey Bataev4acb8592014-07-07 13:01:15 +00002821void
2822EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002823 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002824}
2825
Alexander Musmane4e893b2014-09-23 09:33:00 +00002826void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2827 const OMPParallelForSimdDirective *D) {
2828 VisitOMPLoopDirective(D);
2829}
2830
cchen47d60942019-12-05 13:43:48 -05002831void EnqueueVisitor::VisitOMPParallelMasterDirective(
2832 const OMPParallelMasterDirective *D) {
2833 VisitOMPExecutableDirective(D);
2834}
2835
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002836void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2837 const OMPParallelSectionsDirective *D) {
2838 VisitOMPExecutableDirective(D);
2839}
2840
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002841void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2842 VisitOMPExecutableDirective(D);
2843}
2844
Alexey Bataev68446b72014-07-18 07:47:19 +00002845void
2846EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2847 VisitOMPExecutableDirective(D);
2848}
2849
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002850void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2851 VisitOMPExecutableDirective(D);
2852}
2853
Alexey Bataev2df347a2014-07-18 10:17:07 +00002854void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2855 VisitOMPExecutableDirective(D);
2856}
2857
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002858void EnqueueVisitor::VisitOMPTaskgroupDirective(
2859 const OMPTaskgroupDirective *D) {
2860 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002861 if (const Expr *E = D->getReductionRef())
2862 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002863}
2864
Alexey Bataev6125da92014-07-21 11:26:11 +00002865void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2866 VisitOMPExecutableDirective(D);
2867}
2868
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002869void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2870 VisitOMPExecutableDirective(D);
2871}
2872
Alexey Bataev0162e452014-07-22 10:10:35 +00002873void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2874 VisitOMPExecutableDirective(D);
2875}
2876
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002877void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2878 VisitOMPExecutableDirective(D);
2879}
2880
Michael Wong65f367f2015-07-21 13:44:28 +00002881void EnqueueVisitor::VisitOMPTargetDataDirective(const
2882 OMPTargetDataDirective *D) {
2883 VisitOMPExecutableDirective(D);
2884}
2885
Samuel Antaodf67fc42016-01-19 19:15:56 +00002886void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2887 const OMPTargetEnterDataDirective *D) {
2888 VisitOMPExecutableDirective(D);
2889}
2890
Samuel Antao72590762016-01-19 20:04:50 +00002891void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2892 const OMPTargetExitDataDirective *D) {
2893 VisitOMPExecutableDirective(D);
2894}
2895
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002896void EnqueueVisitor::VisitOMPTargetParallelDirective(
2897 const OMPTargetParallelDirective *D) {
2898 VisitOMPExecutableDirective(D);
2899}
2900
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002901void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2902 const OMPTargetParallelForDirective *D) {
2903 VisitOMPLoopDirective(D);
2904}
2905
Alexey Bataev13314bf2014-10-09 04:18:56 +00002906void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2907 VisitOMPExecutableDirective(D);
2908}
2909
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002910void EnqueueVisitor::VisitOMPCancellationPointDirective(
2911 const OMPCancellationPointDirective *D) {
2912 VisitOMPExecutableDirective(D);
2913}
2914
Alexey Bataev80909872015-07-02 11:25:17 +00002915void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2916 VisitOMPExecutableDirective(D);
2917}
2918
Alexey Bataev49f6e782015-12-01 04:18:41 +00002919void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2920 VisitOMPLoopDirective(D);
2921}
2922
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002923void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2924 const OMPTaskLoopSimdDirective *D) {
2925 VisitOMPLoopDirective(D);
2926}
2927
Alexey Bataev60e51c42019-10-10 20:13:02 +00002928void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2929 const OMPMasterTaskLoopDirective *D) {
2930 VisitOMPLoopDirective(D);
2931}
2932
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002933void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2934 const OMPMasterTaskLoopSimdDirective *D) {
2935 VisitOMPLoopDirective(D);
2936}
2937
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002938void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2939 const OMPParallelMasterTaskLoopDirective *D) {
2940 VisitOMPLoopDirective(D);
2941}
2942
Alexey Bataev14a388f2019-10-25 10:27:13 -04002943void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
2944 const OMPParallelMasterTaskLoopSimdDirective *D) {
2945 VisitOMPLoopDirective(D);
2946}
2947
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002948void EnqueueVisitor::VisitOMPDistributeDirective(
2949 const OMPDistributeDirective *D) {
2950 VisitOMPLoopDirective(D);
2951}
2952
Carlo Bertolli9925f152016-06-27 14:55:37 +00002953void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2954 const OMPDistributeParallelForDirective *D) {
2955 VisitOMPLoopDirective(D);
2956}
2957
Kelvin Li4a39add2016-07-05 05:00:15 +00002958void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2959 const OMPDistributeParallelForSimdDirective *D) {
2960 VisitOMPLoopDirective(D);
2961}
2962
Kelvin Li787f3fc2016-07-06 04:45:38 +00002963void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2964 const OMPDistributeSimdDirective *D) {
2965 VisitOMPLoopDirective(D);
2966}
2967
Kelvin Lia579b912016-07-14 02:54:56 +00002968void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2969 const OMPTargetParallelForSimdDirective *D) {
2970 VisitOMPLoopDirective(D);
2971}
2972
Kelvin Li986330c2016-07-20 22:57:10 +00002973void EnqueueVisitor::VisitOMPTargetSimdDirective(
2974 const OMPTargetSimdDirective *D) {
2975 VisitOMPLoopDirective(D);
2976}
2977
Kelvin Li02532872016-08-05 14:37:37 +00002978void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2979 const OMPTeamsDistributeDirective *D) {
2980 VisitOMPLoopDirective(D);
2981}
2982
Kelvin Li4e325f72016-10-25 12:50:55 +00002983void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2984 const OMPTeamsDistributeSimdDirective *D) {
2985 VisitOMPLoopDirective(D);
2986}
2987
Kelvin Li579e41c2016-11-30 23:51:03 +00002988void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2989 const OMPTeamsDistributeParallelForSimdDirective *D) {
2990 VisitOMPLoopDirective(D);
2991}
2992
Kelvin Li7ade93f2016-12-09 03:24:30 +00002993void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2994 const OMPTeamsDistributeParallelForDirective *D) {
2995 VisitOMPLoopDirective(D);
2996}
2997
Kelvin Libf594a52016-12-17 05:48:59 +00002998void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2999 const OMPTargetTeamsDirective *D) {
3000 VisitOMPExecutableDirective(D);
3001}
3002
Kelvin Li83c451e2016-12-25 04:52:54 +00003003void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3004 const OMPTargetTeamsDistributeDirective *D) {
3005 VisitOMPLoopDirective(D);
3006}
3007
Kelvin Li80e8f562016-12-29 22:16:30 +00003008void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3009 const OMPTargetTeamsDistributeParallelForDirective *D) {
3010 VisitOMPLoopDirective(D);
3011}
3012
Kelvin Li1851df52017-01-03 05:23:48 +00003013void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3014 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3015 VisitOMPLoopDirective(D);
3016}
3017
Kelvin Lida681182017-01-10 18:08:18 +00003018void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3019 const OMPTargetTeamsDistributeSimdDirective *D) {
3020 VisitOMPLoopDirective(D);
3021}
3022
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003023void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
3025}
3026
3027bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3028 if (RegionOfInterest.isValid()) {
3029 SourceRange Range = getRawCursorExtent(C);
3030 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3031 return false;
3032 }
3033 return true;
3034}
3035
3036bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3037 while (!WL.empty()) {
3038 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003039 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003040
3041 // Set the Parent field, then back to its old value once we're done.
3042 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3043
3044 switch (LI.getKind()) {
3045 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003046 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 if (!D)
3048 continue;
3049
3050 // For now, perform default visitation for Decls.
3051 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3052 cast<DeclVisit>(&LI)->isFirst())))
3053 return true;
3054
3055 continue;
3056 }
3057 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003058 for (const TemplateArgumentLoc &Arg :
3059 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3060 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 return true;
3062 }
3063 continue;
3064 }
3065 case VisitorJob::TypeLocVisitKind: {
3066 // Perform default visitation for TypeLocs.
3067 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3068 return true;
3069 continue;
3070 }
3071 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003072 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003073 if (LabelStmt *stmt = LS->getStmt()) {
3074 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3075 TU))) {
3076 return true;
3077 }
3078 }
3079 continue;
3080 }
3081
3082 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3083 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3084 if (VisitNestedNameSpecifierLoc(V->get()))
3085 return true;
3086 continue;
3087 }
3088
3089 case VisitorJob::DeclarationNameInfoVisitKind: {
3090 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3091 ->get()))
3092 return true;
3093 continue;
3094 }
3095 case VisitorJob::MemberRefVisitKind: {
3096 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3097 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3098 return true;
3099 continue;
3100 }
3101 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003102 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 if (!S)
3104 continue;
3105
3106 // Update the current cursor.
3107 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3108 if (!IsInRegionOfInterest(Cursor))
3109 continue;
3110 switch (Visitor(Cursor, Parent, ClientData)) {
3111 case CXChildVisit_Break: return true;
3112 case CXChildVisit_Continue: break;
3113 case CXChildVisit_Recurse:
3114 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003115 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 EnqueueWorkList(WL, S);
3117 break;
3118 }
3119 continue;
3120 }
3121 case VisitorJob::MemberExprPartsKind: {
3122 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003123 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003124
3125 // Visit the nested-name-specifier
3126 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3127 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3128 return true;
3129
3130 // Visit the declaration name.
3131 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3132 return true;
3133
3134 // Visit the explicitly-specified template arguments, if any.
3135 if (M->hasExplicitTemplateArgs()) {
3136 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3137 *ArgEnd = Arg + M->getNumTemplateArgs();
3138 Arg != ArgEnd; ++Arg) {
3139 if (VisitTemplateArgumentLoc(*Arg))
3140 return true;
3141 }
3142 }
3143 continue;
3144 }
3145 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003146 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 // Visit nested-name-specifier, if present.
3148 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3149 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3150 return true;
3151 // Visit declaration name.
3152 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3153 return true;
3154 continue;
3155 }
3156 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003157 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 // Visit the nested-name-specifier.
3159 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3160 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3161 return true;
3162 // Visit the declaration name.
3163 if (VisitDeclarationNameInfo(O->getNameInfo()))
3164 return true;
3165 // Visit the overloaded declaration reference.
3166 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3167 return true;
3168 continue;
3169 }
3170 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003171 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 NamedDecl *Pack = E->getPack();
3173 if (isa<TemplateTypeParmDecl>(Pack)) {
3174 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3175 E->getPackLoc(), TU)))
3176 return true;
3177
3178 continue;
3179 }
3180
3181 if (isa<TemplateTemplateParmDecl>(Pack)) {
3182 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3183 E->getPackLoc(), TU)))
3184 return true;
3185
3186 continue;
3187 }
3188
3189 // Non-type template parameter packs and function parameter packs are
3190 // treated like DeclRefExpr cursors.
3191 continue;
3192 }
3193
3194 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003195 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003196 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003197 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3198 CEnd = E->explicit_capture_end();
3199 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003200 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003202
Guy Benyei11169dd2012-12-18 14:30:41 +00003203 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3204 C->getLocation(),
3205 TU)))
3206 return true;
3207 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003208 // Visit init captures
3209 for (auto InitExpr : E->capture_inits()) {
3210 if (Visit(InitExpr))
3211 return true;
3212 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003213
Haojian Wuef87c262018-12-18 15:29:12 +00003214 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003215 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003216 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3217 if (E->hasExplicitParameters()) {
3218 // Visit parameters.
3219 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3220 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003222 }
3223 if (E->hasExplicitResultType()) {
3224 // Visit result type.
3225 if (Visit(Proto.getReturnLoc()))
3226 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 }
3228 }
3229 break;
3230 }
3231
3232 case VisitorJob::PostChildrenVisitKind:
3233 if (PostChildrenVisitor(Parent, ClientData))
3234 return true;
3235 break;
3236 }
3237 }
3238 return false;
3239}
3240
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003241bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003242 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003243 if (!WorkListFreeList.empty()) {
3244 WL = WorkListFreeList.back();
3245 WL->clear();
3246 WorkListFreeList.pop_back();
3247 }
3248 else {
3249 WL = new VisitorWorkList();
3250 WorkListCache.push_back(WL);
3251 }
3252 EnqueueWorkList(*WL, S);
3253 bool result = RunVisitorWorkList(*WL);
3254 WorkListFreeList.push_back(WL);
3255 return result;
3256}
3257
3258namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003259typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003260RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3261 const DeclarationNameInfo &NI, SourceRange QLoc,
3262 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3264 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3265 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3266
3267 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3268
3269 RefNamePieces Pieces;
3270
3271 if (WantQualifier && QLoc.isValid())
3272 Pieces.push_back(QLoc);
3273
3274 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3275 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003276
3277 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3278 Pieces.push_back(*TemplateArgsLoc);
3279
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 if (Kind == DeclarationName::CXXOperatorName) {
3281 Pieces.push_back(SourceLocation::getFromRawEncoding(
3282 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3283 Pieces.push_back(SourceLocation::getFromRawEncoding(
3284 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3285 }
3286
3287 if (WantSinglePiece) {
3288 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3289 Pieces.clear();
3290 Pieces.push_back(R);
3291 }
3292
3293 return Pieces;
3294}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003295}
Guy Benyei11169dd2012-12-18 14:30:41 +00003296
3297//===----------------------------------------------------------------------===//
3298// Misc. API hooks.
3299//===----------------------------------------------------------------------===//
3300
Chandler Carruth66660742014-06-27 16:37:27 +00003301namespace {
3302struct RegisterFatalErrorHandler {
3303 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003304 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003305 }
3306};
3307}
3308
3309static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3310
Guy Benyei11169dd2012-12-18 14:30:41 +00003311CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3312 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 // We use crash recovery to make some of our APIs more reliable, implicitly
3314 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003315 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3316 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003317
Chandler Carruth66660742014-06-27 16:37:27 +00003318 // Look through the managed static to trigger construction of the managed
3319 // static which registers our fatal error handler. This ensures it is only
3320 // registered once.
3321 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003322
Adrian Prantlbc068582015-07-08 01:00:30 +00003323 // Initialize targets for clang module support.
3324 llvm::InitializeAllTargets();
3325 llvm::InitializeAllTargetMCs();
3326 llvm::InitializeAllAsmPrinters();
3327 llvm::InitializeAllAsmParsers();
3328
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003329 CIndexer *CIdxr = new CIndexer();
3330
Guy Benyei11169dd2012-12-18 14:30:41 +00003331 if (excludeDeclarationsFromPCH)
3332 CIdxr->setOnlyLocalDecls();
3333 if (displayDiagnostics)
3334 CIdxr->setDisplayDiagnostics();
3335
3336 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3337 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3338 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3339 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3340 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3341 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3342
3343 return CIdxr;
3344}
3345
3346void clang_disposeIndex(CXIndex CIdx) {
3347 if (CIdx)
3348 delete static_cast<CIndexer *>(CIdx);
3349}
3350
3351void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3352 if (CIdx)
3353 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3354}
3355
3356unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3357 if (CIdx)
3358 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3359 return 0;
3360}
3361
Alex Lorenz08615792017-12-04 21:56:36 +00003362void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3363 const char *Path) {
3364 if (CIdx)
3365 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3366}
3367
Guy Benyei11169dd2012-12-18 14:30:41 +00003368void clang_toggleCrashRecovery(unsigned isEnabled) {
3369 if (isEnabled)
3370 llvm::CrashRecoveryContext::Enable();
3371 else
3372 llvm::CrashRecoveryContext::Disable();
3373}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003374
Guy Benyei11169dd2012-12-18 14:30:41 +00003375CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3376 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003377 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003378 enum CXErrorCode Result =
3379 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003380 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003381 assert((TU && Result == CXError_Success) ||
3382 (!TU && Result != CXError_Success));
3383 return TU;
3384}
3385
3386enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3387 const char *ast_filename,
3388 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003389 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003390 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003391
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003392 if (!CIdx || !ast_filename || !out_TU)
3393 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003394
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003395 LOG_FUNC_SECTION {
3396 *Log << ast_filename;
3397 }
3398
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3400 FileSystemOptions FileSystemOpts;
3401
Justin Bognerd512c1e2014-10-15 00:33:06 +00003402 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3403 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003404 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003405 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3406 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003407 FileSystemOpts, /*UseDebugInfo=*/false,
3408 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003409 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003410 /*AllowPCHWithCompilerErrors=*/true,
3411 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003412 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003413 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003414}
3415
3416unsigned clang_defaultEditingTranslationUnitOptions() {
3417 return CXTranslationUnit_PrecompiledPreamble |
3418 CXTranslationUnit_CacheCompletionResults;
3419}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003420
Guy Benyei11169dd2012-12-18 14:30:41 +00003421CXTranslationUnit
3422clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3423 const char *source_filename,
3424 int num_command_line_args,
3425 const char * const *command_line_args,
3426 unsigned num_unsaved_files,
3427 struct CXUnsavedFile *unsaved_files) {
3428 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3429 return clang_parseTranslationUnit(CIdx, source_filename,
3430 command_line_args, num_command_line_args,
3431 unsaved_files, num_unsaved_files,
3432 Options);
3433}
3434
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003435static CXErrorCode
3436clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3437 const char *const *command_line_args,
3438 int num_command_line_args,
3439 ArrayRef<CXUnsavedFile> unsaved_files,
3440 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003441 // Set up the initial return values.
3442 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003443 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003444
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003445 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003446 if (!CIdx || !out_TU)
3447 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003448
Guy Benyei11169dd2012-12-18 14:30:41 +00003449 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3450
3451 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3452 setThreadBackgroundPriority();
3453
3454 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003455 bool CreatePreambleOnFirstParse =
3456 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003457 // FIXME: Add a flag for modules.
3458 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003459 = (options & (CXTranslationUnit_Incomplete |
3460 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003461 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003462 = options & CXTranslationUnit_CacheCompletionResults;
3463 bool IncludeBriefCommentsInCodeCompletion
3464 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003465 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3466 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003467 bool RetainExcludedCB = options &
3468 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003469 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3470 if (options & CXTranslationUnit_SkipFunctionBodies) {
3471 SkipFunctionBodies =
3472 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3473 ? SkipFunctionBodiesScope::Preamble
3474 : SkipFunctionBodiesScope::PreambleAndMainFile;
3475 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003476
3477 // Configure the diagnostics.
3478 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003479 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003480
Manuel Klimek016c0242016-03-01 10:56:19 +00003481 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003482 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003483
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003484 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3485 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3486 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3487
Guy Benyei11169dd2012-12-18 14:30:41 +00003488 // Recover resources if we crash before exiting this function.
3489 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3490 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003491 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003492
Ahmed Charlesb8984322014-03-07 20:03:18 +00003493 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3494 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003495
3496 // Recover resources if we crash before exiting this function.
3497 llvm::CrashRecoveryContextCleanupRegistrar<
3498 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3499
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003500 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003501 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003502 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003503 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003504 }
3505
Ahmed Charlesb8984322014-03-07 20:03:18 +00003506 std::unique_ptr<std::vector<const char *>> Args(
3507 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003508
3509 // Recover resources if we crash before exiting this method.
3510 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3511 ArgsCleanup(Args.get());
3512
3513 // Since the Clang C library is primarily used by batch tools dealing with
3514 // (often very broken) source code, where spell-checking can have a
3515 // significant negative impact on performance (particularly when
3516 // precompiled headers are involved), we disable it by default.
3517 // Only do this if we haven't found a spell-checking-related argument.
3518 bool FoundSpellCheckingArgument = false;
3519 for (int I = 0; I != num_command_line_args; ++I) {
3520 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3521 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3522 FoundSpellCheckingArgument = true;
3523 break;
3524 }
3525 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003526 Args->insert(Args->end(), command_line_args,
3527 command_line_args + num_command_line_args);
3528
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003529 if (!FoundSpellCheckingArgument)
3530 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3531
Guy Benyei11169dd2012-12-18 14:30:41 +00003532 // The 'source_filename' argument is optional. If the caller does not
3533 // specify it then it is assumed that the source file is specified
3534 // in the actual argument list.
3535 // Put the source file after command_line_args otherwise if '-x' flag is
3536 // present it will be unused.
3537 if (source_filename)
3538 Args->push_back(source_filename);
3539
3540 // Do we need the detailed preprocessing record?
3541 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3542 Args->push_back("-Xclang");
3543 Args->push_back("-detailed-preprocessing-record");
3544 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003545
3546 // Suppress any editor placeholder diagnostics.
3547 Args->push_back("-fallow-editor-placeholders");
3548
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003550 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003551 // Unless the user specified that they want the preamble on the first parse
3552 // set it up to be created on the first reparse. This makes the first parse
3553 // faster, trading for a slower (first) reparse.
3554 unsigned PrecompilePreambleAfterNParses =
3555 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003556
Alex Lorenz08615792017-12-04 21:56:36 +00003557 LibclangInvocationReporter InvocationReporter(
3558 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003559 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3560 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003561 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003562 Args->data(), Args->data() + Args->size(),
3563 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003564 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003565 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003566 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3567 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003568 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003569 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003570 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3571 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003572
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003573 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003574 if (!Unit && !ErrUnit)
3575 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003576
Guy Benyei11169dd2012-12-18 14:30:41 +00003577 if (NumErrors != Diags->getClient()->getNumErrors()) {
3578 // Make sure to check that 'Unit' is non-NULL.
3579 if (CXXIdx->getDisplayDiagnostics())
3580 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3581 }
3582
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003583 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3584 return CXError_ASTReadError;
3585
David Blaikieea4395e2017-01-06 19:49:01 +00003586 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003587 if (CXTranslationUnitImpl *TU = *out_TU) {
3588 TU->ParsingOptions = options;
3589 TU->Arguments.reserve(Args->size());
3590 for (const char *Arg : *Args)
3591 TU->Arguments.push_back(Arg);
3592 return CXError_Success;
3593 }
3594 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003595}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003596
3597CXTranslationUnit
3598clang_parseTranslationUnit(CXIndex CIdx,
3599 const char *source_filename,
3600 const char *const *command_line_args,
3601 int num_command_line_args,
3602 struct CXUnsavedFile *unsaved_files,
3603 unsigned num_unsaved_files,
3604 unsigned options) {
3605 CXTranslationUnit TU;
3606 enum CXErrorCode Result = clang_parseTranslationUnit2(
3607 CIdx, source_filename, command_line_args, num_command_line_args,
3608 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003609 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003610 assert((TU && Result == CXError_Success) ||
3611 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003612 return TU;
3613}
3614
3615enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003616 CXIndex CIdx, const char *source_filename,
3617 const char *const *command_line_args, int num_command_line_args,
3618 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3619 unsigned options, CXTranslationUnit *out_TU) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003620 noteBottomOfStack();
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003621 SmallVector<const char *, 4> Args;
3622 Args.push_back("clang");
3623 Args.append(command_line_args, command_line_args + num_command_line_args);
3624 return clang_parseTranslationUnit2FullArgv(
3625 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3626 num_unsaved_files, options, out_TU);
3627}
3628
3629enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3630 CXIndex CIdx, const char *source_filename,
3631 const char *const *command_line_args, int num_command_line_args,
3632 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3633 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003634 LOG_FUNC_SECTION {
3635 *Log << source_filename << ": ";
3636 for (int i = 0; i != num_command_line_args; ++i)
3637 *Log << command_line_args[i] << " ";
3638 }
3639
Alp Toker9d85b182014-07-07 01:23:14 +00003640 if (num_unsaved_files && !unsaved_files)
3641 return CXError_InvalidArguments;
3642
Alp Toker5c532982014-07-07 22:42:03 +00003643 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003644 auto ParseTranslationUnitImpl = [=, &result] {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003645 noteBottomOfStack();
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003646 result = clang_parseTranslationUnit_Impl(
3647 CIdx, source_filename, command_line_args, num_command_line_args,
3648 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3649 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003650
Guy Benyei11169dd2012-12-18 14:30:41 +00003651 llvm::CrashRecoveryContext CRC;
3652
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003653 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3655 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3656 fprintf(stderr, " 'command_line_args' : [");
3657 for (int i = 0; i != num_command_line_args; ++i) {
3658 if (i)
3659 fprintf(stderr, ", ");
3660 fprintf(stderr, "'%s'", command_line_args[i]);
3661 }
3662 fprintf(stderr, "],\n");
3663 fprintf(stderr, " 'unsaved_files' : [");
3664 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3665 if (i)
3666 fprintf(stderr, ", ");
3667 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3668 unsaved_files[i].Length);
3669 }
3670 fprintf(stderr, "],\n");
3671 fprintf(stderr, " 'options' : %d,\n", options);
3672 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003673
3674 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003675 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003676 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003677 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003678 }
Alp Toker5c532982014-07-07 22:42:03 +00003679
3680 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003681}
3682
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003683CXString clang_Type_getObjCEncoding(CXType CT) {
3684 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3685 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3686 std::string encoding;
3687 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3688 encoding);
3689
3690 return cxstring::createDup(encoding);
3691}
3692
3693static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3694 if (C.kind == CXCursor_MacroDefinition) {
3695 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3696 return MDR->getName();
3697 } else if (C.kind == CXCursor_MacroExpansion) {
3698 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3699 return ME.getName();
3700 }
3701 return nullptr;
3702}
3703
3704unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3705 const IdentifierInfo *II = getMacroIdentifier(C);
3706 if (!II) {
3707 return false;
3708 }
3709 ASTUnit *ASTU = getCursorASTUnit(C);
3710 Preprocessor &PP = ASTU->getPreprocessor();
3711 if (const MacroInfo *MI = PP.getMacroInfo(II))
3712 return MI->isFunctionLike();
3713 return false;
3714}
3715
3716unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3717 const IdentifierInfo *II = getMacroIdentifier(C);
3718 if (!II) {
3719 return false;
3720 }
3721 ASTUnit *ASTU = getCursorASTUnit(C);
3722 Preprocessor &PP = ASTU->getPreprocessor();
3723 if (const MacroInfo *MI = PP.getMacroInfo(II))
3724 return MI->isBuiltinMacro();
3725 return false;
3726}
3727
3728unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3729 const Decl *D = getCursorDecl(C);
3730 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3731 if (!FD) {
3732 return false;
3733 }
3734 return FD->isInlined();
3735}
3736
3737static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3738 if (callExpr->getNumArgs() != 1) {
3739 return nullptr;
3740 }
3741
3742 StringLiteral *S = nullptr;
3743 auto *arg = callExpr->getArg(0);
3744 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3745 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3746 auto *subExpr = I->getSubExprAsWritten();
3747
3748 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3749 return nullptr;
3750 }
3751
3752 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3753 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3754 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3755 } else {
3756 return nullptr;
3757 }
3758 return S;
3759}
3760
David Blaikie59272572016-04-13 18:23:33 +00003761struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003762 CXEvalResultKind EvalType;
3763 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003764 unsigned long long unsignedVal;
3765 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003766 double floatVal;
3767 char *stringVal;
3768 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003769 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003770 ~ExprEvalResult() {
3771 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3772 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003773 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003774 }
3775 }
3776};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003777
3778void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003779 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003780}
3781
3782CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3783 if (!E) {
3784 return CXEval_UnExposed;
3785 }
3786 return ((ExprEvalResult *)E)->EvalType;
3787}
3788
3789int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003790 return clang_EvalResult_getAsLongLong(E);
3791}
3792
3793long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003794 if (!E) {
3795 return 0;
3796 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003797 ExprEvalResult *Result = (ExprEvalResult*)E;
3798 if (Result->IsUnsignedInt)
3799 return Result->EvalData.unsignedVal;
3800 return Result->EvalData.intVal;
3801}
3802
3803unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3804 return ((ExprEvalResult *)E)->IsUnsignedInt;
3805}
3806
3807unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3808 if (!E) {
3809 return 0;
3810 }
3811
3812 ExprEvalResult *Result = (ExprEvalResult*)E;
3813 if (Result->IsUnsignedInt)
3814 return Result->EvalData.unsignedVal;
3815 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003816}
3817
3818double clang_EvalResult_getAsDouble(CXEvalResult E) {
3819 if (!E) {
3820 return 0;
3821 }
3822 return ((ExprEvalResult *)E)->EvalData.floatVal;
3823}
3824
3825const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3826 if (!E) {
3827 return nullptr;
3828 }
3829 return ((ExprEvalResult *)E)->EvalData.stringVal;
3830}
3831
3832static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3833 Expr::EvalResult ER;
3834 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003835 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003836 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003837
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003838 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003839 if (expr->isValueDependent())
3840 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003841 if (!expr->EvaluateAsRValue(ER, ctx))
3842 return nullptr;
3843
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003844 QualType rettype;
3845 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003846 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003847 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003848 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003849
David Blaikiebbc00882016-04-13 18:36:19 +00003850 if (ER.Val.isInt()) {
3851 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003852
3853 auto& val = ER.Val.getInt();
3854 if (val.isUnsigned()) {
3855 result->IsUnsignedInt = true;
3856 result->EvalData.unsignedVal = val.getZExtValue();
3857 } else {
3858 result->EvalData.intVal = val.getExtValue();
3859 }
3860
David Blaikiebbc00882016-04-13 18:36:19 +00003861 return result.release();
3862 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003863
David Blaikiebbc00882016-04-13 18:36:19 +00003864 if (ER.Val.isFloat()) {
3865 llvm::SmallVector<char, 100> Buffer;
3866 ER.Val.getFloat().toString(Buffer);
3867 std::string floatStr(Buffer.data(), Buffer.size());
3868 result->EvalType = CXEval_Float;
3869 bool ignored;
3870 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003871 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003872 llvm::APFloat::rmNearestTiesToEven, &ignored);
3873 result->EvalData.floatVal = apFloat.convertToDouble();
3874 return result.release();
3875 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003876
David Blaikiebbc00882016-04-13 18:36:19 +00003877 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3878 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3879 auto *subExpr = I->getSubExprAsWritten();
3880 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3881 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003882 const StringLiteral *StrE = nullptr;
3883 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003884 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003885
3886 if (ObjCExpr) {
3887 StrE = ObjCExpr->getString();
3888 result->EvalType = CXEval_ObjCStrLiteral;
3889 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003890 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003891 result->EvalType = CXEval_StrLiteral;
3892 }
3893
3894 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003895 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003896 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3897 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003898 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003899 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003900 }
3901 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3902 expr->getStmtClass() == Stmt::StringLiteralClass) {
3903 const StringLiteral *StrE = nullptr;
3904 const ObjCStringLiteral *ObjCExpr;
3905 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003906
David Blaikiebbc00882016-04-13 18:36:19 +00003907 if (ObjCExpr) {
3908 StrE = ObjCExpr->getString();
3909 result->EvalType = CXEval_ObjCStrLiteral;
3910 } else {
3911 StrE = cast<StringLiteral>(expr);
3912 result->EvalType = CXEval_StrLiteral;
3913 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003914
David Blaikiebbc00882016-04-13 18:36:19 +00003915 std::string strRef(StrE->getString().str());
3916 result->EvalData.stringVal = new char[strRef.size() + 1];
3917 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3918 result->EvalData.stringVal[strRef.size()] = '\0';
3919 return result.release();
3920 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003921
David Blaikiebbc00882016-04-13 18:36:19 +00003922 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3923 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003924
David Blaikiebbc00882016-04-13 18:36:19 +00003925 rettype = CC->getType();
3926 if (rettype.getAsString() == "CFStringRef" &&
3927 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003928
David Blaikiebbc00882016-04-13 18:36:19 +00003929 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3930 StringLiteral *S = getCFSTR_value(callExpr);
3931 if (S) {
3932 std::string strLiteral(S->getString().str());
3933 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003934
David Blaikiebbc00882016-04-13 18:36:19 +00003935 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3936 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3937 strLiteral.size());
3938 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003939 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003940 }
3941 }
3942
David Blaikiebbc00882016-04-13 18:36:19 +00003943 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3944 callExpr = static_cast<CallExpr *>(expr);
3945 rettype = callExpr->getCallReturnType(ctx);
3946
3947 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3948 return nullptr;
3949
3950 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3951 if (callExpr->getNumArgs() == 1 &&
3952 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3953 return nullptr;
3954 } else if (rettype.getAsString() == "CFStringRef") {
3955
3956 StringLiteral *S = getCFSTR_value(callExpr);
3957 if (S) {
3958 std::string strLiteral(S->getString().str());
3959 result->EvalType = CXEval_CFStr;
3960 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3961 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3962 strLiteral.size());
3963 result->EvalData.stringVal[strLiteral.size()] = '\0';
3964 return result.release();
3965 }
3966 }
3967 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3968 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3969 ValueDecl *V = D->getDecl();
3970 if (V->getKind() == Decl::Function) {
3971 std::string strName = V->getNameAsString();
3972 result->EvalType = CXEval_Other;
3973 result->EvalData.stringVal = new char[strName.size() + 1];
3974 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3975 result->EvalData.stringVal[strName.size()] = '\0';
3976 return result.release();
3977 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003978 }
3979
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003980 return nullptr;
3981}
3982
Alex Lorenz65317e12019-01-08 22:32:51 +00003983static const Expr *evaluateDeclExpr(const Decl *D) {
3984 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003985 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003986 if (auto *Var = dyn_cast<VarDecl>(D))
3987 return Var->getInit();
3988 else if (auto *Field = dyn_cast<FieldDecl>(D))
3989 return Field->getInClassInitializer();
3990 return nullptr;
3991}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003992
Alex Lorenz65317e12019-01-08 22:32:51 +00003993static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3994 assert(CS && "invalid compound statement");
3995 for (auto *bodyIterator : CS->body()) {
3996 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3997 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003998 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003999 return nullptr;
4000}
4001
Alex Lorenz65317e12019-01-08 22:32:51 +00004002CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4003 if (const Expr *E =
4004 clang_getCursorKind(C) == CXCursor_CompoundStmt
4005 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
4006 : evaluateDeclExpr(getCursorDecl(C)))
4007 return const_cast<CXEvalResult>(
4008 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4009 return nullptr;
4010}
4011
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004012unsigned clang_Cursor_hasAttrs(CXCursor C) {
4013 const Decl *D = getCursorDecl(C);
4014 if (!D) {
4015 return 0;
4016 }
4017
4018 if (D->hasAttrs()) {
4019 return 1;
4020 }
4021
4022 return 0;
4023}
Guy Benyei11169dd2012-12-18 14:30:41 +00004024unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4025 return CXSaveTranslationUnit_None;
4026}
4027
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004028static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4029 const char *FileName,
4030 unsigned options) {
4031 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004032 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4033 setThreadBackgroundPriority();
4034
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004035 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4036 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004037}
4038
4039int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4040 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004041 LOG_FUNC_SECTION {
4042 *Log << TU << ' ' << FileName;
4043 }
4044
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004045 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004046 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004048 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004049
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004050 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004051 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4052 if (!CXXUnit->hasSema())
4053 return CXSaveError_InvalidTU;
4054
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004055 CXSaveError result;
4056 auto SaveTranslationUnitImpl = [=, &result]() {
4057 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4058 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004059
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004060 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004061 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004062
4063 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4064 PrintLibclangResourceUsage(TU);
4065
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004066 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 }
4068
4069 // We have an AST that has invalid nodes due to compiler errors.
4070 // Use a crash recovery thread for protection.
4071
4072 llvm::CrashRecoveryContext CRC;
4073
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004074 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4076 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4077 fprintf(stderr, " 'options' : %d,\n", options);
4078 fprintf(stderr, "}\n");
4079
4080 return CXSaveError_Unknown;
4081
4082 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4083 PrintLibclangResourceUsage(TU);
4084 }
4085
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004086 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004087}
4088
4089void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4090 if (CTUnit) {
4091 // If the translation unit has been marked as unsafe to free, just discard
4092 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004093 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4094 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 return;
4096
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004097 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004098 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4100 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004101 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004102 delete CTUnit;
4103 }
4104}
4105
Erik Verbruggen346066b2017-05-30 14:25:54 +00004106unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4107 if (CTUnit) {
4108 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4109
4110 if (Unit && Unit->isUnsafeToFree())
4111 return false;
4112
4113 Unit->ResetForParse();
4114 return true;
4115 }
4116
4117 return false;
4118}
4119
Guy Benyei11169dd2012-12-18 14:30:41 +00004120unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4121 return CXReparse_None;
4122}
4123
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004124static CXErrorCode
4125clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4126 ArrayRef<CXUnsavedFile> unsaved_files,
4127 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004128 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004129 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004130 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004131 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004132 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004133
4134 // Reset the associated diagnostics.
4135 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004136 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004137
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004138 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4140 setThreadBackgroundPriority();
4141
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004142 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004144
4145 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4146 new std::vector<ASTUnit::RemappedFile>());
4147
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 // Recover resources if we crash before exiting this function.
4149 llvm::CrashRecoveryContextCleanupRegistrar<
4150 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004151
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004152 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004153 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004154 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004155 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004156 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004157
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004158 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4159 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004160 return CXError_Success;
4161 if (isASTReadError(CXXUnit))
4162 return CXError_ASTReadError;
4163 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004164}
4165
4166int clang_reparseTranslationUnit(CXTranslationUnit TU,
4167 unsigned num_unsaved_files,
4168 struct CXUnsavedFile *unsaved_files,
4169 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004170 LOG_FUNC_SECTION {
4171 *Log << TU;
4172 }
4173
Alp Toker9d85b182014-07-07 01:23:14 +00004174 if (num_unsaved_files && !unsaved_files)
4175 return CXError_InvalidArguments;
4176
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004177 CXErrorCode result;
4178 auto ReparseTranslationUnitImpl = [=, &result]() {
4179 result = clang_reparseTranslationUnit_Impl(
4180 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4181 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004182
Guy Benyei11169dd2012-12-18 14:30:41 +00004183 llvm::CrashRecoveryContext CRC;
4184
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004185 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004187 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004188 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004189 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4190 PrintLibclangResourceUsage(TU);
4191
Alp Toker5c532982014-07-07 22:42:03 +00004192 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004193}
4194
4195
4196CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004197 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004198 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004199 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004200 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004201
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004202 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004203 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004204}
4205
4206CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004207 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004208 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004209 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004210 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004211
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004212 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4214}
4215
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004216CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4217 if (isNotUsableTU(CTUnit)) {
4218 LOG_BAD_TU(CTUnit);
4219 return nullptr;
4220 }
4221
4222 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4223 impl->TranslationUnit = CTUnit;
4224 return impl;
4225}
4226
4227CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4228 if (!TargetInfo)
4229 return cxstring::createEmpty();
4230
4231 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4232 assert(!isNotUsableTU(CTUnit) &&
4233 "Unexpected unusable translation unit in TargetInfo");
4234
4235 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4236 std::string Triple =
4237 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4238 return cxstring::createDup(Triple);
4239}
4240
4241int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4242 if (!TargetInfo)
4243 return -1;
4244
4245 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4246 assert(!isNotUsableTU(CTUnit) &&
4247 "Unexpected unusable translation unit in TargetInfo");
4248
4249 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4250 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4251}
4252
4253void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4254 if (!TargetInfo)
4255 return;
4256
4257 delete TargetInfo;
4258}
4259
Guy Benyei11169dd2012-12-18 14:30:41 +00004260//===----------------------------------------------------------------------===//
4261// CXFile Operations.
4262//===----------------------------------------------------------------------===//
4263
Guy Benyei11169dd2012-12-18 14:30:41 +00004264CXString clang_getFileName(CXFile SFile) {
4265 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004266 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004267
4268 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004269 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004270}
4271
4272time_t clang_getFileTime(CXFile SFile) {
4273 if (!SFile)
4274 return 0;
4275
4276 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4277 return FEnt->getModificationTime();
4278}
4279
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004280CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004281 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004282 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004283 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004284 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004285
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004286 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004287
4288 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004289 auto File = FMgr.getFile(file_name);
4290 if (!File)
4291 return nullptr;
4292 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004293}
4294
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004295const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4296 size_t *size) {
4297 if (isNotUsableTU(TU)) {
4298 LOG_BAD_TU(TU);
4299 return nullptr;
4300 }
4301
4302 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4303 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4304 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004305 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004306 if (Invalid) {
4307 if (size)
4308 *size = 0;
4309 return nullptr;
4310 }
4311 if (size)
4312 *size = buf->getBufferSize();
4313 return buf->getBufferStart();
4314}
4315
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004316unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4317 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004318 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004319 LOG_BAD_TU(TU);
4320 return 0;
4321 }
4322
4323 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 return 0;
4325
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004326 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 FileEntry *FEnt = static_cast<FileEntry *>(file);
4328 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4329 .isFileMultipleIncludeGuarded(FEnt);
4330}
4331
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004332int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4333 if (!file || !outID)
4334 return 1;
4335
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004336 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004337 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4338 outID->data[0] = ID.getDevice();
4339 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004340 outID->data[2] = FEnt->getModificationTime();
4341 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004342}
4343
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004344int clang_File_isEqual(CXFile file1, CXFile file2) {
4345 if (file1 == file2)
4346 return true;
4347
4348 if (!file1 || !file2)
4349 return false;
4350
4351 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4352 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4353 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4354}
4355
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004356CXString clang_File_tryGetRealPathName(CXFile SFile) {
4357 if (!SFile)
4358 return cxstring::createNull();
4359
4360 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4361 return cxstring::createRef(FEnt->tryGetRealPathName());
4362}
4363
Guy Benyei11169dd2012-12-18 14:30:41 +00004364//===----------------------------------------------------------------------===//
4365// CXCursor Operations.
4366//===----------------------------------------------------------------------===//
4367
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004368static const Decl *getDeclFromExpr(const Stmt *E) {
4369 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 return getDeclFromExpr(CE->getSubExpr());
4371
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004372 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004374 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004376 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004378 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 if (PRE->isExplicitProperty())
4380 return PRE->getExplicitProperty();
4381 // It could be messaging both getter and setter as in:
4382 // ++myobj.myprop;
4383 // in which case prefer to associate the setter since it is less obvious
4384 // from inspecting the source that the setter is going to get called.
4385 if (PRE->isMessagingSetter())
4386 return PRE->getImplicitPropertySetter();
4387 return PRE->getImplicitPropertyGetter();
4388 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004389 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004391 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 if (Expr *Src = OVE->getSourceExpr())
4393 return getDeclFromExpr(Src);
4394
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004395 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004397 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 if (!CE->isElidable())
4399 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004400 if (const CXXInheritedCtorInitExpr *CE =
4401 dyn_cast<CXXInheritedCtorInitExpr>(E))
4402 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004403 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 return OME->getMethodDecl();
4405
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004406 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004408 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4410 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004411 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4413 isa<ParmVarDecl>(SizeOfPack->getPack()))
4414 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004415
4416 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004417}
4418
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004419static SourceLocation getLocationFromExpr(const Expr *E) {
4420 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 return getLocationFromExpr(CE->getSubExpr());
4422
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004423 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004425 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004427 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004429 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004431 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004433 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004435
4436 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004437}
4438
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004439extern "C" {
4440
Guy Benyei11169dd2012-12-18 14:30:41 +00004441unsigned clang_visitChildren(CXCursor parent,
4442 CXCursorVisitor visitor,
4443 CXClientData client_data) {
4444 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4445 /*VisitPreprocessorLast=*/false);
4446 return CursorVis.VisitChildren(parent);
4447}
4448
4449#ifndef __has_feature
4450#define __has_feature(x) 0
4451#endif
4452#if __has_feature(blocks)
4453typedef enum CXChildVisitResult
4454 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4455
4456static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4457 CXClientData client_data) {
4458 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4459 return block(cursor, parent);
4460}
4461#else
4462// If we are compiled with a compiler that doesn't have native blocks support,
4463// define and call the block manually, so the
4464typedef struct _CXChildVisitResult
4465{
4466 void *isa;
4467 int flags;
4468 int reserved;
4469 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4470 CXCursor);
4471} *CXCursorVisitorBlock;
4472
4473static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4474 CXClientData client_data) {
4475 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4476 return block->invoke(block, cursor, parent);
4477}
4478#endif
4479
4480
4481unsigned clang_visitChildrenWithBlock(CXCursor parent,
4482 CXCursorVisitorBlock block) {
4483 return clang_visitChildren(parent, visitWithBlock, block);
4484}
4485
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004486static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004488 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004489
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004490 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004492 if (const ObjCPropertyImplDecl *PropImpl =
4493 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004495 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004496
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004497 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004499 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004500
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004501 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 }
4503
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004504 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004505 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004506
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004507 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4509 // and returns different names. NamedDecl returns the class name and
4510 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004511 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004512
4513 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004514 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004515
4516 SmallString<1024> S;
4517 llvm::raw_svector_ostream os(S);
4518 ND->printName(os);
4519
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004520 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004521}
4522
4523CXString clang_getCursorSpelling(CXCursor C) {
4524 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004525 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004526
4527 if (clang_isReference(C.kind)) {
4528 switch (C.kind) {
4529 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004530 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004531 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 }
4533 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004534 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004535 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 }
4537 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004538 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004540 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 }
4542 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004543 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004544 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 }
4546 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004547 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 assert(Type && "Missing type decl");
4549
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004550 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 getAsString());
4552 }
4553 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004554 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 assert(Template && "Missing template decl");
4556
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004557 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 }
4559
4560 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004561 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004562 assert(NS && "Missing namespace decl");
4563
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004564 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 }
4566
4567 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004568 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 assert(Field && "Missing member decl");
4570
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004571 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 }
4573
4574 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004575 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 assert(Label && "Missing label");
4577
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004578 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 }
4580
4581 case CXCursor_OverloadedDeclRef: {
4582 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004583 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4584 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004585 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004586 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004588 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004589 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 OverloadedTemplateStorage *Ovl
4591 = Storage.get<OverloadedTemplateStorage*>();
4592 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004593 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004594 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 }
4596
4597 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004598 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 assert(Var && "Missing variable decl");
4600
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004601 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 }
4603
4604 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004605 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 }
4607 }
4608
4609 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004610 const Expr *E = getCursorExpr(C);
4611
4612 if (C.kind == CXCursor_ObjCStringLiteral ||
4613 C.kind == CXCursor_StringLiteral) {
4614 const StringLiteral *SLit;
4615 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4616 SLit = OSL->getString();
4617 } else {
4618 SLit = cast<StringLiteral>(E);
4619 }
4620 SmallString<256> Buf;
4621 llvm::raw_svector_ostream OS(Buf);
4622 SLit->outputString(OS);
4623 return cxstring::createDup(OS.str());
4624 }
4625
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004626 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 if (D)
4628 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004629 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 }
4631
4632 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004633 const Stmt *S = getCursorStmt(C);
4634 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004635 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004636
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004637 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 }
4639
4640 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004641 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 ->getNameStart());
4643
4644 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004645 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 ->getNameStart());
4647
4648 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004649 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004650
4651 if (clang_isDeclaration(C.kind))
4652 return getDeclSpelling(getCursorDecl(C));
4653
4654 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004655 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004656 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 }
4658
4659 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004660 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004661 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 }
4663
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004664 if (C.kind == CXCursor_PackedAttr) {
4665 return cxstring::createRef("packed");
4666 }
4667
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004668 if (C.kind == CXCursor_VisibilityAttr) {
4669 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4670 switch (AA->getVisibility()) {
4671 case VisibilityAttr::VisibilityType::Default:
4672 return cxstring::createRef("default");
4673 case VisibilityAttr::VisibilityType::Hidden:
4674 return cxstring::createRef("hidden");
4675 case VisibilityAttr::VisibilityType::Protected:
4676 return cxstring::createRef("protected");
4677 }
4678 llvm_unreachable("unknown visibility type");
4679 }
4680
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004681 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004682}
4683
4684CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4685 unsigned pieceIndex,
4686 unsigned options) {
4687 if (clang_Cursor_isNull(C))
4688 return clang_getNullRange();
4689
4690 ASTContext &Ctx = getCursorContext(C);
4691
4692 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004693 const Stmt *S = getCursorStmt(C);
4694 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004695 if (pieceIndex > 0)
4696 return clang_getNullRange();
4697 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4698 }
4699
4700 return clang_getNullRange();
4701 }
4702
4703 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004704 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4706 if (pieceIndex >= ME->getNumSelectorLocs())
4707 return clang_getNullRange();
4708 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4709 }
4710 }
4711
4712 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4713 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004714 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4716 if (pieceIndex >= MD->getNumSelectorLocs())
4717 return clang_getNullRange();
4718 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4719 }
4720 }
4721
4722 if (C.kind == CXCursor_ObjCCategoryDecl ||
4723 C.kind == CXCursor_ObjCCategoryImplDecl) {
4724 if (pieceIndex > 0)
4725 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004726 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4728 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004729 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4731 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4732 }
4733
4734 if (C.kind == CXCursor_ModuleImportDecl) {
4735 if (pieceIndex > 0)
4736 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004737 if (const ImportDecl *ImportD =
4738 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4740 if (!Locs.empty())
4741 return cxloc::translateSourceRange(Ctx,
4742 SourceRange(Locs.front(), Locs.back()));
4743 }
4744 return clang_getNullRange();
4745 }
4746
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004747 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004748 C.kind == CXCursor_ConversionFunction ||
4749 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004750 if (pieceIndex > 0)
4751 return clang_getNullRange();
4752 if (const FunctionDecl *FD =
4753 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4754 DeclarationNameInfo FunctionName = FD->getNameInfo();
4755 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4756 }
4757 return clang_getNullRange();
4758 }
4759
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 // FIXME: A CXCursor_InclusionDirective should give the location of the
4761 // filename, but we don't keep track of this.
4762
4763 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4764 // but we don't keep track of this.
4765
4766 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4767 // but we don't keep track of this.
4768
4769 // Default handling, give the location of the cursor.
4770
4771 if (pieceIndex > 0)
4772 return clang_getNullRange();
4773
4774 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4775 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4776 return cxloc::translateSourceRange(Ctx, Loc);
4777}
4778
Eli Bendersky44a206f2014-07-31 18:04:56 +00004779CXString clang_Cursor_getMangling(CXCursor C) {
4780 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4781 return cxstring::createEmpty();
4782
Eli Bendersky44a206f2014-07-31 18:04:56 +00004783 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004784 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004785 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4786 return cxstring::createEmpty();
4787
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004788 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004789 ASTNameGenerator ASTNameGen(Ctx);
4790 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004791}
4792
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004793CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4794 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4795 return nullptr;
4796
4797 const Decl *D = getCursorDecl(C);
4798 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4799 return nullptr;
4800
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004801 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004802 ASTNameGenerator ASTNameGen(Ctx);
4803 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004804 return cxstring::createSet(Manglings);
4805}
4806
Dave Lee1a532c92017-09-22 16:58:57 +00004807CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4808 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4809 return nullptr;
4810
4811 const Decl *D = getCursorDecl(C);
4812 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4813 return nullptr;
4814
4815 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004816 ASTNameGenerator ASTNameGen(Ctx);
4817 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004818 return cxstring::createSet(Manglings);
4819}
4820
Jonathan Coe45ef5032018-01-16 10:19:56 +00004821CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4822 if (clang_Cursor_isNull(C))
4823 return 0;
4824 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4825}
4826
4827void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4828 if (Policy)
4829 delete static_cast<PrintingPolicy *>(Policy);
4830}
4831
4832unsigned
4833clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4834 enum CXPrintingPolicyProperty Property) {
4835 if (!Policy)
4836 return 0;
4837
4838 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4839 switch (Property) {
4840 case CXPrintingPolicy_Indentation:
4841 return P->Indentation;
4842 case CXPrintingPolicy_SuppressSpecifiers:
4843 return P->SuppressSpecifiers;
4844 case CXPrintingPolicy_SuppressTagKeyword:
4845 return P->SuppressTagKeyword;
4846 case CXPrintingPolicy_IncludeTagDefinition:
4847 return P->IncludeTagDefinition;
4848 case CXPrintingPolicy_SuppressScope:
4849 return P->SuppressScope;
4850 case CXPrintingPolicy_SuppressUnwrittenScope:
4851 return P->SuppressUnwrittenScope;
4852 case CXPrintingPolicy_SuppressInitializers:
4853 return P->SuppressInitializers;
4854 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4855 return P->ConstantArraySizeAsWritten;
4856 case CXPrintingPolicy_AnonymousTagLocations:
4857 return P->AnonymousTagLocations;
4858 case CXPrintingPolicy_SuppressStrongLifetime:
4859 return P->SuppressStrongLifetime;
4860 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4861 return P->SuppressLifetimeQualifiers;
4862 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4863 return P->SuppressTemplateArgsInCXXConstructors;
4864 case CXPrintingPolicy_Bool:
4865 return P->Bool;
4866 case CXPrintingPolicy_Restrict:
4867 return P->Restrict;
4868 case CXPrintingPolicy_Alignof:
4869 return P->Alignof;
4870 case CXPrintingPolicy_UnderscoreAlignof:
4871 return P->UnderscoreAlignof;
4872 case CXPrintingPolicy_UseVoidForZeroParams:
4873 return P->UseVoidForZeroParams;
4874 case CXPrintingPolicy_TerseOutput:
4875 return P->TerseOutput;
4876 case CXPrintingPolicy_PolishForDeclaration:
4877 return P->PolishForDeclaration;
4878 case CXPrintingPolicy_Half:
4879 return P->Half;
4880 case CXPrintingPolicy_MSWChar:
4881 return P->MSWChar;
4882 case CXPrintingPolicy_IncludeNewlines:
4883 return P->IncludeNewlines;
4884 case CXPrintingPolicy_MSVCFormatting:
4885 return P->MSVCFormatting;
4886 case CXPrintingPolicy_ConstantsAsWritten:
4887 return P->ConstantsAsWritten;
4888 case CXPrintingPolicy_SuppressImplicitBase:
4889 return P->SuppressImplicitBase;
4890 case CXPrintingPolicy_FullyQualifiedName:
4891 return P->FullyQualifiedName;
4892 }
4893
4894 assert(false && "Invalid CXPrintingPolicyProperty");
4895 return 0;
4896}
4897
4898void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4899 enum CXPrintingPolicyProperty Property,
4900 unsigned Value) {
4901 if (!Policy)
4902 return;
4903
4904 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4905 switch (Property) {
4906 case CXPrintingPolicy_Indentation:
4907 P->Indentation = Value;
4908 return;
4909 case CXPrintingPolicy_SuppressSpecifiers:
4910 P->SuppressSpecifiers = Value;
4911 return;
4912 case CXPrintingPolicy_SuppressTagKeyword:
4913 P->SuppressTagKeyword = Value;
4914 return;
4915 case CXPrintingPolicy_IncludeTagDefinition:
4916 P->IncludeTagDefinition = Value;
4917 return;
4918 case CXPrintingPolicy_SuppressScope:
4919 P->SuppressScope = Value;
4920 return;
4921 case CXPrintingPolicy_SuppressUnwrittenScope:
4922 P->SuppressUnwrittenScope = Value;
4923 return;
4924 case CXPrintingPolicy_SuppressInitializers:
4925 P->SuppressInitializers = Value;
4926 return;
4927 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4928 P->ConstantArraySizeAsWritten = Value;
4929 return;
4930 case CXPrintingPolicy_AnonymousTagLocations:
4931 P->AnonymousTagLocations = Value;
4932 return;
4933 case CXPrintingPolicy_SuppressStrongLifetime:
4934 P->SuppressStrongLifetime = Value;
4935 return;
4936 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4937 P->SuppressLifetimeQualifiers = Value;
4938 return;
4939 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4940 P->SuppressTemplateArgsInCXXConstructors = Value;
4941 return;
4942 case CXPrintingPolicy_Bool:
4943 P->Bool = Value;
4944 return;
4945 case CXPrintingPolicy_Restrict:
4946 P->Restrict = Value;
4947 return;
4948 case CXPrintingPolicy_Alignof:
4949 P->Alignof = Value;
4950 return;
4951 case CXPrintingPolicy_UnderscoreAlignof:
4952 P->UnderscoreAlignof = Value;
4953 return;
4954 case CXPrintingPolicy_UseVoidForZeroParams:
4955 P->UseVoidForZeroParams = Value;
4956 return;
4957 case CXPrintingPolicy_TerseOutput:
4958 P->TerseOutput = Value;
4959 return;
4960 case CXPrintingPolicy_PolishForDeclaration:
4961 P->PolishForDeclaration = Value;
4962 return;
4963 case CXPrintingPolicy_Half:
4964 P->Half = Value;
4965 return;
4966 case CXPrintingPolicy_MSWChar:
4967 P->MSWChar = Value;
4968 return;
4969 case CXPrintingPolicy_IncludeNewlines:
4970 P->IncludeNewlines = Value;
4971 return;
4972 case CXPrintingPolicy_MSVCFormatting:
4973 P->MSVCFormatting = Value;
4974 return;
4975 case CXPrintingPolicy_ConstantsAsWritten:
4976 P->ConstantsAsWritten = Value;
4977 return;
4978 case CXPrintingPolicy_SuppressImplicitBase:
4979 P->SuppressImplicitBase = Value;
4980 return;
4981 case CXPrintingPolicy_FullyQualifiedName:
4982 P->FullyQualifiedName = Value;
4983 return;
4984 }
4985
4986 assert(false && "Invalid CXPrintingPolicyProperty");
4987}
4988
4989CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4990 if (clang_Cursor_isNull(C))
4991 return cxstring::createEmpty();
4992
4993 if (clang_isDeclaration(C.kind)) {
4994 const Decl *D = getCursorDecl(C);
4995 if (!D)
4996 return cxstring::createEmpty();
4997
4998 SmallString<128> Str;
4999 llvm::raw_svector_ostream OS(Str);
5000 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
5001 D->print(OS, UserPolicy ? *UserPolicy
5002 : getCursorContext(C).getPrintingPolicy());
5003
5004 return cxstring::createDup(OS.str());
5005 }
5006
5007 return cxstring::createEmpty();
5008}
5009
Guy Benyei11169dd2012-12-18 14:30:41 +00005010CXString clang_getCursorDisplayName(CXCursor C) {
5011 if (!clang_isDeclaration(C.kind))
5012 return clang_getCursorSpelling(C);
5013
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005014 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005016 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005017
5018 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005019 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 D = FunTmpl->getTemplatedDecl();
5021
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005022 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 SmallString<64> Str;
5024 llvm::raw_svector_ostream OS(Str);
5025 OS << *Function;
5026 if (Function->getPrimaryTemplate())
5027 OS << "<>";
5028 OS << "(";
5029 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5030 if (I)
5031 OS << ", ";
5032 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5033 }
5034
5035 if (Function->isVariadic()) {
5036 if (Function->getNumParams())
5037 OS << ", ";
5038 OS << "...";
5039 }
5040 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005041 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 }
5043
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005044 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 SmallString<64> Str;
5046 llvm::raw_svector_ostream OS(Str);
5047 OS << *ClassTemplate;
5048 OS << "<";
5049 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5050 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5051 if (I)
5052 OS << ", ";
5053
5054 NamedDecl *Param = Params->getParam(I);
5055 if (Param->getIdentifier()) {
5056 OS << Param->getIdentifier()->getName();
5057 continue;
5058 }
5059
5060 // There is no parameter name, which makes this tricky. Try to come up
5061 // with something useful that isn't too long.
5062 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Saar Razff1e0fc2020-01-15 02:48:42 +02005063 if (const auto *TC = TTP->getTypeConstraint()) {
5064 TC->getConceptNameInfo().printName(OS, Policy);
5065 if (TC->hasExplicitTemplateArgs())
5066 OS << "<...>";
5067 } else
5068 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 else if (NonTypeTemplateParmDecl *NTTP
5070 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5071 OS << NTTP->getType().getAsString(Policy);
5072 else
5073 OS << "template<...> class";
5074 }
5075
5076 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005077 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 }
5079
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005080 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5082 // If the type was explicitly written, use that.
5083 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005084 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005085
Benjamin Kramer9170e912013-02-22 15:46:01 +00005086 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 llvm::raw_svector_ostream OS(Str);
5088 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005089 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5090 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005091 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 }
5093
5094 return clang_getCursorSpelling(C);
5095}
5096
5097CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5098 switch (Kind) {
5099 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005163 case CXCursor_FixedPointLiteral:
5164 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005179 case CXCursor_OMPArraySectionExpr:
5180 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005231 case CXCursor_ObjCAvailabilityCheckExpr:
5232 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005233 case CXCursor_ObjCSelfExpr:
5234 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005261 case CXCursor_BuiltinBitCastExpr:
5262 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005268 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005270 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005272 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005273 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005274 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005275 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005276 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005278 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005280 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005282 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005284 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005286 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005288 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005290 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005292 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005294 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005295 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005296 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005298 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005300 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005301 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005302 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005303 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005304 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005305 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005306 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005307 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005308 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005309 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005310 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005312 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005313 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005314 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005316 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005317 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005318 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005319 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005320 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005321 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005322 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005323 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005324 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005325 case CXCursor_SEHLeaveStmt:
5326 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005327 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005328 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005329 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005330 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005332 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005334 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005336 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005338 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005340 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005342 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005344 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005346 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005348 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005350 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005354 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005355 case CXCursor_PackedAttr:
5356 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005357 case CXCursor_PureAttr:
5358 return cxstring::createRef("attribute(pure)");
5359 case CXCursor_ConstAttr:
5360 return cxstring::createRef("attribute(const)");
5361 case CXCursor_NoDuplicateAttr:
5362 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005363 case CXCursor_CUDAConstantAttr:
5364 return cxstring::createRef("attribute(constant)");
5365 case CXCursor_CUDADeviceAttr:
5366 return cxstring::createRef("attribute(device)");
5367 case CXCursor_CUDAGlobalAttr:
5368 return cxstring::createRef("attribute(global)");
5369 case CXCursor_CUDAHostAttr:
5370 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005371 case CXCursor_CUDASharedAttr:
5372 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005373 case CXCursor_VisibilityAttr:
5374 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005375 case CXCursor_DLLExport:
5376 return cxstring::createRef("attribute(dllexport)");
5377 case CXCursor_DLLImport:
5378 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005379 case CXCursor_NSReturnsRetained:
5380 return cxstring::createRef("attribute(ns_returns_retained)");
5381 case CXCursor_NSReturnsNotRetained:
5382 return cxstring::createRef("attribute(ns_returns_not_retained)");
5383 case CXCursor_NSReturnsAutoreleased:
5384 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5385 case CXCursor_NSConsumesSelf:
5386 return cxstring::createRef("attribute(ns_consumes_self)");
5387 case CXCursor_NSConsumed:
5388 return cxstring::createRef("attribute(ns_consumed)");
5389 case CXCursor_ObjCException:
5390 return cxstring::createRef("attribute(objc_exception)");
5391 case CXCursor_ObjCNSObject:
5392 return cxstring::createRef("attribute(NSObject)");
5393 case CXCursor_ObjCIndependentClass:
5394 return cxstring::createRef("attribute(objc_independent_class)");
5395 case CXCursor_ObjCPreciseLifetime:
5396 return cxstring::createRef("attribute(objc_precise_lifetime)");
5397 case CXCursor_ObjCReturnsInnerPointer:
5398 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5399 case CXCursor_ObjCRequiresSuper:
5400 return cxstring::createRef("attribute(objc_requires_super)");
5401 case CXCursor_ObjCRootClass:
5402 return cxstring::createRef("attribute(objc_root_class)");
5403 case CXCursor_ObjCSubclassingRestricted:
5404 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5405 case CXCursor_ObjCExplicitProtocolImpl:
5406 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5407 case CXCursor_ObjCDesignatedInitializer:
5408 return cxstring::createRef("attribute(objc_designated_initializer)");
5409 case CXCursor_ObjCRuntimeVisible:
5410 return cxstring::createRef("attribute(objc_runtime_visible)");
5411 case CXCursor_ObjCBoxable:
5412 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005413 case CXCursor_FlagEnum:
5414 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005415 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005416 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005417 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005418 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005419 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005420 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005421 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005422 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005424 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005425 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005426 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005427 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005428 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005429 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005430 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005431 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005432 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005433 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005434 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005435 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005436 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005437 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005438 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005439 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005440 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005441 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005442 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005443 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005444 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005445 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005446 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005447 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005448 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005449 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005450 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005451 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005452 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005453 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005454 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005455 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005456 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005457 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005458 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005459 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005460 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005461 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005462 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005463 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005464 return cxstring::createRef("OMPParallelDirective");
5465 case CXCursor_OMPSimdDirective:
5466 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005467 case CXCursor_OMPForDirective:
5468 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005469 case CXCursor_OMPForSimdDirective:
5470 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005471 case CXCursor_OMPSectionsDirective:
5472 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005473 case CXCursor_OMPSectionDirective:
5474 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005475 case CXCursor_OMPSingleDirective:
5476 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005477 case CXCursor_OMPMasterDirective:
5478 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005479 case CXCursor_OMPCriticalDirective:
5480 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005481 case CXCursor_OMPParallelForDirective:
5482 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005483 case CXCursor_OMPParallelForSimdDirective:
5484 return cxstring::createRef("OMPParallelForSimdDirective");
cchen47d60942019-12-05 13:43:48 -05005485 case CXCursor_OMPParallelMasterDirective:
5486 return cxstring::createRef("OMPParallelMasterDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005487 case CXCursor_OMPParallelSectionsDirective:
5488 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005489 case CXCursor_OMPTaskDirective:
5490 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005491 case CXCursor_OMPTaskyieldDirective:
5492 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005493 case CXCursor_OMPBarrierDirective:
5494 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005495 case CXCursor_OMPTaskwaitDirective:
5496 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005497 case CXCursor_OMPTaskgroupDirective:
5498 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005499 case CXCursor_OMPFlushDirective:
5500 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005501 case CXCursor_OMPOrderedDirective:
5502 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005503 case CXCursor_OMPAtomicDirective:
5504 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005505 case CXCursor_OMPTargetDirective:
5506 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005507 case CXCursor_OMPTargetDataDirective:
5508 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005509 case CXCursor_OMPTargetEnterDataDirective:
5510 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005511 case CXCursor_OMPTargetExitDataDirective:
5512 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005513 case CXCursor_OMPTargetParallelDirective:
5514 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005515 case CXCursor_OMPTargetParallelForDirective:
5516 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005517 case CXCursor_OMPTargetUpdateDirective:
5518 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005519 case CXCursor_OMPTeamsDirective:
5520 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005521 case CXCursor_OMPCancellationPointDirective:
5522 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005523 case CXCursor_OMPCancelDirective:
5524 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005525 case CXCursor_OMPTaskLoopDirective:
5526 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005527 case CXCursor_OMPTaskLoopSimdDirective:
5528 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005529 case CXCursor_OMPMasterTaskLoopDirective:
5530 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005531 case CXCursor_OMPMasterTaskLoopSimdDirective:
5532 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005533 case CXCursor_OMPParallelMasterTaskLoopDirective:
5534 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Alexey Bataev14a388f2019-10-25 10:27:13 -04005535 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5536 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005537 case CXCursor_OMPDistributeDirective:
5538 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005539 case CXCursor_OMPDistributeParallelForDirective:
5540 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005541 case CXCursor_OMPDistributeParallelForSimdDirective:
5542 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005543 case CXCursor_OMPDistributeSimdDirective:
5544 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005545 case CXCursor_OMPTargetParallelForSimdDirective:
5546 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005547 case CXCursor_OMPTargetSimdDirective:
5548 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005549 case CXCursor_OMPTeamsDistributeDirective:
5550 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005551 case CXCursor_OMPTeamsDistributeSimdDirective:
5552 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005553 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5554 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005555 case CXCursor_OMPTeamsDistributeParallelForDirective:
5556 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005557 case CXCursor_OMPTargetTeamsDirective:
5558 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005559 case CXCursor_OMPTargetTeamsDistributeDirective:
5560 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005561 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5562 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005563 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5564 return cxstring::createRef(
5565 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005566 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5567 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005568 case CXCursor_OverloadCandidate:
5569 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005570 case CXCursor_TypeAliasTemplateDecl:
5571 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005572 case CXCursor_StaticAssert:
5573 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005574 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005575 return cxstring::createRef("FriendDecl");
5576 case CXCursor_ConvergentAttr:
5577 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005578 case CXCursor_WarnUnusedAttr:
5579 return cxstring::createRef("attribute(warn_unused)");
5580 case CXCursor_WarnUnusedResultAttr:
5581 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005582 case CXCursor_AlignedAttr:
5583 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005584 }
5585
5586 llvm_unreachable("Unhandled CXCursorKind");
5587}
5588
5589struct GetCursorData {
5590 SourceLocation TokenBeginLoc;
5591 bool PointsAtMacroArgExpansion;
5592 bool VisitedObjCPropertyImplDecl;
5593 SourceLocation VisitedDeclaratorDeclStartLoc;
5594 CXCursor &BestCursor;
5595
5596 GetCursorData(SourceManager &SM,
5597 SourceLocation tokenBegin, CXCursor &outputCursor)
5598 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5599 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5600 VisitedObjCPropertyImplDecl = false;
5601 }
5602};
5603
5604static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5605 CXCursor parent,
5606 CXClientData client_data) {
5607 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5608 CXCursor *BestCursor = &Data->BestCursor;
5609
5610 // If we point inside a macro argument we should provide info of what the
5611 // token is so use the actual cursor, don't replace it with a macro expansion
5612 // cursor.
5613 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5614 return CXChildVisit_Recurse;
5615
5616 if (clang_isDeclaration(cursor.kind)) {
5617 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005618 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005619 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5620 if (MD->isImplicit())
5621 return CXChildVisit_Break;
5622
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005623 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005624 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5625 // Check that when we have multiple @class references in the same line,
5626 // that later ones do not override the previous ones.
5627 // If we have:
5628 // @class Foo, Bar;
5629 // source ranges for both start at '@', so 'Bar' will end up overriding
5630 // 'Foo' even though the cursor location was at 'Foo'.
5631 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5632 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005633 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005634 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5635 if (PrevID != ID &&
5636 !PrevID->isThisDeclarationADefinition() &&
5637 !ID->isThisDeclarationADefinition())
5638 return CXChildVisit_Break;
5639 }
5640
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005641 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005642 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5643 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5644 // Check that when we have multiple declarators in the same line,
5645 // that later ones do not override the previous ones.
5646 // If we have:
5647 // int Foo, Bar;
5648 // source ranges for both start at 'int', so 'Bar' will end up overriding
5649 // 'Foo' even though the cursor location was at 'Foo'.
5650 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5651 return CXChildVisit_Break;
5652 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5653
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005654 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5656 (void)PropImp;
5657 // Check that when we have multiple @synthesize in the same line,
5658 // that later ones do not override the previous ones.
5659 // If we have:
5660 // @synthesize Foo, Bar;
5661 // source ranges for both start at '@', so 'Bar' will end up overriding
5662 // 'Foo' even though the cursor location was at 'Foo'.
5663 if (Data->VisitedObjCPropertyImplDecl)
5664 return CXChildVisit_Break;
5665 Data->VisitedObjCPropertyImplDecl = true;
5666 }
5667 }
5668
5669 if (clang_isExpression(cursor.kind) &&
5670 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005671 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005672 // Avoid having the cursor of an expression replace the declaration cursor
5673 // when the expression source range overlaps the declaration range.
5674 // This can happen for C++ constructor expressions whose range generally
5675 // include the variable declaration, e.g.:
5676 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5677 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5678 D->getLocation() == Data->TokenBeginLoc)
5679 return CXChildVisit_Break;
5680 }
5681 }
5682
5683 // If our current best cursor is the construction of a temporary object,
5684 // don't replace that cursor with a type reference, because we want
5685 // clang_getCursor() to point at the constructor.
5686 if (clang_isExpression(BestCursor->kind) &&
5687 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5688 cursor.kind == CXCursor_TypeRef) {
5689 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5690 // as having the actual point on the type reference.
5691 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5692 return CXChildVisit_Recurse;
5693 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005694
5695 // If we already have an Objective-C superclass reference, don't
5696 // update it further.
5697 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5698 return CXChildVisit_Break;
5699
Guy Benyei11169dd2012-12-18 14:30:41 +00005700 *BestCursor = cursor;
5701 return CXChildVisit_Recurse;
5702}
5703
5704CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005705 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005706 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005707 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005708 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005709
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005710 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005711 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5712
5713 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5714 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5715
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005716 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005717 CXFile SearchFile;
5718 unsigned SearchLine, SearchColumn;
5719 CXFile ResultFile;
5720 unsigned ResultLine, ResultColumn;
5721 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5722 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5723 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005724
5725 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5726 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005727 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005728 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005729 SearchFileName = clang_getFileName(SearchFile);
5730 ResultFileName = clang_getFileName(ResultFile);
5731 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5732 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005733 *Log << llvm::format("(%s:%d:%d) = %s",
5734 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5735 clang_getCString(KindSpelling))
5736 << llvm::format("(%s:%d:%d):%s%s",
5737 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5738 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005739 clang_disposeString(SearchFileName);
5740 clang_disposeString(ResultFileName);
5741 clang_disposeString(KindSpelling);
5742 clang_disposeString(USR);
5743
5744 CXCursor Definition = clang_getCursorDefinition(Result);
5745 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5746 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5747 CXString DefinitionKindSpelling
5748 = clang_getCursorKindSpelling(Definition.kind);
5749 CXFile DefinitionFile;
5750 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005751 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005752 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005753 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005754 *Log << llvm::format(" -> %s(%s:%d:%d)",
5755 clang_getCString(DefinitionKindSpelling),
5756 clang_getCString(DefinitionFileName),
5757 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005758 clang_disposeString(DefinitionFileName);
5759 clang_disposeString(DefinitionKindSpelling);
5760 }
5761 }
5762
5763 return Result;
5764}
5765
5766CXCursor clang_getNullCursor(void) {
5767 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5768}
5769
5770unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005771 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5772 // can't set consistently. For example, when visiting a DeclStmt we will set
5773 // it but we don't set it on the result of clang_getCursorDefinition for
5774 // a reference of the same declaration.
5775 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5776 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5777 // to provide that kind of info.
5778 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005779 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005780 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005781 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005782
Guy Benyei11169dd2012-12-18 14:30:41 +00005783 return X == Y;
5784}
5785
5786unsigned clang_hashCursor(CXCursor C) {
5787 unsigned Index = 0;
5788 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5789 Index = 1;
5790
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005791 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 std::make_pair(C.kind, C.data[Index]));
5793}
5794
5795unsigned clang_isInvalid(enum CXCursorKind K) {
5796 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5797}
5798
5799unsigned clang_isDeclaration(enum CXCursorKind K) {
5800 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005801 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5802}
5803
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005804unsigned clang_isInvalidDeclaration(CXCursor C) {
5805 if (clang_isDeclaration(C.kind)) {
5806 if (const Decl *D = getCursorDecl(C))
5807 return D->isInvalidDecl();
5808 }
5809
5810 return 0;
5811}
5812
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005813unsigned clang_isReference(enum CXCursorKind K) {
5814 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5815}
Guy Benyei11169dd2012-12-18 14:30:41 +00005816
5817unsigned clang_isExpression(enum CXCursorKind K) {
5818 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5819}
5820
5821unsigned clang_isStatement(enum CXCursorKind K) {
5822 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5823}
5824
5825unsigned clang_isAttribute(enum CXCursorKind K) {
5826 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5827}
5828
5829unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5830 return K == CXCursor_TranslationUnit;
5831}
5832
5833unsigned clang_isPreprocessing(enum CXCursorKind K) {
5834 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5835}
5836
5837unsigned clang_isUnexposed(enum CXCursorKind K) {
5838 switch (K) {
5839 case CXCursor_UnexposedDecl:
5840 case CXCursor_UnexposedExpr:
5841 case CXCursor_UnexposedStmt:
5842 case CXCursor_UnexposedAttr:
5843 return true;
5844 default:
5845 return false;
5846 }
5847}
5848
5849CXCursorKind clang_getCursorKind(CXCursor C) {
5850 return C.kind;
5851}
5852
5853CXSourceLocation clang_getCursorLocation(CXCursor C) {
5854 if (clang_isReference(C.kind)) {
5855 switch (C.kind) {
5856 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005857 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005858 = getCursorObjCSuperClassRef(C);
5859 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5860 }
5861
5862 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005863 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005864 = getCursorObjCProtocolRef(C);
5865 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5866 }
5867
5868 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005869 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005870 = getCursorObjCClassRef(C);
5871 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5872 }
5873
5874 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005875 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005876 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5877 }
5878
5879 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005880 std::pair<const TemplateDecl *, SourceLocation> P =
5881 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005882 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5883 }
5884
5885 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005886 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005887 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5888 }
5889
5890 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005891 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005892 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5893 }
5894
5895 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005896 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005897 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5898 }
5899
5900 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005901 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005902 if (!BaseSpec)
5903 return clang_getNullLocation();
5904
5905 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5906 return cxloc::translateSourceLocation(getCursorContext(C),
5907 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005908
Guy Benyei11169dd2012-12-18 14:30:41 +00005909 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005910 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005911 }
5912
5913 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005914 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005915 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5916 }
5917
5918 case CXCursor_OverloadedDeclRef:
5919 return cxloc::translateSourceLocation(getCursorContext(C),
5920 getCursorOverloadedDeclRef(C).second);
5921
5922 default:
5923 // FIXME: Need a way to enumerate all non-reference cases.
5924 llvm_unreachable("Missed a reference kind");
5925 }
5926 }
5927
5928 if (clang_isExpression(C.kind))
5929 return cxloc::translateSourceLocation(getCursorContext(C),
5930 getLocationFromExpr(getCursorExpr(C)));
5931
5932 if (clang_isStatement(C.kind))
5933 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005934 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005935
5936 if (C.kind == CXCursor_PreprocessingDirective) {
5937 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5938 return cxloc::translateSourceLocation(getCursorContext(C), L);
5939 }
5940
5941 if (C.kind == CXCursor_MacroExpansion) {
5942 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005943 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005944 return cxloc::translateSourceLocation(getCursorContext(C), L);
5945 }
5946
5947 if (C.kind == CXCursor_MacroDefinition) {
5948 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5949 return cxloc::translateSourceLocation(getCursorContext(C), L);
5950 }
5951
5952 if (C.kind == CXCursor_InclusionDirective) {
5953 SourceLocation L
5954 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5955 return cxloc::translateSourceLocation(getCursorContext(C), L);
5956 }
5957
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005958 if (clang_isAttribute(C.kind)) {
5959 SourceLocation L
5960 = cxcursor::getCursorAttr(C)->getLocation();
5961 return cxloc::translateSourceLocation(getCursorContext(C), L);
5962 }
5963
Guy Benyei11169dd2012-12-18 14:30:41 +00005964 if (!clang_isDeclaration(C.kind))
5965 return clang_getNullLocation();
5966
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005967 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005968 if (!D)
5969 return clang_getNullLocation();
5970
5971 SourceLocation Loc = D->getLocation();
5972 // FIXME: Multiple variables declared in a single declaration
5973 // currently lack the information needed to correctly determine their
5974 // ranges when accounting for the type-specifier. We use context
5975 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5976 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005977 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005978 if (!cxcursor::isFirstInDeclGroup(C))
5979 Loc = VD->getLocation();
5980 }
5981
5982 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005983 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005984 Loc = MD->getSelectorStartLoc();
5985
5986 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5987}
5988
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005989} // end extern "C"
5990
Guy Benyei11169dd2012-12-18 14:30:41 +00005991CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5992 assert(TU);
5993
5994 // Guard against an invalid SourceLocation, or we may assert in one
5995 // of the following calls.
5996 if (SLoc.isInvalid())
5997 return clang_getNullCursor();
5998
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005999 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006000
6001 // Translate the given source location to make it point at the beginning of
6002 // the token under the cursor.
6003 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
6004 CXXUnit->getASTContext().getLangOpts());
6005
6006 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
6007 if (SLoc.isValid()) {
6008 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
6009 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
6010 /*VisitPreprocessorLast=*/true,
6011 /*VisitIncludedEntities=*/false,
6012 SourceLocation(SLoc));
6013 CursorVis.visitFileRegion();
6014 }
6015
6016 return Result;
6017}
6018
6019static SourceRange getRawCursorExtent(CXCursor C) {
6020 if (clang_isReference(C.kind)) {
6021 switch (C.kind) {
6022 case CXCursor_ObjCSuperClassRef:
6023 return getCursorObjCSuperClassRef(C).second;
6024
6025 case CXCursor_ObjCProtocolRef:
6026 return getCursorObjCProtocolRef(C).second;
6027
6028 case CXCursor_ObjCClassRef:
6029 return getCursorObjCClassRef(C).second;
6030
6031 case CXCursor_TypeRef:
6032 return getCursorTypeRef(C).second;
6033
6034 case CXCursor_TemplateRef:
6035 return getCursorTemplateRef(C).second;
6036
6037 case CXCursor_NamespaceRef:
6038 return getCursorNamespaceRef(C).second;
6039
6040 case CXCursor_MemberRef:
6041 return getCursorMemberRef(C).second;
6042
6043 case CXCursor_CXXBaseSpecifier:
6044 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6045
6046 case CXCursor_LabelRef:
6047 return getCursorLabelRef(C).second;
6048
6049 case CXCursor_OverloadedDeclRef:
6050 return getCursorOverloadedDeclRef(C).second;
6051
6052 case CXCursor_VariableRef:
6053 return getCursorVariableRef(C).second;
6054
6055 default:
6056 // FIXME: Need a way to enumerate all non-reference cases.
6057 llvm_unreachable("Missed a reference kind");
6058 }
6059 }
6060
6061 if (clang_isExpression(C.kind))
6062 return getCursorExpr(C)->getSourceRange();
6063
6064 if (clang_isStatement(C.kind))
6065 return getCursorStmt(C)->getSourceRange();
6066
6067 if (clang_isAttribute(C.kind))
6068 return getCursorAttr(C)->getRange();
6069
6070 if (C.kind == CXCursor_PreprocessingDirective)
6071 return cxcursor::getCursorPreprocessingDirective(C);
6072
6073 if (C.kind == CXCursor_MacroExpansion) {
6074 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006075 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006076 return TU->mapRangeFromPreamble(Range);
6077 }
6078
6079 if (C.kind == CXCursor_MacroDefinition) {
6080 ASTUnit *TU = getCursorASTUnit(C);
6081 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6082 return TU->mapRangeFromPreamble(Range);
6083 }
6084
6085 if (C.kind == CXCursor_InclusionDirective) {
6086 ASTUnit *TU = getCursorASTUnit(C);
6087 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6088 return TU->mapRangeFromPreamble(Range);
6089 }
6090
6091 if (C.kind == CXCursor_TranslationUnit) {
6092 ASTUnit *TU = getCursorASTUnit(C);
6093 FileID MainID = TU->getSourceManager().getMainFileID();
6094 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6095 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6096 return SourceRange(Start, End);
6097 }
6098
6099 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006100 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006101 if (!D)
6102 return SourceRange();
6103
6104 SourceRange R = D->getSourceRange();
6105 // FIXME: Multiple variables declared in a single declaration
6106 // currently lack the information needed to correctly determine their
6107 // ranges when accounting for the type-specifier. We use context
6108 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6109 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006110 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006111 if (!cxcursor::isFirstInDeclGroup(C))
6112 R.setBegin(VD->getLocation());
6113 }
6114 return R;
6115 }
6116 return SourceRange();
6117}
6118
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006119/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006120/// the decl-specifier-seq for declarations.
6121static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6122 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006123 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006124 if (!D)
6125 return SourceRange();
6126
6127 SourceRange R = D->getSourceRange();
6128
6129 // Adjust the start of the location for declarations preceded by
6130 // declaration specifiers.
6131 SourceLocation StartLoc;
6132 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6133 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006134 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006135 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006137 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006138 }
6139
6140 if (StartLoc.isValid() && R.getBegin().isValid() &&
6141 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6142 R.setBegin(StartLoc);
6143
6144 // FIXME: Multiple variables declared in a single declaration
6145 // currently lack the information needed to correctly determine their
6146 // ranges when accounting for the type-specifier. We use context
6147 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6148 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006149 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006150 if (!cxcursor::isFirstInDeclGroup(C))
6151 R.setBegin(VD->getLocation());
6152 }
6153
6154 return R;
6155 }
6156
6157 return getRawCursorExtent(C);
6158}
6159
Guy Benyei11169dd2012-12-18 14:30:41 +00006160CXSourceRange clang_getCursorExtent(CXCursor C) {
6161 SourceRange R = getRawCursorExtent(C);
6162 if (R.isInvalid())
6163 return clang_getNullRange();
6164
6165 return cxloc::translateSourceRange(getCursorContext(C), R);
6166}
6167
6168CXCursor clang_getCursorReferenced(CXCursor C) {
6169 if (clang_isInvalid(C.kind))
6170 return clang_getNullCursor();
6171
6172 CXTranslationUnit tu = getCursorTU(C);
6173 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006174 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 if (!D)
6176 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006177 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006179 if (const ObjCPropertyImplDecl *PropImpl =
6180 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6182 return MakeCXCursor(Property, tu);
6183
6184 return C;
6185 }
6186
6187 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006188 const Expr *E = getCursorExpr(C);
6189 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006190 if (D) {
6191 CXCursor declCursor = MakeCXCursor(D, tu);
6192 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6193 declCursor);
6194 return declCursor;
6195 }
6196
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006197 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006198 return MakeCursorOverloadedDeclRef(Ovl, tu);
6199
6200 return clang_getNullCursor();
6201 }
6202
6203 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006204 const Stmt *S = getCursorStmt(C);
6205 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006206 if (LabelDecl *label = Goto->getLabel())
6207 if (LabelStmt *labelS = label->getStmt())
6208 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6209
6210 return clang_getNullCursor();
6211 }
Richard Smith66a81862015-05-04 02:25:31 +00006212
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006214 if (const MacroDefinitionRecord *Def =
6215 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006216 return MakeMacroDefinitionCursor(Def, tu);
6217 }
6218
6219 if (!clang_isReference(C.kind))
6220 return clang_getNullCursor();
6221
6222 switch (C.kind) {
6223 case CXCursor_ObjCSuperClassRef:
6224 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6225
6226 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006227 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6228 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 return MakeCXCursor(Def, tu);
6230
6231 return MakeCXCursor(Prot, tu);
6232 }
6233
6234 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006235 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6236 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006237 return MakeCXCursor(Def, tu);
6238
6239 return MakeCXCursor(Class, tu);
6240 }
6241
6242 case CXCursor_TypeRef:
6243 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6244
6245 case CXCursor_TemplateRef:
6246 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6247
6248 case CXCursor_NamespaceRef:
6249 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6250
6251 case CXCursor_MemberRef:
6252 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6253
6254 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006255 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006256 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6257 tu ));
6258 }
6259
6260 case CXCursor_LabelRef:
6261 // FIXME: We end up faking the "parent" declaration here because we
6262 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006263 return MakeCXCursor(getCursorLabelRef(C).first,
6264 cxtu::getASTUnit(tu)->getASTContext()
6265 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006266 tu);
6267
6268 case CXCursor_OverloadedDeclRef:
6269 return C;
6270
6271 case CXCursor_VariableRef:
6272 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6273
6274 default:
6275 // We would prefer to enumerate all non-reference cursor kinds here.
6276 llvm_unreachable("Unhandled reference cursor kind");
6277 }
6278}
6279
6280CXCursor clang_getCursorDefinition(CXCursor C) {
6281 if (clang_isInvalid(C.kind))
6282 return clang_getNullCursor();
6283
6284 CXTranslationUnit TU = getCursorTU(C);
6285
6286 bool WasReference = false;
6287 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6288 C = clang_getCursorReferenced(C);
6289 WasReference = true;
6290 }
6291
6292 if (C.kind == CXCursor_MacroExpansion)
6293 return clang_getCursorReferenced(C);
6294
6295 if (!clang_isDeclaration(C.kind))
6296 return clang_getNullCursor();
6297
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006298 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006299 if (!D)
6300 return clang_getNullCursor();
6301
6302 switch (D->getKind()) {
6303 // Declaration kinds that don't really separate the notions of
6304 // declaration and definition.
6305 case Decl::Namespace:
6306 case Decl::Typedef:
6307 case Decl::TypeAlias:
6308 case Decl::TypeAliasTemplate:
6309 case Decl::TemplateTypeParm:
6310 case Decl::EnumConstant:
6311 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006312 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006313 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006314 case Decl::IndirectField:
6315 case Decl::ObjCIvar:
6316 case Decl::ObjCAtDefsField:
6317 case Decl::ImplicitParam:
6318 case Decl::ParmVar:
6319 case Decl::NonTypeTemplateParm:
6320 case Decl::TemplateTemplateParm:
6321 case Decl::ObjCCategoryImpl:
6322 case Decl::ObjCImplementation:
6323 case Decl::AccessSpec:
6324 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006325 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006326 case Decl::ObjCPropertyImpl:
6327 case Decl::FileScopeAsm:
6328 case Decl::StaticAssert:
6329 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006330 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006331 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006332 case Decl::Label: // FIXME: Is this right??
6333 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006334 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006335 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006336 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006337 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006338 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006339 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006340 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006341 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006342 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006343 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006344 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006345 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006346 case Decl::Concept:
Tykerb0561b32019-11-17 11:41:55 +01006347 case Decl::LifetimeExtendedTemporary:
Saar Raza0f50d72020-01-18 09:11:43 +02006348 case Decl::RequiresExprBody:
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 return C;
6350
6351 // Declaration kinds that don't make any sense here, but are
6352 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006353 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006354 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006355 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 break;
6357
6358 // Declaration kinds for which the definition is not resolvable.
6359 case Decl::UnresolvedUsingTypename:
6360 case Decl::UnresolvedUsingValue:
6361 break;
6362
6363 case Decl::UsingDirective:
6364 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6365 TU);
6366
6367 case Decl::NamespaceAlias:
6368 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6369
6370 case Decl::Enum:
6371 case Decl::Record:
6372 case Decl::CXXRecord:
6373 case Decl::ClassTemplateSpecialization:
6374 case Decl::ClassTemplatePartialSpecialization:
6375 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6376 return MakeCXCursor(Def, TU);
6377 return clang_getNullCursor();
6378
6379 case Decl::Function:
6380 case Decl::CXXMethod:
6381 case Decl::CXXConstructor:
6382 case Decl::CXXDestructor:
6383 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006384 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006385 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006386 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006387 return clang_getNullCursor();
6388 }
6389
Larisse Voufo39a1e502013-08-06 01:03:05 +00006390 case Decl::Var:
6391 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006392 case Decl::VarTemplatePartialSpecialization:
6393 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006395 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006396 return MakeCXCursor(Def, TU);
6397 return clang_getNullCursor();
6398 }
6399
6400 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006401 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6403 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6404 return clang_getNullCursor();
6405 }
6406
6407 case Decl::ClassTemplate: {
6408 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6409 ->getDefinition())
6410 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6411 TU);
6412 return clang_getNullCursor();
6413 }
6414
Larisse Voufo39a1e502013-08-06 01:03:05 +00006415 case Decl::VarTemplate: {
6416 if (VarDecl *Def =
6417 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6418 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6419 return clang_getNullCursor();
6420 }
6421
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 case Decl::Using:
6423 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6424 D->getLocation(), TU);
6425
6426 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006427 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006428 return clang_getCursorDefinition(
6429 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6430 TU));
6431
6432 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006433 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006434 if (Method->isThisDeclarationADefinition())
6435 return C;
6436
6437 // Dig out the method definition in the associated
6438 // @implementation, if we have it.
6439 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006440 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006441 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6442 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6443 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6444 Method->isInstanceMethod()))
6445 if (Def->isThisDeclarationADefinition())
6446 return MakeCXCursor(Def, TU);
6447
6448 return clang_getNullCursor();
6449 }
6450
6451 case Decl::ObjCCategory:
6452 if (ObjCCategoryImplDecl *Impl
6453 = cast<ObjCCategoryDecl>(D)->getImplementation())
6454 return MakeCXCursor(Impl, TU);
6455 return clang_getNullCursor();
6456
6457 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006458 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006459 return MakeCXCursor(Def, TU);
6460 return clang_getNullCursor();
6461
6462 case Decl::ObjCInterface: {
6463 // There are two notions of a "definition" for an Objective-C
6464 // class: the interface and its implementation. When we resolved a
6465 // reference to an Objective-C class, produce the @interface as
6466 // the definition; when we were provided with the interface,
6467 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006468 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006469 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006470 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006471 return MakeCXCursor(Def, TU);
6472 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6473 return MakeCXCursor(Impl, TU);
6474 return clang_getNullCursor();
6475 }
6476
6477 case Decl::ObjCProperty:
6478 // FIXME: We don't really know where to find the
6479 // ObjCPropertyImplDecls that implement this property.
6480 return clang_getNullCursor();
6481
6482 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006483 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006485 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006486 return MakeCXCursor(Def, TU);
6487
6488 return clang_getNullCursor();
6489
6490 case Decl::Friend:
6491 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6492 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6493 return clang_getNullCursor();
6494
6495 case Decl::FriendTemplate:
6496 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6497 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6498 return clang_getNullCursor();
6499 }
6500
6501 return clang_getNullCursor();
6502}
6503
6504unsigned clang_isCursorDefinition(CXCursor C) {
6505 if (!clang_isDeclaration(C.kind))
6506 return 0;
6507
6508 return clang_getCursorDefinition(C) == C;
6509}
6510
6511CXCursor clang_getCanonicalCursor(CXCursor C) {
6512 if (!clang_isDeclaration(C.kind))
6513 return C;
6514
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006515 if (const Decl *D = getCursorDecl(C)) {
6516 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6518 return MakeCXCursor(CatD, getCursorTU(C));
6519
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006520 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6521 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 return MakeCXCursor(IFD, getCursorTU(C));
6523
6524 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6525 }
6526
6527 return C;
6528}
6529
6530int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6531 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6532}
6533
6534unsigned clang_getNumOverloadedDecls(CXCursor C) {
6535 if (C.kind != CXCursor_OverloadedDeclRef)
6536 return 0;
6537
6538 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006539 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006540 return E->getNumDecls();
6541
6542 if (OverloadedTemplateStorage *S
6543 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6544 return S->size();
6545
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006546 const Decl *D = Storage.get<const Decl *>();
6547 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006548 return Using->shadow_size();
6549
6550 return 0;
6551}
6552
6553CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6554 if (cursor.kind != CXCursor_OverloadedDeclRef)
6555 return clang_getNullCursor();
6556
6557 if (index >= clang_getNumOverloadedDecls(cursor))
6558 return clang_getNullCursor();
6559
6560 CXTranslationUnit TU = getCursorTU(cursor);
6561 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006562 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006563 return MakeCXCursor(E->decls_begin()[index], TU);
6564
6565 if (OverloadedTemplateStorage *S
6566 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6567 return MakeCXCursor(S->begin()[index], TU);
6568
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006569 const Decl *D = Storage.get<const Decl *>();
6570 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006571 // FIXME: This is, unfortunately, linear time.
6572 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6573 std::advance(Pos, index);
6574 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6575 }
6576
6577 return clang_getNullCursor();
6578}
6579
6580void clang_getDefinitionSpellingAndExtent(CXCursor C,
6581 const char **startBuf,
6582 const char **endBuf,
6583 unsigned *startLine,
6584 unsigned *startColumn,
6585 unsigned *endLine,
6586 unsigned *endColumn) {
6587 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006588 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006589 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6590
6591 SourceManager &SM = FD->getASTContext().getSourceManager();
6592 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6593 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6594 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6595 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6596 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6597 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6598}
6599
6600
6601CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6602 unsigned PieceIndex) {
6603 RefNamePieces Pieces;
6604
6605 switch (C.kind) {
6606 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006607 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006608 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6609 E->getQualifierLoc().getSourceRange());
6610 break;
6611
6612 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006613 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6614 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6615 Pieces =
6616 buildPieces(NameFlags, false, E->getNameInfo(),
6617 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6618 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006619 break;
6620
6621 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006622 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006623 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006624 const Expr *Callee = OCE->getCallee();
6625 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006626 Callee = ICE->getSubExpr();
6627
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006628 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006629 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6630 DRE->getQualifierLoc().getSourceRange());
6631 }
6632 break;
6633
6634 default:
6635 break;
6636 }
6637
6638 if (Pieces.empty()) {
6639 if (PieceIndex == 0)
6640 return clang_getCursorExtent(C);
6641 } else if (PieceIndex < Pieces.size()) {
6642 SourceRange R = Pieces[PieceIndex];
6643 if (R.isValid())
6644 return cxloc::translateSourceRange(getCursorContext(C), R);
6645 }
6646
6647 return clang_getNullRange();
6648}
6649
6650void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006651 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6652 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006653}
6654
6655void clang_executeOnThread(void (*fn)(void*), void *user_data,
6656 unsigned stack_size) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05006657 llvm::llvm_execute_on_thread(fn, user_data,
6658 stack_size == 0
6659 ? clang::DesiredStackSize
6660 : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006661}
6662
Guy Benyei11169dd2012-12-18 14:30:41 +00006663//===----------------------------------------------------------------------===//
6664// Token-based Operations.
6665//===----------------------------------------------------------------------===//
6666
6667/* CXToken layout:
6668 * int_data[0]: a CXTokenKind
6669 * int_data[1]: starting token location
6670 * int_data[2]: token length
6671 * int_data[3]: reserved
6672 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6673 * otherwise unused.
6674 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006675CXTokenKind clang_getTokenKind(CXToken CXTok) {
6676 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6677}
6678
6679CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6680 switch (clang_getTokenKind(CXTok)) {
6681 case CXToken_Identifier:
6682 case CXToken_Keyword:
6683 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006684 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006685 ->getNameStart());
6686
6687 case CXToken_Literal: {
6688 // We have stashed the starting pointer in the ptr_data field. Use it.
6689 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006690 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006691 }
6692
6693 case CXToken_Punctuation:
6694 case CXToken_Comment:
6695 break;
6696 }
6697
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006698 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006699 LOG_BAD_TU(TU);
6700 return cxstring::createEmpty();
6701 }
6702
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 // We have to find the starting buffer pointer the hard way, by
6704 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006705 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006707 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006708
6709 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6710 std::pair<FileID, unsigned> LocInfo
6711 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6712 bool Invalid = false;
6713 StringRef Buffer
6714 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6715 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006716 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006717
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006718 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006719}
6720
6721CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006722 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006723 LOG_BAD_TU(TU);
6724 return clang_getNullLocation();
6725 }
6726
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006727 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006728 if (!CXXUnit)
6729 return clang_getNullLocation();
6730
6731 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6732 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6733}
6734
6735CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006736 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006737 LOG_BAD_TU(TU);
6738 return clang_getNullRange();
6739 }
6740
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006741 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006742 if (!CXXUnit)
6743 return clang_getNullRange();
6744
6745 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6746 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6747}
6748
6749static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6750 SmallVectorImpl<CXToken> &CXTokens) {
6751 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6752 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006753 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006754 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006755 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006756
6757 // Cannot tokenize across files.
6758 if (BeginLocInfo.first != EndLocInfo.first)
6759 return;
6760
6761 // Create a lexer
6762 bool Invalid = false;
6763 StringRef Buffer
6764 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6765 if (Invalid)
6766 return;
6767
6768 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6769 CXXUnit->getASTContext().getLangOpts(),
6770 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6771 Lex.SetCommentRetentionState(true);
6772
6773 // Lex tokens until we hit the end of the range.
6774 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6775 Token Tok;
6776 bool previousWasAt = false;
6777 do {
6778 // Lex the next token
6779 Lex.LexFromRawLexer(Tok);
6780 if (Tok.is(tok::eof))
6781 break;
6782
6783 // Initialize the CXToken.
6784 CXToken CXTok;
6785
6786 // - Common fields
6787 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6788 CXTok.int_data[2] = Tok.getLength();
6789 CXTok.int_data[3] = 0;
6790
6791 // - Kind-specific fields
6792 if (Tok.isLiteral()) {
6793 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006794 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006795 } else if (Tok.is(tok::raw_identifier)) {
6796 // Lookup the identifier to determine whether we have a keyword.
6797 IdentifierInfo *II
6798 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6799
6800 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6801 CXTok.int_data[0] = CXToken_Keyword;
6802 }
6803 else {
6804 CXTok.int_data[0] = Tok.is(tok::identifier)
6805 ? CXToken_Identifier
6806 : CXToken_Keyword;
6807 }
6808 CXTok.ptr_data = II;
6809 } else if (Tok.is(tok::comment)) {
6810 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006811 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006812 } else {
6813 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006814 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006815 }
6816 CXTokens.push_back(CXTok);
6817 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006818 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006819}
6820
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006821CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6822 LOG_FUNC_SECTION {
6823 *Log << TU << ' ' << Location;
6824 }
6825
6826 if (isNotUsableTU(TU)) {
6827 LOG_BAD_TU(TU);
6828 return NULL;
6829 }
6830
6831 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6832 if (!CXXUnit)
6833 return NULL;
6834
6835 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6836 if (Begin.isInvalid())
6837 return NULL;
6838 SourceManager &SM = CXXUnit->getSourceManager();
6839 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6840 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6841
6842 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6843
6844 SmallVector<CXToken, 32> CXTokens;
6845 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6846
6847 if (CXTokens.empty())
6848 return NULL;
6849
6850 CXTokens.resize(1);
6851 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6852
6853 memmove(Token, CXTokens.data(), sizeof(CXToken));
6854 return Token;
6855}
6856
Guy Benyei11169dd2012-12-18 14:30:41 +00006857void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6858 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006859 LOG_FUNC_SECTION {
6860 *Log << TU << ' ' << Range;
6861 }
6862
Guy Benyei11169dd2012-12-18 14:30:41 +00006863 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006864 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006865 if (NumTokens)
6866 *NumTokens = 0;
6867
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006868 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006869 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006870 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006871 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006872
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006873 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006874 if (!CXXUnit || !Tokens || !NumTokens)
6875 return;
6876
6877 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6878
6879 SourceRange R = cxloc::translateCXSourceRange(Range);
6880 if (R.isInvalid())
6881 return;
6882
6883 SmallVector<CXToken, 32> CXTokens;
6884 getTokens(CXXUnit, R, CXTokens);
6885
6886 if (CXTokens.empty())
6887 return;
6888
Serge Pavlov52525732018-02-21 02:02:39 +00006889 *Tokens = static_cast<CXToken *>(
6890 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6892 *NumTokens = CXTokens.size();
6893}
6894
6895void clang_disposeTokens(CXTranslationUnit TU,
6896 CXToken *Tokens, unsigned NumTokens) {
6897 free(Tokens);
6898}
6899
Guy Benyei11169dd2012-12-18 14:30:41 +00006900//===----------------------------------------------------------------------===//
6901// Token annotation APIs.
6902//===----------------------------------------------------------------------===//
6903
Guy Benyei11169dd2012-12-18 14:30:41 +00006904static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6905 CXCursor parent,
6906 CXClientData client_data);
6907static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6908 CXClientData client_data);
6909
6910namespace {
6911class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006912 CXToken *Tokens;
6913 CXCursor *Cursors;
6914 unsigned NumTokens;
6915 unsigned TokIdx;
6916 unsigned PreprocessingTokIdx;
6917 CursorVisitor AnnotateVis;
6918 SourceManager &SrcMgr;
6919 bool HasContextSensitiveKeywords;
6920
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006921 struct PostChildrenAction {
6922 CXCursor cursor;
6923 enum Action { Invalid, Ignore, Postpone } action;
6924 };
6925 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6926
Guy Benyei11169dd2012-12-18 14:30:41 +00006927 struct PostChildrenInfo {
6928 CXCursor Cursor;
6929 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006930 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006931 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006932 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006934 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006935
6936 CXToken &getTok(unsigned Idx) {
6937 assert(Idx < NumTokens);
6938 return Tokens[Idx];
6939 }
6940 const CXToken &getTok(unsigned Idx) const {
6941 assert(Idx < NumTokens);
6942 return Tokens[Idx];
6943 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 bool MoreTokens() const { return TokIdx < NumTokens; }
6945 unsigned NextToken() const { return TokIdx; }
6946 void AdvanceToken() { ++TokIdx; }
6947 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006948 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 }
6950 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006951 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 }
6953 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006954 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 }
6956
6957 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006958 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 SourceRange);
6960
6961public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006962 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006963 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006964 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006965 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006966 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006967 AnnotateTokensVisitor, this,
6968 /*VisitPreprocessorLast=*/true,
6969 /*VisitIncludedEntities=*/false,
6970 RegionOfInterest,
6971 /*VisitDeclsOnly=*/false,
6972 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006973 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006974 HasContextSensitiveKeywords(false) { }
6975
6976 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6977 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006978 bool IsIgnoredChildCursor(CXCursor cursor) const;
6979 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6980
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006982 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6983 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6984
Guy Benyei11169dd2012-12-18 14:30:41 +00006985 void AnnotateTokens();
6986
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006987 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006988 /// context-sensitive keywords.
6989 bool hasContextSensitiveKeywords() const {
6990 return HasContextSensitiveKeywords;
6991 }
6992
6993 ~AnnotateTokensWorker() {
6994 assert(PostChildrenInfos.empty());
6995 }
6996};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006997}
Guy Benyei11169dd2012-12-18 14:30:41 +00006998
6999void AnnotateTokensWorker::AnnotateTokens() {
7000 // Walk the AST within the region of interest, annotating tokens
7001 // along the way.
7002 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007003}
Guy Benyei11169dd2012-12-18 14:30:41 +00007004
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007005bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
7006 if (PostChildrenInfos.empty())
7007 return false;
7008
7009 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
7010 if (ChildAction.cursor == cursor &&
7011 ChildAction.action == PostChildrenAction::Ignore) {
7012 return true;
7013 }
7014 }
7015
7016 return false;
7017}
7018
7019const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
7020 if (!clang_isExpression(Cursor.kind))
7021 return nullptr;
7022
7023 const Expr *E = getCursorExpr(Cursor);
7024 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7025 const OverloadedOperatorKind Kind = OCE->getOperator();
7026 if (Kind == OO_Call || Kind == OO_Subscript)
7027 return OCE;
7028 }
7029
7030 return nullptr;
7031}
7032
7033AnnotateTokensWorker::PostChildrenActions
7034AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7035 PostChildrenActions actions;
7036
7037 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
7038 // visited before the arguments to the operator call. For the Call and
7039 // Subscript operator the range of this DeclRefExpr includes the whole call
7040 // expression, so that all tokens in that range would be mapped to the
7041 // operator function, including the tokens of the arguments. To avoid that,
7042 // ensure to visit this DeclRefExpr as last node.
7043 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7044 const Expr *Callee = OCE->getCallee();
7045 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7046 const Expr *SubExpr = ICE->getSubExpr();
7047 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007048 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007049 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7050
7051 // Visit the DeclRefExpr as last.
7052 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7053 actions.push_back({cxChild, PostChildrenAction::Postpone});
7054
7055 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7056 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7057 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7058 actions.push_back({cxChild, PostChildrenAction::Ignore});
7059 }
7060 }
7061 }
7062
7063 return actions;
7064}
7065
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007066static inline void updateCursorAnnotation(CXCursor &Cursor,
7067 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007068 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007069 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007070 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007071}
7072
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007073/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007074//// between the cursor location and the source range is the same as
7075/// \arg compResult.
7076///
7077/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7078/// Pass RangeOverlap to annotate tokens inside a range.
7079void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7080 RangeComparisonResult compResult,
7081 SourceRange range) {
7082 while (MoreTokens()) {
7083 const unsigned I = NextToken();
7084 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007085 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7086 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007087
7088 SourceLocation TokLoc = GetTokenLoc(I);
7089 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007090 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007091 AdvanceToken();
7092 continue;
7093 }
7094 break;
7095 }
7096}
7097
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007098/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007099/// \returns true if it advanced beyond all macro tokens, false otherwise.
7100bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007101 CXCursor updateC,
7102 RangeComparisonResult compResult,
7103 SourceRange range) {
7104 assert(MoreTokens());
7105 assert(isFunctionMacroToken(NextToken()) &&
7106 "Should be called only for macro arg tokens");
7107
7108 // This works differently than annotateAndAdvanceTokens; because expanded
7109 // macro arguments can have arbitrary translation-unit source order, we do not
7110 // advance the token index one by one until a token fails the range test.
7111 // We only advance once past all of the macro arg tokens if all of them
7112 // pass the range test. If one of them fails we keep the token index pointing
7113 // at the start of the macro arg tokens so that the failing token will be
7114 // annotated by a subsequent annotation try.
7115
7116 bool atLeastOneCompFail = false;
7117
7118 unsigned I = NextToken();
7119 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7120 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7121 if (TokLoc.isFileID())
7122 continue; // not macro arg token, it's parens or comma.
7123 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7124 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7125 Cursors[I] = updateC;
7126 } else
7127 atLeastOneCompFail = true;
7128 }
7129
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007130 if (atLeastOneCompFail)
7131 return false;
7132
7133 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7134 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007135}
7136
7137enum CXChildVisitResult
7138AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007139 SourceRange cursorRange = getRawCursorExtent(cursor);
7140 if (cursorRange.isInvalid())
7141 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007142
7143 if (IsIgnoredChildCursor(cursor))
7144 return CXChildVisit_Continue;
7145
Guy Benyei11169dd2012-12-18 14:30:41 +00007146 if (!HasContextSensitiveKeywords) {
7147 // Objective-C properties can have context-sensitive keywords.
7148 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007149 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007150 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7151 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7152 }
7153 // Objective-C methods can have context-sensitive keywords.
7154 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7155 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007156 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7158 if (Method->getObjCDeclQualifier())
7159 HasContextSensitiveKeywords = true;
7160 else {
David Majnemer59f77922016-06-24 04:05:48 +00007161 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007162 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 HasContextSensitiveKeywords = true;
7164 break;
7165 }
7166 }
7167 }
7168 }
7169 }
7170 // C++ methods can have context-sensitive keywords.
7171 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007172 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007173 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7174 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7175 HasContextSensitiveKeywords = true;
7176 }
7177 }
7178 // C++ classes can have context-sensitive keywords.
7179 else if (cursor.kind == CXCursor_StructDecl ||
7180 cursor.kind == CXCursor_ClassDecl ||
7181 cursor.kind == CXCursor_ClassTemplate ||
7182 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007183 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007184 if (D->hasAttr<FinalAttr>())
7185 HasContextSensitiveKeywords = true;
7186 }
7187 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007188
7189 // Don't override a property annotation with its getter/setter method.
7190 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7191 parent.kind == CXCursor_ObjCPropertyDecl)
7192 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007193
7194 if (clang_isPreprocessing(cursor.kind)) {
7195 // Items in the preprocessing record are kept separate from items in
7196 // declarations, so we keep a separate token index.
7197 unsigned SavedTokIdx = TokIdx;
7198 TokIdx = PreprocessingTokIdx;
7199
7200 // Skip tokens up until we catch up to the beginning of the preprocessing
7201 // entry.
7202 while (MoreTokens()) {
7203 const unsigned I = NextToken();
7204 SourceLocation TokLoc = GetTokenLoc(I);
7205 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7206 case RangeBefore:
7207 AdvanceToken();
7208 continue;
7209 case RangeAfter:
7210 case RangeOverlap:
7211 break;
7212 }
7213 break;
7214 }
7215
7216 // Look at all of the tokens within this range.
7217 while (MoreTokens()) {
7218 const unsigned I = NextToken();
7219 SourceLocation TokLoc = GetTokenLoc(I);
7220 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7221 case RangeBefore:
7222 llvm_unreachable("Infeasible");
7223 case RangeAfter:
7224 break;
7225 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007226 // For macro expansions, just note where the beginning of the macro
7227 // expansion occurs.
7228 if (cursor.kind == CXCursor_MacroExpansion) {
7229 if (TokLoc == cursorRange.getBegin())
7230 Cursors[I] = cursor;
7231 AdvanceToken();
7232 break;
7233 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007234 // We may have already annotated macro names inside macro definitions.
7235 if (Cursors[I].kind != CXCursor_MacroExpansion)
7236 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007237 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007238 continue;
7239 }
7240 break;
7241 }
7242
7243 // Save the preprocessing token index; restore the non-preprocessing
7244 // token index.
7245 PreprocessingTokIdx = TokIdx;
7246 TokIdx = SavedTokIdx;
7247 return CXChildVisit_Recurse;
7248 }
7249
7250 if (cursorRange.isInvalid())
7251 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007252
7253 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 const enum CXCursorKind K = clang_getCursorKind(parent);
7256 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007257 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7258 // Attributes are annotated out-of-order, skip tokens until we reach it.
7259 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 ? clang_getNullCursor() : parent;
7261
7262 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7263
7264 // Avoid having the cursor of an expression "overwrite" the annotation of the
7265 // variable declaration that it belongs to.
7266 // This can happen for C++ constructor expressions whose range generally
7267 // include the variable declaration, e.g.:
7268 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007269 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007270 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007271 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007272 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007273 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7274 E->getBeginLoc() == D->getLocation() &&
7275 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007276 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007277 AdvanceToken();
7278 }
7279 }
7280 }
7281
7282 // Before recursing into the children keep some state that we are going
7283 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7284 // extra work after the child nodes are visited.
7285 // Note that we don't call VisitChildren here to avoid traversing statements
7286 // code-recursively which can blow the stack.
7287
7288 PostChildrenInfo Info;
7289 Info.Cursor = cursor;
7290 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007291 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007292 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007293 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007294 PostChildrenInfos.push_back(Info);
7295
7296 return CXChildVisit_Recurse;
7297}
7298
7299bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7300 if (PostChildrenInfos.empty())
7301 return false;
7302 const PostChildrenInfo &Info = PostChildrenInfos.back();
7303 if (!clang_equalCursors(Info.Cursor, cursor))
7304 return false;
7305
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007306 HandlePostPonedChildCursors(Info);
7307
Guy Benyei11169dd2012-12-18 14:30:41 +00007308 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7309 const unsigned AfterChildren = NextToken();
7310 SourceRange cursorRange = Info.CursorRange;
7311
7312 // Scan the tokens that are at the end of the cursor, but are not captured
7313 // but the child cursors.
7314 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7315
7316 // Scan the tokens that are at the beginning of the cursor, but are not
7317 // capture by the child cursors.
7318 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7319 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7320 break;
7321
7322 Cursors[I] = cursor;
7323 }
7324
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007325 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7326 // encountered the attribute cursor.
7327 if (clang_isAttribute(cursor.kind))
7328 TokIdx = Info.BeforeReachingCursorIdx;
7329
Guy Benyei11169dd2012-12-18 14:30:41 +00007330 PostChildrenInfos.pop_back();
7331 return false;
7332}
7333
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007334void AnnotateTokensWorker::HandlePostPonedChildCursors(
7335 const PostChildrenInfo &Info) {
7336 for (const auto &ChildAction : Info.ChildActions) {
7337 if (ChildAction.action == PostChildrenAction::Postpone) {
7338 HandlePostPonedChildCursor(ChildAction.cursor,
7339 Info.BeforeChildrenTokenIdx);
7340 }
7341 }
7342}
7343
7344void AnnotateTokensWorker::HandlePostPonedChildCursor(
7345 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007346 unsigned I = StartTokenIndex;
7347
7348 // The bracket tokens of a Call or Subscript operator are mapped to
7349 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7350 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7351 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007352 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7353 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007354 if (clang_Range_isNull(CXRefNameRange))
7355 break; // All ranges handled.
7356
7357 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7358 while (I < NumTokens) {
7359 const SourceLocation TokenLocation = GetTokenLoc(I);
7360 if (!TokenLocation.isValid())
7361 break;
7362
7363 // Adapt the end range, because LocationCompare() reports
7364 // RangeOverlap even for the not-inclusive end location.
7365 const SourceLocation fixedEnd =
7366 RefNameRange.getEnd().getLocWithOffset(-1);
7367 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7368
7369 const RangeComparisonResult ComparisonResult =
7370 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7371
7372 if (ComparisonResult == RangeOverlap) {
7373 Cursors[I++] = Cursor;
7374 } else if (ComparisonResult == RangeBefore) {
7375 ++I; // Not relevant token, check next one.
7376 } else if (ComparisonResult == RangeAfter) {
7377 break; // All tokens updated for current range, check next.
7378 }
7379 }
7380 }
7381}
7382
Guy Benyei11169dd2012-12-18 14:30:41 +00007383static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7384 CXCursor parent,
7385 CXClientData client_data) {
7386 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7387}
7388
7389static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7390 CXClientData client_data) {
7391 return static_cast<AnnotateTokensWorker*>(client_data)->
7392 postVisitChildren(cursor);
7393}
7394
7395namespace {
7396
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007397/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007398/// and mark tokens that are macro arguments. This info is used by the
7399/// AnnotateTokensWorker.
7400class MarkMacroArgTokensVisitor {
7401 SourceManager &SM;
7402 CXToken *Tokens;
7403 unsigned NumTokens;
7404 unsigned CurIdx;
7405
7406public:
7407 MarkMacroArgTokensVisitor(SourceManager &SM,
7408 CXToken *tokens, unsigned numTokens)
7409 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7410
7411 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7412 if (cursor.kind != CXCursor_MacroExpansion)
7413 return CXChildVisit_Continue;
7414
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007415 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007416 if (macroRange.getBegin() == macroRange.getEnd())
7417 return CXChildVisit_Continue; // it's not a function macro.
7418
7419 for (; CurIdx < NumTokens; ++CurIdx) {
7420 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7421 macroRange.getBegin()))
7422 break;
7423 }
7424
7425 if (CurIdx == NumTokens)
7426 return CXChildVisit_Break;
7427
7428 for (; CurIdx < NumTokens; ++CurIdx) {
7429 SourceLocation tokLoc = getTokenLoc(CurIdx);
7430 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7431 break;
7432
7433 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7434 }
7435
7436 if (CurIdx == NumTokens)
7437 return CXChildVisit_Break;
7438
7439 return CXChildVisit_Continue;
7440 }
7441
7442private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007443 CXToken &getTok(unsigned Idx) {
7444 assert(Idx < NumTokens);
7445 return Tokens[Idx];
7446 }
7447 const CXToken &getTok(unsigned Idx) const {
7448 assert(Idx < NumTokens);
7449 return Tokens[Idx];
7450 }
7451
Guy Benyei11169dd2012-12-18 14:30:41 +00007452 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007453 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007454 }
7455
7456 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7457 // The third field is reserved and currently not used. Use it here
7458 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007459 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007460 }
7461};
7462
7463} // end anonymous namespace
7464
7465static CXChildVisitResult
7466MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7467 CXClientData client_data) {
7468 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7469 parent);
7470}
7471
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007472/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007473/// \returns true if lexing was finished, false otherwise.
7474static bool lexNext(Lexer &Lex, Token &Tok,
7475 unsigned &NextIdx, unsigned NumTokens) {
7476 if (NextIdx >= NumTokens)
7477 return true;
7478
7479 ++NextIdx;
7480 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007481 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007482}
7483
Guy Benyei11169dd2012-12-18 14:30:41 +00007484static void annotatePreprocessorTokens(CXTranslationUnit TU,
7485 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007486 CXCursor *Cursors,
7487 CXToken *Tokens,
7488 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007489 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007490
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007491 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007492 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7493 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007494 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007495 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007496 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007497
7498 if (BeginLocInfo.first != EndLocInfo.first)
7499 return;
7500
7501 StringRef Buffer;
7502 bool Invalid = false;
7503 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7504 if (Buffer.empty() || Invalid)
7505 return;
7506
7507 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7508 CXXUnit->getASTContext().getLangOpts(),
7509 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7510 Buffer.end());
7511 Lex.SetCommentRetentionState(true);
7512
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007513 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 // Lex tokens in raw mode until we hit the end of the range, to avoid
7515 // entering #includes or expanding macros.
7516 while (true) {
7517 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007518 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7519 break;
7520 unsigned TokIdx = NextIdx-1;
7521 assert(Tok.getLocation() ==
7522 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007523
7524 reprocess:
7525 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007526 // We have found a preprocessing directive. Annotate the tokens
7527 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007528 //
7529 // FIXME: Some simple tests here could identify macro definitions and
7530 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007531
7532 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007533 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7534 break;
7535
Craig Topper69186e72014-06-08 08:38:04 +00007536 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007537 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007538 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7539 break;
7540
7541 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007542 IdentifierInfo &II =
7543 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007544 SourceLocation MappedTokLoc =
7545 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7546 MI = getMacroInfo(II, MappedTokLoc, TU);
7547 }
7548 }
7549
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007550 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007551 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007552 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7553 finished = true;
7554 break;
7555 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007556 // If we are in a macro definition, check if the token was ever a
7557 // macro name and annotate it if that's the case.
7558 if (MI) {
7559 SourceLocation SaveLoc = Tok.getLocation();
7560 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007561 MacroDefinitionRecord *MacroDef =
7562 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007563 Tok.setLocation(SaveLoc);
7564 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007565 Cursors[NextIdx - 1] =
7566 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007567 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007568 } while (!Tok.isAtStartOfLine());
7569
7570 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7571 assert(TokIdx <= LastIdx);
7572 SourceLocation EndLoc =
7573 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7574 CXCursor Cursor =
7575 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7576
7577 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007578 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007579
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007580 if (finished)
7581 break;
7582 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007583 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007584 }
7585}
7586
7587// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007588static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7589 CXToken *Tokens, unsigned NumTokens,
7590 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007591 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007592 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7593 setThreadBackgroundPriority();
7594
7595 // Determine the region of interest, which contains all of the tokens.
7596 SourceRange RegionOfInterest;
7597 RegionOfInterest.setBegin(
7598 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7599 RegionOfInterest.setEnd(
7600 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7601 Tokens[NumTokens-1])));
7602
Guy Benyei11169dd2012-12-18 14:30:41 +00007603 // Relex the tokens within the source range to look for preprocessing
7604 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007605 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007606
7607 // If begin location points inside a macro argument, set it to the expansion
7608 // location so we can have the full context when annotating semantically.
7609 {
7610 SourceManager &SM = CXXUnit->getSourceManager();
7611 SourceLocation Loc =
7612 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7613 if (Loc.isMacroID())
7614 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7615 }
7616
Guy Benyei11169dd2012-12-18 14:30:41 +00007617 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7618 // Search and mark tokens that are macro argument expansions.
7619 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7620 Tokens, NumTokens);
7621 CursorVisitor MacroArgMarker(TU,
7622 MarkMacroArgTokensVisitorDelegate, &Visitor,
7623 /*VisitPreprocessorLast=*/true,
7624 /*VisitIncludedEntities=*/false,
7625 RegionOfInterest);
7626 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7627 }
7628
7629 // Annotate all of the source locations in the region of interest that map to
7630 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007631 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007632
7633 // FIXME: We use a ridiculous stack size here because the data-recursion
7634 // algorithm uses a large stack frame than the non-data recursive version,
7635 // and AnnotationTokensWorker currently transforms the data-recursion
7636 // algorithm back into a traditional recursion by explicitly calling
7637 // VisitChildren(). We will need to remove this explicit recursive call.
7638 W.AnnotateTokens();
7639
7640 // If we ran into any entities that involve context-sensitive keywords,
7641 // take another pass through the tokens to mark them as such.
7642 if (W.hasContextSensitiveKeywords()) {
7643 for (unsigned I = 0; I != NumTokens; ++I) {
7644 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7645 continue;
7646
7647 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7648 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007649 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007650 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7651 if (Property->getPropertyAttributesAsWritten() != 0 &&
7652 llvm::StringSwitch<bool>(II->getName())
7653 .Case("readonly", true)
7654 .Case("assign", true)
7655 .Case("unsafe_unretained", true)
7656 .Case("readwrite", true)
7657 .Case("retain", true)
7658 .Case("copy", true)
7659 .Case("nonatomic", true)
7660 .Case("atomic", true)
7661 .Case("getter", true)
7662 .Case("setter", true)
7663 .Case("strong", true)
7664 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007665 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 .Default(false))
7667 Tokens[I].int_data[0] = CXToken_Keyword;
7668 }
7669 continue;
7670 }
7671
7672 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7673 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7674 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7675 if (llvm::StringSwitch<bool>(II->getName())
7676 .Case("in", true)
7677 .Case("out", true)
7678 .Case("inout", true)
7679 .Case("oneway", true)
7680 .Case("bycopy", true)
7681 .Case("byref", true)
7682 .Default(false))
7683 Tokens[I].int_data[0] = CXToken_Keyword;
7684 continue;
7685 }
7686
7687 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7688 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7689 Tokens[I].int_data[0] = CXToken_Keyword;
7690 continue;
7691 }
7692 }
7693 }
7694}
7695
Guy Benyei11169dd2012-12-18 14:30:41 +00007696void clang_annotateTokens(CXTranslationUnit TU,
7697 CXToken *Tokens, unsigned NumTokens,
7698 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007699 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007700 LOG_BAD_TU(TU);
7701 return;
7702 }
7703 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007704 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007705 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007706 }
7707
7708 LOG_FUNC_SECTION {
7709 *Log << TU << ' ';
7710 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7711 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7712 *Log << clang_getRange(bloc, eloc);
7713 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007714
7715 // Any token we don't specifically annotate will have a NULL cursor.
7716 CXCursor C = clang_getNullCursor();
7717 for (unsigned I = 0; I != NumTokens; ++I)
7718 Cursors[I] = C;
7719
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007720 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 if (!CXXUnit)
7722 return;
7723
7724 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007725
7726 auto AnnotateTokensImpl = [=]() {
7727 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7728 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007729 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007730 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007731 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7732 }
7733}
7734
Guy Benyei11169dd2012-12-18 14:30:41 +00007735//===----------------------------------------------------------------------===//
7736// Operations for querying linkage of a cursor.
7737//===----------------------------------------------------------------------===//
7738
Guy Benyei11169dd2012-12-18 14:30:41 +00007739CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7740 if (!clang_isDeclaration(cursor.kind))
7741 return CXLinkage_Invalid;
7742
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007743 const Decl *D = cxcursor::getCursorDecl(cursor);
7744 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007745 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007746 case NoLinkage:
7747 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007748 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007749 case InternalLinkage: return CXLinkage_Internal;
7750 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007751 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007752 case ExternalLinkage: return CXLinkage_External;
7753 };
7754
7755 return CXLinkage_Invalid;
7756}
Guy Benyei11169dd2012-12-18 14:30:41 +00007757
7758//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007759// Operations for querying visibility of a cursor.
7760//===----------------------------------------------------------------------===//
7761
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007762CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7763 if (!clang_isDeclaration(cursor.kind))
7764 return CXVisibility_Invalid;
7765
7766 const Decl *D = cxcursor::getCursorDecl(cursor);
7767 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7768 switch (ND->getVisibility()) {
7769 case HiddenVisibility: return CXVisibility_Hidden;
7770 case ProtectedVisibility: return CXVisibility_Protected;
7771 case DefaultVisibility: return CXVisibility_Default;
7772 };
7773
7774 return CXVisibility_Invalid;
7775}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007776
7777//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007778// Operations for querying language of a cursor.
7779//===----------------------------------------------------------------------===//
7780
7781static CXLanguageKind getDeclLanguage(const Decl *D) {
7782 if (!D)
7783 return CXLanguage_C;
7784
7785 switch (D->getKind()) {
7786 default:
7787 break;
7788 case Decl::ImplicitParam:
7789 case Decl::ObjCAtDefsField:
7790 case Decl::ObjCCategory:
7791 case Decl::ObjCCategoryImpl:
7792 case Decl::ObjCCompatibleAlias:
7793 case Decl::ObjCImplementation:
7794 case Decl::ObjCInterface:
7795 case Decl::ObjCIvar:
7796 case Decl::ObjCMethod:
7797 case Decl::ObjCProperty:
7798 case Decl::ObjCPropertyImpl:
7799 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007800 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007801 return CXLanguage_ObjC;
7802 case Decl::CXXConstructor:
7803 case Decl::CXXConversion:
7804 case Decl::CXXDestructor:
7805 case Decl::CXXMethod:
7806 case Decl::CXXRecord:
7807 case Decl::ClassTemplate:
7808 case Decl::ClassTemplatePartialSpecialization:
7809 case Decl::ClassTemplateSpecialization:
7810 case Decl::Friend:
7811 case Decl::FriendTemplate:
7812 case Decl::FunctionTemplate:
7813 case Decl::LinkageSpec:
7814 case Decl::Namespace:
7815 case Decl::NamespaceAlias:
7816 case Decl::NonTypeTemplateParm:
7817 case Decl::StaticAssert:
7818 case Decl::TemplateTemplateParm:
7819 case Decl::TemplateTypeParm:
7820 case Decl::UnresolvedUsingTypename:
7821 case Decl::UnresolvedUsingValue:
7822 case Decl::Using:
7823 case Decl::UsingDirective:
7824 case Decl::UsingShadow:
7825 return CXLanguage_CPlusPlus;
7826 }
7827
7828 return CXLanguage_C;
7829}
7830
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007831static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7832 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007833 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007834
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007835 switch (D->getAvailability()) {
7836 case AR_Available:
7837 case AR_NotYetIntroduced:
7838 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007839 return getCursorAvailabilityForDecl(
7840 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007841 return CXAvailability_Available;
7842
7843 case AR_Deprecated:
7844 return CXAvailability_Deprecated;
7845
7846 case AR_Unavailable:
7847 return CXAvailability_NotAvailable;
7848 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007849
7850 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007851}
7852
Guy Benyei11169dd2012-12-18 14:30:41 +00007853enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7854 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007855 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7856 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007857
7858 return CXAvailability_Available;
7859}
7860
7861static CXVersion convertVersion(VersionTuple In) {
7862 CXVersion Out = { -1, -1, -1 };
7863 if (In.empty())
7864 return Out;
7865
7866 Out.Major = In.getMajor();
7867
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007868 Optional<unsigned> Minor = In.getMinor();
7869 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007870 Out.Minor = *Minor;
7871 else
7872 return Out;
7873
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007874 Optional<unsigned> Subminor = In.getSubminor();
7875 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 Out.Subminor = *Subminor;
7877
7878 return Out;
7879}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007880
Alex Lorenz1345ea22017-06-12 19:06:30 +00007881static void getCursorPlatformAvailabilityForDecl(
7882 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7883 int *always_unavailable, CXString *unavailable_message,
7884 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007885 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007886 for (auto A : D->attrs()) {
7887 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007888 HadAvailAttr = true;
7889 if (always_deprecated)
7890 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007891 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007892 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007893 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007894 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007895 continue;
7896 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007897
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007898 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007899 HadAvailAttr = true;
7900 if (always_unavailable)
7901 *always_unavailable = 1;
7902 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007903 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007904 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7905 }
7906 continue;
7907 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007908
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007909 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007910 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007911 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007912 }
7913 }
7914
7915 if (!HadAvailAttr)
7916 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7917 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007918 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7919 deprecated_message, always_unavailable, unavailable_message,
7920 AvailabilityAttrs);
7921
7922 if (AvailabilityAttrs.empty())
7923 return;
7924
Fangrui Song55fab262018-09-26 22:16:28 +00007925 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007926 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7927 return LHS->getPlatform()->getName() <
7928 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007929 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007930 ASTContext &Ctx = D->getASTContext();
7931 auto It = std::unique(
7932 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7933 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7934 if (LHS->getPlatform() != RHS->getPlatform())
7935 return false;
7936
7937 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7938 LHS->getDeprecated() == RHS->getDeprecated() &&
7939 LHS->getObsoleted() == RHS->getObsoleted() &&
7940 LHS->getMessage() == RHS->getMessage() &&
7941 LHS->getReplacement() == RHS->getReplacement())
7942 return true;
7943
7944 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7945 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7946 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7947 return false;
7948
7949 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7950 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7951
7952 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7953 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7954 if (LHS->getMessage().empty())
7955 LHS->setMessage(Ctx, RHS->getMessage());
7956 if (LHS->getReplacement().empty())
7957 LHS->setReplacement(Ctx, RHS->getReplacement());
7958 }
7959
7960 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7961 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7962 if (LHS->getMessage().empty())
7963 LHS->setMessage(Ctx, RHS->getMessage());
7964 if (LHS->getReplacement().empty())
7965 LHS->setReplacement(Ctx, RHS->getReplacement());
7966 }
7967
7968 return true;
7969 });
7970 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007971}
7972
Alex Lorenz1345ea22017-06-12 19:06:30 +00007973int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 CXString *deprecated_message,
7975 int *always_unavailable,
7976 CXString *unavailable_message,
7977 CXPlatformAvailability *availability,
7978 int availability_size) {
7979 if (always_deprecated)
7980 *always_deprecated = 0;
7981 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007982 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007983 if (always_unavailable)
7984 *always_unavailable = 0;
7985 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007986 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007987
Guy Benyei11169dd2012-12-18 14:30:41 +00007988 if (!clang_isDeclaration(cursor.kind))
7989 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007990
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007991 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007992 if (!D)
7993 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007994
Alex Lorenz1345ea22017-06-12 19:06:30 +00007995 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7996 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7997 always_unavailable, unavailable_message,
7998 AvailabilityAttrs);
7999 for (const auto &Avail :
8000 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
8001 .take_front(availability_size))) {
8002 availability[Avail.index()].Platform =
8003 cxstring::createDup(Avail.value()->getPlatform()->getName());
8004 availability[Avail.index()].Introduced =
8005 convertVersion(Avail.value()->getIntroduced());
8006 availability[Avail.index()].Deprecated =
8007 convertVersion(Avail.value()->getDeprecated());
8008 availability[Avail.index()].Obsoleted =
8009 convertVersion(Avail.value()->getObsoleted());
8010 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
8011 availability[Avail.index()].Message =
8012 cxstring::createDup(Avail.value()->getMessage());
8013 }
8014
8015 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008016}
Alex Lorenz1345ea22017-06-12 19:06:30 +00008017
Guy Benyei11169dd2012-12-18 14:30:41 +00008018void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
8019 clang_disposeString(availability->Platform);
8020 clang_disposeString(availability->Message);
8021}
8022
8023CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
8024 if (clang_isDeclaration(cursor.kind))
8025 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
8026
8027 return CXLanguage_Invalid;
8028}
8029
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00008030CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
8031 const Decl *D = cxcursor::getCursorDecl(cursor);
8032 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8033 switch (VD->getTLSKind()) {
8034 case VarDecl::TLS_None:
8035 return CXTLS_None;
8036 case VarDecl::TLS_Dynamic:
8037 return CXTLS_Dynamic;
8038 case VarDecl::TLS_Static:
8039 return CXTLS_Static;
8040 }
8041 }
8042
8043 return CXTLS_None;
8044}
8045
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008046 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008047 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008049static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008050 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008051 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008052
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008053 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008054 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8055 return FunTmpl;
8056
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008057 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008058 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8059 return ClassTmpl;
8060
8061 return D;
8062}
8063
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008064
8065enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8066 StorageClass sc = SC_None;
8067 const Decl *D = getCursorDecl(C);
8068 if (D) {
8069 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8070 sc = FD->getStorageClass();
8071 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8072 sc = VD->getStorageClass();
8073 } else {
8074 return CX_SC_Invalid;
8075 }
8076 } else {
8077 return CX_SC_Invalid;
8078 }
8079 switch (sc) {
8080 case SC_None:
8081 return CX_SC_None;
8082 case SC_Extern:
8083 return CX_SC_Extern;
8084 case SC_Static:
8085 return CX_SC_Static;
8086 case SC_PrivateExtern:
8087 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008088 case SC_Auto:
8089 return CX_SC_Auto;
8090 case SC_Register:
8091 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008092 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008093 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008094}
8095
Guy Benyei11169dd2012-12-18 14:30:41 +00008096CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8097 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008098 if (const Decl *D = getCursorDecl(cursor)) {
8099 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008100 if (!DC)
8101 return clang_getNullCursor();
8102
8103 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8104 getCursorTU(cursor));
8105 }
8106 }
8107
8108 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008109 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008110 return MakeCXCursor(D, getCursorTU(cursor));
8111 }
8112
8113 return clang_getNullCursor();
8114}
8115
8116CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8117 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008118 if (const Decl *D = getCursorDecl(cursor)) {
8119 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008120 if (!DC)
8121 return clang_getNullCursor();
8122
8123 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8124 getCursorTU(cursor));
8125 }
8126 }
8127
8128 // FIXME: Note that we can't easily compute the lexical context of a
8129 // statement or expression, so we return nothing.
8130 return clang_getNullCursor();
8131}
8132
8133CXFile clang_getIncludedFile(CXCursor cursor) {
8134 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008135 return nullptr;
8136
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008137 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008138 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008139}
8140
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008141unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8142 if (C.kind != CXCursor_ObjCPropertyDecl)
8143 return CXObjCPropertyAttr_noattr;
8144
8145 unsigned Result = CXObjCPropertyAttr_noattr;
8146 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8147 ObjCPropertyDecl::PropertyAttributeKind Attr =
8148 PD->getPropertyAttributesAsWritten();
8149
8150#define SET_CXOBJCPROP_ATTR(A) \
8151 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8152 Result |= CXObjCPropertyAttr_##A
8153 SET_CXOBJCPROP_ATTR(readonly);
8154 SET_CXOBJCPROP_ATTR(getter);
8155 SET_CXOBJCPROP_ATTR(assign);
8156 SET_CXOBJCPROP_ATTR(readwrite);
8157 SET_CXOBJCPROP_ATTR(retain);
8158 SET_CXOBJCPROP_ATTR(copy);
8159 SET_CXOBJCPROP_ATTR(nonatomic);
8160 SET_CXOBJCPROP_ATTR(setter);
8161 SET_CXOBJCPROP_ATTR(atomic);
8162 SET_CXOBJCPROP_ATTR(weak);
8163 SET_CXOBJCPROP_ATTR(strong);
8164 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008165 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008166#undef SET_CXOBJCPROP_ATTR
8167
8168 return Result;
8169}
8170
Michael Wu6e88f532018-08-03 05:38:29 +00008171CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8172 if (C.kind != CXCursor_ObjCPropertyDecl)
8173 return cxstring::createNull();
8174
8175 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8176 Selector sel = PD->getGetterName();
8177 if (sel.isNull())
8178 return cxstring::createNull();
8179
8180 return cxstring::createDup(sel.getAsString());
8181}
8182
8183CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8184 if (C.kind != CXCursor_ObjCPropertyDecl)
8185 return cxstring::createNull();
8186
8187 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8188 Selector sel = PD->getSetterName();
8189 if (sel.isNull())
8190 return cxstring::createNull();
8191
8192 return cxstring::createDup(sel.getAsString());
8193}
8194
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008195unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8196 if (!clang_isDeclaration(C.kind))
8197 return CXObjCDeclQualifier_None;
8198
8199 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8200 const Decl *D = getCursorDecl(C);
8201 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8202 QT = MD->getObjCDeclQualifier();
8203 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8204 QT = PD->getObjCDeclQualifier();
8205 if (QT == Decl::OBJC_TQ_None)
8206 return CXObjCDeclQualifier_None;
8207
8208 unsigned Result = CXObjCDeclQualifier_None;
8209 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8210 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8211 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8212 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8213 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8214 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8215
8216 return Result;
8217}
8218
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008219unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8220 if (!clang_isDeclaration(C.kind))
8221 return 0;
8222
8223 const Decl *D = getCursorDecl(C);
8224 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8225 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8226 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8227 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8228
8229 return 0;
8230}
8231
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008232unsigned clang_Cursor_isVariadic(CXCursor C) {
8233 if (!clang_isDeclaration(C.kind))
8234 return 0;
8235
8236 const Decl *D = getCursorDecl(C);
8237 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8238 return FD->isVariadic();
8239 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8240 return MD->isVariadic();
8241
8242 return 0;
8243}
8244
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008245unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8246 CXString *language, CXString *definedIn,
8247 unsigned *isGenerated) {
8248 if (!clang_isDeclaration(C.kind))
8249 return 0;
8250
8251 const Decl *D = getCursorDecl(C);
8252
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008253 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008254 if (language)
8255 *language = cxstring::createDup(attr->getLanguage());
8256 if (definedIn)
8257 *definedIn = cxstring::createDup(attr->getDefinedIn());
8258 if (isGenerated)
8259 *isGenerated = attr->getGeneratedDeclaration();
8260 return 1;
8261 }
8262 return 0;
8263}
8264
Guy Benyei11169dd2012-12-18 14:30:41 +00008265CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8266 if (!clang_isDeclaration(C.kind))
8267 return clang_getNullRange();
8268
8269 const Decl *D = getCursorDecl(C);
8270 ASTContext &Context = getCursorContext(C);
8271 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8272 if (!RC)
8273 return clang_getNullRange();
8274
8275 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8276}
8277
8278CXString clang_Cursor_getRawCommentText(CXCursor C) {
8279 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008280 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008281
8282 const Decl *D = getCursorDecl(C);
8283 ASTContext &Context = getCursorContext(C);
8284 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8285 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8286 StringRef();
8287
8288 // Don't duplicate the string because RawText points directly into source
8289 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008290 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008291}
8292
8293CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8294 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008295 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008296
8297 const Decl *D = getCursorDecl(C);
8298 const ASTContext &Context = getCursorContext(C);
8299 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8300
8301 if (RC) {
8302 StringRef BriefText = RC->getBriefText(Context);
8303
8304 // Don't duplicate the string because RawComment ensures that this memory
8305 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008306 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008307 }
8308
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008309 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008310}
8311
Guy Benyei11169dd2012-12-18 14:30:41 +00008312CXModule clang_Cursor_getModule(CXCursor C) {
8313 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008314 if (const ImportDecl *ImportD =
8315 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008316 return ImportD->getImportedModule();
8317 }
8318
Craig Topper69186e72014-06-08 08:38:04 +00008319 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008320}
8321
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008322CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8323 if (isNotUsableTU(TU)) {
8324 LOG_BAD_TU(TU);
8325 return nullptr;
8326 }
8327 if (!File)
8328 return nullptr;
8329 FileEntry *FE = static_cast<FileEntry *>(File);
8330
8331 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8332 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8333 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8334
Richard Smithfeb54b62014-10-23 02:01:19 +00008335 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008336}
8337
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008338CXFile clang_Module_getASTFile(CXModule CXMod) {
8339 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008340 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008341 Module *Mod = static_cast<Module*>(CXMod);
8342 return const_cast<FileEntry *>(Mod->getASTFile());
8343}
8344
Guy Benyei11169dd2012-12-18 14:30:41 +00008345CXModule clang_Module_getParent(CXModule CXMod) {
8346 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008347 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008348 Module *Mod = static_cast<Module*>(CXMod);
8349 return Mod->Parent;
8350}
8351
8352CXString clang_Module_getName(CXModule CXMod) {
8353 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008354 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008355 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008356 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008357}
8358
8359CXString clang_Module_getFullName(CXModule CXMod) {
8360 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008361 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008362 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008363 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008364}
8365
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008366int clang_Module_isSystem(CXModule CXMod) {
8367 if (!CXMod)
8368 return 0;
8369 Module *Mod = static_cast<Module*>(CXMod);
8370 return Mod->IsSystem;
8371}
8372
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008373unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8374 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008375 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008376 LOG_BAD_TU(TU);
8377 return 0;
8378 }
8379 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008380 return 0;
8381 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008382 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8383 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8384 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008385}
8386
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008387CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8388 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008389 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008390 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008391 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008392 }
8393 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008394 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008395 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008396 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008397
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008398 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8399 if (Index < TopHeaders.size())
8400 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008401
Craig Topper69186e72014-06-08 08:38:04 +00008402 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008403}
8404
Guy Benyei11169dd2012-12-18 14:30:41 +00008405//===----------------------------------------------------------------------===//
8406// C++ AST instrospection.
8407//===----------------------------------------------------------------------===//
8408
Jonathan Coe29565352016-04-27 12:48:25 +00008409unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8410 if (!clang_isDeclaration(C.kind))
8411 return 0;
8412
8413 const Decl *D = cxcursor::getCursorDecl(C);
8414 const CXXConstructorDecl *Constructor =
8415 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8416 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8417}
8418
8419unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8420 if (!clang_isDeclaration(C.kind))
8421 return 0;
8422
8423 const Decl *D = cxcursor::getCursorDecl(C);
8424 const CXXConstructorDecl *Constructor =
8425 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8426 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8427}
8428
8429unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8430 if (!clang_isDeclaration(C.kind))
8431 return 0;
8432
8433 const Decl *D = cxcursor::getCursorDecl(C);
8434 const CXXConstructorDecl *Constructor =
8435 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8436 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8437}
8438
8439unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8440 if (!clang_isDeclaration(C.kind))
8441 return 0;
8442
8443 const Decl *D = cxcursor::getCursorDecl(C);
8444 const CXXConstructorDecl *Constructor =
8445 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8446 // Passing 'false' excludes constructors marked 'explicit'.
8447 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8448}
8449
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008450unsigned clang_CXXField_isMutable(CXCursor C) {
8451 if (!clang_isDeclaration(C.kind))
8452 return 0;
8453
8454 if (const auto D = cxcursor::getCursorDecl(C))
8455 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8456 return FD->isMutable() ? 1 : 0;
8457 return 0;
8458}
8459
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008460unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8461 if (!clang_isDeclaration(C.kind))
8462 return 0;
8463
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008464 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008465 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008466 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008467 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8468}
8469
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008470unsigned clang_CXXMethod_isConst(CXCursor C) {
8471 if (!clang_isDeclaration(C.kind))
8472 return 0;
8473
8474 const Decl *D = cxcursor::getCursorDecl(C);
8475 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008476 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008477 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008478}
8479
Jonathan Coe29565352016-04-27 12:48:25 +00008480unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8481 if (!clang_isDeclaration(C.kind))
8482 return 0;
8483
8484 const Decl *D = cxcursor::getCursorDecl(C);
8485 const CXXMethodDecl *Method =
8486 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8487 return (Method && Method->isDefaulted()) ? 1 : 0;
8488}
8489
Guy Benyei11169dd2012-12-18 14:30:41 +00008490unsigned clang_CXXMethod_isStatic(CXCursor C) {
8491 if (!clang_isDeclaration(C.kind))
8492 return 0;
8493
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008494 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008495 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008496 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008497 return (Method && Method->isStatic()) ? 1 : 0;
8498}
8499
8500unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8501 if (!clang_isDeclaration(C.kind))
8502 return 0;
8503
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008504 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008505 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008506 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008507 return (Method && Method->isVirtual()) ? 1 : 0;
8508}
Guy Benyei11169dd2012-12-18 14:30:41 +00008509
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008510unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8511 if (!clang_isDeclaration(C.kind))
8512 return 0;
8513
8514 const auto *D = cxcursor::getCursorDecl(C);
8515 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8516 if (RD)
8517 RD = RD->getDefinition();
8518 return (RD && RD->isAbstract()) ? 1 : 0;
8519}
8520
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008521unsigned clang_EnumDecl_isScoped(CXCursor C) {
8522 if (!clang_isDeclaration(C.kind))
8523 return 0;
8524
8525 const Decl *D = cxcursor::getCursorDecl(C);
8526 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8527 return (Enum && Enum->isScoped()) ? 1 : 0;
8528}
8529
Guy Benyei11169dd2012-12-18 14:30:41 +00008530//===----------------------------------------------------------------------===//
8531// Attribute introspection.
8532//===----------------------------------------------------------------------===//
8533
Guy Benyei11169dd2012-12-18 14:30:41 +00008534CXType clang_getIBOutletCollectionType(CXCursor C) {
8535 if (C.kind != CXCursor_IBOutletCollectionAttr)
8536 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8537
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008538 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008539 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8540
8541 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8542}
Guy Benyei11169dd2012-12-18 14:30:41 +00008543
8544//===----------------------------------------------------------------------===//
8545// Inspecting memory usage.
8546//===----------------------------------------------------------------------===//
8547
8548typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8549
8550static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8551 enum CXTUResourceUsageKind k,
8552 unsigned long amount) {
8553 CXTUResourceUsageEntry entry = { k, amount };
8554 entries.push_back(entry);
8555}
8556
Guy Benyei11169dd2012-12-18 14:30:41 +00008557const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8558 const char *str = "";
8559 switch (kind) {
8560 case CXTUResourceUsage_AST:
8561 str = "ASTContext: expressions, declarations, and types";
8562 break;
8563 case CXTUResourceUsage_Identifiers:
8564 str = "ASTContext: identifiers";
8565 break;
8566 case CXTUResourceUsage_Selectors:
8567 str = "ASTContext: selectors";
8568 break;
8569 case CXTUResourceUsage_GlobalCompletionResults:
8570 str = "Code completion: cached global results";
8571 break;
8572 case CXTUResourceUsage_SourceManagerContentCache:
8573 str = "SourceManager: content cache allocator";
8574 break;
8575 case CXTUResourceUsage_AST_SideTables:
8576 str = "ASTContext: side tables";
8577 break;
8578 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8579 str = "SourceManager: malloc'ed memory buffers";
8580 break;
8581 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8582 str = "SourceManager: mmap'ed memory buffers";
8583 break;
8584 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8585 str = "ExternalASTSource: malloc'ed memory buffers";
8586 break;
8587 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8588 str = "ExternalASTSource: mmap'ed memory buffers";
8589 break;
8590 case CXTUResourceUsage_Preprocessor:
8591 str = "Preprocessor: malloc'ed memory";
8592 break;
8593 case CXTUResourceUsage_PreprocessingRecord:
8594 str = "Preprocessor: PreprocessingRecord";
8595 break;
8596 case CXTUResourceUsage_SourceManager_DataStructures:
8597 str = "SourceManager: data structures and tables";
8598 break;
8599 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8600 str = "Preprocessor: header search tables";
8601 break;
8602 }
8603 return str;
8604}
8605
8606CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008607 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008608 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008609 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008610 return usage;
8611 }
8612
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008613 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008614 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008615 ASTContext &astContext = astUnit->getASTContext();
8616
8617 // How much memory is used by AST nodes and types?
8618 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8619 (unsigned long) astContext.getASTAllocatedMemory());
8620
8621 // How much memory is used by identifiers?
8622 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8623 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8624
8625 // How much memory is used for selectors?
8626 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8627 (unsigned long) astContext.Selectors.getTotalMemory());
8628
8629 // How much memory is used by ASTContext's side tables?
8630 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8631 (unsigned long) astContext.getSideTableAllocatedMemory());
8632
8633 // How much memory is used for caching global code completion results?
8634 unsigned long completionBytes = 0;
8635 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008636 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008637 completionBytes = completionAllocator->getTotalMemory();
8638 }
8639 createCXTUResourceUsageEntry(*entries,
8640 CXTUResourceUsage_GlobalCompletionResults,
8641 completionBytes);
8642
8643 // How much memory is being used by SourceManager's content cache?
8644 createCXTUResourceUsageEntry(*entries,
8645 CXTUResourceUsage_SourceManagerContentCache,
8646 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8647
8648 // How much memory is being used by the MemoryBuffer's in SourceManager?
8649 const SourceManager::MemoryBufferSizes &srcBufs =
8650 astUnit->getSourceManager().getMemoryBufferSizes();
8651
8652 createCXTUResourceUsageEntry(*entries,
8653 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8654 (unsigned long) srcBufs.malloc_bytes);
8655 createCXTUResourceUsageEntry(*entries,
8656 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8657 (unsigned long) srcBufs.mmap_bytes);
8658 createCXTUResourceUsageEntry(*entries,
8659 CXTUResourceUsage_SourceManager_DataStructures,
8660 (unsigned long) astContext.getSourceManager()
8661 .getDataStructureSizes());
8662
8663 // How much memory is being used by the ExternalASTSource?
8664 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8665 const ExternalASTSource::MemoryBufferSizes &sizes =
8666 esrc->getMemoryBufferSizes();
8667
8668 createCXTUResourceUsageEntry(*entries,
8669 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8670 (unsigned long) sizes.malloc_bytes);
8671 createCXTUResourceUsageEntry(*entries,
8672 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8673 (unsigned long) sizes.mmap_bytes);
8674 }
8675
8676 // How much memory is being used by the Preprocessor?
8677 Preprocessor &pp = astUnit->getPreprocessor();
8678 createCXTUResourceUsageEntry(*entries,
8679 CXTUResourceUsage_Preprocessor,
8680 pp.getTotalMemory());
8681
8682 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8683 createCXTUResourceUsageEntry(*entries,
8684 CXTUResourceUsage_PreprocessingRecord,
8685 pRec->getTotalMemory());
8686 }
8687
8688 createCXTUResourceUsageEntry(*entries,
8689 CXTUResourceUsage_Preprocessor_HeaderSearch,
8690 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008691
Guy Benyei11169dd2012-12-18 14:30:41 +00008692 CXTUResourceUsage usage = { (void*) entries.get(),
8693 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008694 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008695 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008696 return usage;
8697}
8698
8699void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8700 if (usage.data)
8701 delete (MemUsageEntries*) usage.data;
8702}
8703
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008704CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8705 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008706 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008707 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008708
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008709 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008710 LOG_BAD_TU(TU);
8711 return skipped;
8712 }
8713
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008714 if (!file)
8715 return skipped;
8716
8717 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8718 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8719 if (!ppRec)
8720 return skipped;
8721
8722 ASTContext &Ctx = astUnit->getASTContext();
8723 SourceManager &sm = Ctx.getSourceManager();
8724 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8725 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008726 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008727
8728 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8729 std::vector<SourceRange> wantedRanges;
8730 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8731 i != ei; ++i) {
8732 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8733 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008734 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8735 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008736 }
8737
8738 skipped->count = wantedRanges.size();
8739 skipped->ranges = new CXSourceRange[skipped->count];
8740 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8741 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8742
8743 return skipped;
8744}
8745
Cameron Desrochersd8091282016-08-18 15:43:55 +00008746CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8747 CXSourceRangeList *skipped = new CXSourceRangeList;
8748 skipped->count = 0;
8749 skipped->ranges = nullptr;
8750
8751 if (isNotUsableTU(TU)) {
8752 LOG_BAD_TU(TU);
8753 return skipped;
8754 }
8755
8756 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8757 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8758 if (!ppRec)
8759 return skipped;
8760
8761 ASTContext &Ctx = astUnit->getASTContext();
8762
8763 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8764
8765 skipped->count = SkippedRanges.size();
8766 skipped->ranges = new CXSourceRange[skipped->count];
8767 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8768 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8769
8770 return skipped;
8771}
8772
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008773void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8774 if (ranges) {
8775 delete[] ranges->ranges;
8776 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008777 }
8778}
8779
Guy Benyei11169dd2012-12-18 14:30:41 +00008780void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8781 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8782 for (unsigned I = 0; I != Usage.numEntries; ++I)
8783 fprintf(stderr, " %s: %lu\n",
8784 clang_getTUResourceUsageName(Usage.entries[I].kind),
8785 Usage.entries[I].amount);
8786
8787 clang_disposeCXTUResourceUsage(Usage);
8788}
8789
8790//===----------------------------------------------------------------------===//
8791// Misc. utility functions.
8792//===----------------------------------------------------------------------===//
8793
Richard Smith0a7b2972018-07-03 21:34:13 +00008794/// Default to using our desired 8 MB stack size on "safety" threads.
8795static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008796
8797namespace clang {
8798
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008799bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008800 unsigned Size) {
8801 if (!Size)
8802 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008803 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008804 return CRC.RunSafelyOnThread(Fn, Size);
8805 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008806}
8807
8808unsigned GetSafetyThreadStackSize() {
8809 return SafetyStackThreadSize;
8810}
8811
8812void SetSafetyThreadStackSize(unsigned Value) {
8813 SafetyStackThreadSize = Value;
8814}
8815
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008816}
Guy Benyei11169dd2012-12-18 14:30:41 +00008817
8818void clang::setThreadBackgroundPriority() {
8819 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8820 return;
8821
Nico Weber18cfd9f2019-04-21 19:18:41 +00008822#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008823 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008824#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008825}
8826
8827void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8828 if (!Unit)
8829 return;
8830
8831 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8832 DEnd = Unit->stored_diag_end();
8833 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008834 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008835 CXString Msg = clang_formatDiagnostic(&Diag,
8836 clang_defaultDiagnosticDisplayOptions());
8837 fprintf(stderr, "%s\n", clang_getCString(Msg));
8838 clang_disposeString(Msg);
8839 }
Nico Weber1865df42018-04-27 19:11:14 +00008840#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008841 // On Windows, force a flush, since there may be multiple copies of
8842 // stderr and stdout in the file system, all with different buffers
8843 // but writing to the same device.
8844 fflush(stderr);
8845#endif
8846}
8847
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008848MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8849 SourceLocation MacroDefLoc,
8850 CXTranslationUnit TU){
8851 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008852 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008853 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008854 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008855
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008856 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008857 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008858 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008859 if (MD) {
8860 for (MacroDirective::DefInfo
8861 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8862 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8863 return Def.getMacroInfo();
8864 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008865 }
8866
Craig Topper69186e72014-06-08 08:38:04 +00008867 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008868}
8869
Richard Smith66a81862015-05-04 02:25:31 +00008870const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008871 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008872 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008873 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008874 const IdentifierInfo *II = MacroDef->getName();
8875 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008876 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008877
8878 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8879}
8880
Richard Smith66a81862015-05-04 02:25:31 +00008881MacroDefinitionRecord *
8882cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8883 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008884 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008885 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008886 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008887 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008888
8889 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008890 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008891 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8892 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008893 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008894
8895 // Check that the token is inside the definition and not its argument list.
8896 SourceManager &SM = Unit->getSourceManager();
8897 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008898 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008899 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008900 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008901
8902 Preprocessor &PP = Unit->getPreprocessor();
8903 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8904 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008905 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008906
Alp Toker2d57cea2014-05-17 04:53:25 +00008907 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008908 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008909 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008910
8911 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008912 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008913 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008914
Richard Smith20e883e2015-04-29 23:20:19 +00008915 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008916 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008917 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008918
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008919 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008920}
8921
Richard Smith66a81862015-05-04 02:25:31 +00008922MacroDefinitionRecord *
8923cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8924 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008925 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008926 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008927
8928 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008929 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008930 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008931 Preprocessor &PP = Unit->getPreprocessor();
8932 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008933 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008934 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8935 Token Tok;
8936 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008937 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008938
8939 return checkForMacroInMacroDefinition(MI, Tok, TU);
8940}
8941
Guy Benyei11169dd2012-12-18 14:30:41 +00008942CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008943 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008944}
8945
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008946Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8947 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008948 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008949 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008950 if (Unit->isMainFileAST())
8951 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008952 return *this;
8953 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008954 } else {
8955 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008956 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008957 return *this;
8958}
8959
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008960Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8961 *this << FE->getName();
8962 return *this;
8963}
8964
8965Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8966 CXString cursorName = clang_getCursorDisplayName(cursor);
8967 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8968 clang_disposeString(cursorName);
8969 return *this;
8970}
8971
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008972Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8973 CXFile File;
8974 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008975 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008976 CXString FileName = clang_getFileName(File);
8977 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8978 clang_disposeString(FileName);
8979 return *this;
8980}
8981
8982Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8983 CXSourceLocation BLoc = clang_getRangeStart(range);
8984 CXSourceLocation ELoc = clang_getRangeEnd(range);
8985
8986 CXFile BFile;
8987 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008988 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008989
8990 CXFile EFile;
8991 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008992 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008993
8994 CXString BFileName = clang_getFileName(BFile);
8995 if (BFile == EFile) {
8996 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8997 BLine, BColumn, ELine, EColumn);
8998 } else {
8999 CXString EFileName = clang_getFileName(EFile);
9000 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
9001 BLine, BColumn)
9002 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
9003 ELine, EColumn);
9004 clang_disposeString(EFileName);
9005 }
9006 clang_disposeString(BFileName);
9007 return *this;
9008}
9009
9010Logger &cxindex::Logger::operator<<(CXString Str) {
9011 *this << clang_getCString(Str);
9012 return *this;
9013}
9014
9015Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
9016 LogOS << Fmt;
9017 return *this;
9018}
9019
Benjamin Kramer762bc332019-08-07 14:44:40 +00009020static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00009021
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009022cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00009023 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009024
9025 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
9026
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009027 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009028 OS << "[libclang:" << Name << ':';
9029
Alp Toker1a86ad22014-07-06 06:24:00 +00009030#ifdef USE_DARWIN_THREADS
9031 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009032 mach_port_t tid = pthread_mach_thread_np(pthread_self());
9033 OS << tid << ':';
9034#endif
9035
9036 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
9037 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00009038 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009039
9040 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00009041 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009042 OS << "--------------------------------------------------\n";
9043 }
9044}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00009045
9046#ifdef CLANG_TOOL_EXTRA_BUILD
9047// This anchor is used to force the linker to link the clang-tidy plugin.
9048extern volatile int ClangTidyPluginAnchorSource;
9049static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9050 ClangTidyPluginAnchorSource;
9051
9052// This anchor is used to force the linker to link the clang-include-fixer
9053// plugin.
9054extern volatile int ClangIncludeFixerPluginAnchorSource;
9055static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9056 ClangIncludeFixerPluginAnchorSource;
9057#endif