blob: ada5d7551d731aed8367a538bc6b67e5bba81567 [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) {
760 // Visit the default argument.
761 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
762 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
763 if (Visit(DefArg->getTypeLoc()))
764 return true;
765
766 return false;
767}
768
769bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
770 if (Expr *Init = D->getInitExpr())
771 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
772 return false;
773}
774
775bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000776 unsigned NumParamList = DD->getNumTemplateParameterLists();
777 for (unsigned i = 0; i < NumParamList; i++) {
778 TemplateParameterList* Params = DD->getTemplateParameterList(i);
779 if (VisitTemplateParameters(Params))
780 return true;
781 }
782
Guy Benyei11169dd2012-12-18 14:30:41 +0000783 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
784 if (Visit(TSInfo->getTypeLoc()))
785 return true;
786
787 // Visit the nested-name-specifier, if present.
788 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
789 if (VisitNestedNameSpecifierLoc(QualifierLoc))
790 return true;
791
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000792 return false;
793}
794
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000795static bool HasTrailingReturnType(FunctionDecl *ND) {
796 const QualType Ty = ND->getType();
797 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
798 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
799 return FT->hasTrailingReturn();
800 }
801
802 return false;
803}
804
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000805/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000806static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
807 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000808 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
809}
810
Guy Benyei11169dd2012-12-18 14:30:41 +0000811bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000812 unsigned NumParamList = ND->getNumTemplateParameterLists();
813 for (unsigned i = 0; i < NumParamList; i++) {
814 TemplateParameterList* Params = ND->getTemplateParameterList(i);
815 if (VisitTemplateParameters(Params))
816 return true;
817 }
818
Guy Benyei11169dd2012-12-18 14:30:41 +0000819 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
820 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000821 // written. This requires a bit of work.
822 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
823 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000824 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000825
826 // If we have a function declared directly (without the use of a typedef),
827 // visit just the return type. Otherwise, just visit the function's type
828 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000829 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
830 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000831 (!FTL && Visit(TL)))
832 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000833
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000834 // Visit the nested-name-specifier, if present.
835 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
836 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 return true;
838
839 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000840 if (!isa<CXXDestructorDecl>(ND))
841 if (VisitDeclarationNameInfo(ND->getNameInfo()))
842 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000843
844 // FIXME: Visit explicitly-specified template arguments!
845
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000846 // Visit the function parameters, if we have a function type.
847 if (FTL && VisitFunctionTypeLoc(FTL, true))
848 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000849
850 // Visit the function's trailing return type.
851 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
852 return true;
853
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000854 // FIXME: Attributes?
855 }
856
Guy Benyei11169dd2012-12-18 14:30:41 +0000857 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
858 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
859 // Find the initializers that were written in the source.
860 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000861 for (auto *I : Constructor->inits()) {
862 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 continue;
864
Aaron Ballman0ad78302014-03-13 17:34:31 +0000865 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 }
867
868 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000869 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
870 &CompareCXXCtorInitializers);
871
Guy Benyei11169dd2012-12-18 14:30:41 +0000872 // Visit the initializers in source order
873 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
874 CXXCtorInitializer *Init = WrittenInits[I];
875 if (Init->isAnyMemberInitializer()) {
876 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
877 Init->getMemberLocation(), TU)))
878 return true;
879 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
880 if (Visit(TInfo->getTypeLoc()))
881 return true;
882 }
883
884 // Visit the initializer value.
885 if (Expr *Initializer = Init->getInit())
886 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
887 return true;
888 }
889 }
890
891 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
892 return true;
893 }
894
895 return false;
896}
897
898bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
899 if (VisitDeclaratorDecl(D))
900 return true;
901
902 if (Expr *BitWidth = D->getBitWidth())
903 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
904
Benjamin Kramer99f97592017-11-15 12:20:41 +0000905 if (Expr *Init = D->getInClassInitializer())
906 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
907
Guy Benyei11169dd2012-12-18 14:30:41 +0000908 return false;
909}
910
911bool CursorVisitor::VisitVarDecl(VarDecl *D) {
912 if (VisitDeclaratorDecl(D))
913 return true;
914
915 if (Expr *Init = D->getInit())
916 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
917
918 return false;
919}
920
921bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
922 if (VisitDeclaratorDecl(D))
923 return true;
924
925 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
926 if (Expr *DefArg = D->getDefaultArgument())
927 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
928
929 return false;
930}
931
932bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
933 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
934 // before visiting these template parameters.
935 if (VisitTemplateParameters(D->getTemplateParameters()))
936 return true;
937
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000938 auto* FD = D->getTemplatedDecl();
939 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000940}
941
942bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
943 // FIXME: Visit the "outer" template parameter lists on the TagDecl
944 // before visiting these template parameters.
945 if (VisitTemplateParameters(D->getTemplateParameters()))
946 return true;
947
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000948 auto* CD = D->getTemplatedDecl();
949 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000950}
951
952bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
953 if (VisitTemplateParameters(D->getTemplateParameters()))
954 return true;
955
956 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
957 VisitTemplateArgumentLoc(D->getDefaultArgument()))
958 return true;
959
960 return false;
961}
962
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000963bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
964 // Visit the bound, if it's explicit.
965 if (D->hasExplicitBound()) {
966 if (auto TInfo = D->getTypeSourceInfo()) {
967 if (Visit(TInfo->getTypeLoc()))
968 return true;
969 }
970 }
971
972 return false;
973}
974
Guy Benyei11169dd2012-12-18 14:30:41 +0000975bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000976 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 if (Visit(TSInfo->getTypeLoc()))
978 return true;
979
David Majnemer59f77922016-06-24 04:05:48 +0000980 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000981 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000982 return true;
983 }
984
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000985 return ND->isThisDeclarationADefinition() &&
986 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000987}
988
989template <typename DeclIt>
990static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
991 SourceManager &SM, SourceLocation EndLoc,
992 SmallVectorImpl<Decl *> &Decls) {
993 DeclIt next = *DI_current;
994 while (++next != DE_current) {
995 Decl *D_next = *next;
996 if (!D_next)
997 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000998 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +0000999 if (!L.isValid())
1000 break;
1001 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1002 *DI_current = next;
1003 Decls.push_back(D_next);
1004 continue;
1005 }
1006 break;
1007 }
1008}
1009
Guy Benyei11169dd2012-12-18 14:30:41 +00001010bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1011 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1012 // an @implementation can lexically contain Decls that are not properly
1013 // nested in the AST. When we identify such cases, we need to retrofit
1014 // this nesting here.
1015 if (!DI_current && !FileDI_current)
1016 return VisitDeclContext(D);
1017
1018 // Scan the Decls that immediately come after the container
1019 // in the current DeclContext. If any fall within the
1020 // container's lexical region, stash them into a vector
1021 // for later processing.
1022 SmallVector<Decl *, 24> DeclsInContainer;
1023 SourceLocation EndLoc = D->getSourceRange().getEnd();
1024 SourceManager &SM = AU->getSourceManager();
1025 if (EndLoc.isValid()) {
1026 if (DI_current) {
1027 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1028 DeclsInContainer);
1029 } else {
1030 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1031 DeclsInContainer);
1032 }
1033 }
1034
1035 // The common case.
1036 if (DeclsInContainer.empty())
1037 return VisitDeclContext(D);
1038
1039 // Get all the Decls in the DeclContext, and sort them with the
1040 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001041 for (auto *SubDecl : D->decls()) {
1042 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001043 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001045 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001046 }
1047
1048 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001049 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001050 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001051 SourceLocation L_A = A->getBeginLoc();
1052 SourceLocation L_B = B->getBeginLoc();
1053 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001054 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1055 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001056 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001057
1058 // Now visit the decls.
1059 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1060 E = DeclsInContainer.end(); I != E; ++I) {
1061 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001062 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001063 if (!V.hasValue())
1064 continue;
1065 if (!V.getValue())
1066 return false;
1067 if (Visit(Cursor, true))
1068 return true;
1069 }
1070 return false;
1071}
1072
1073bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1074 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1075 TU)))
1076 return true;
1077
Douglas Gregore9d95f12015-07-07 03:57:35 +00001078 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1079 return true;
1080
Guy Benyei11169dd2012-12-18 14:30:41 +00001081 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1082 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1083 E = ND->protocol_end(); I != E; ++I, ++PL)
1084 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1085 return true;
1086
1087 return VisitObjCContainerDecl(ND);
1088}
1089
1090bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1091 if (!PID->isThisDeclarationADefinition())
1092 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1093
1094 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1095 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1096 E = PID->protocol_end(); I != E; ++I, ++PL)
1097 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1098 return true;
1099
1100 return VisitObjCContainerDecl(PID);
1101}
1102
1103bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1104 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1105 return true;
1106
1107 // FIXME: This implements a workaround with @property declarations also being
1108 // installed in the DeclContext for the @interface. Eventually this code
1109 // should be removed.
1110 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1111 if (!CDecl || !CDecl->IsClassExtension())
1112 return false;
1113
1114 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1115 if (!ID)
1116 return false;
1117
1118 IdentifierInfo *PropertyId = PD->getIdentifier();
1119 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001120 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1121 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001122
1123 if (!prevDecl)
1124 return false;
1125
1126 // Visit synthesized methods since they will be skipped when visiting
1127 // the @interface.
1128 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1129 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1130 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1131 return true;
1132
1133 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1134 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1135 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1136 return true;
1137
1138 return false;
1139}
1140
Douglas Gregore9d95f12015-07-07 03:57:35 +00001141bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1142 if (!typeParamList)
1143 return false;
1144
1145 for (auto *typeParam : *typeParamList) {
1146 // Visit the type parameter.
1147 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1148 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001149 }
1150
1151 return false;
1152}
1153
Guy Benyei11169dd2012-12-18 14:30:41 +00001154bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1155 if (!D->isThisDeclarationADefinition()) {
1156 // Forward declaration is treated like a reference.
1157 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1158 }
1159
Douglas Gregore9d95f12015-07-07 03:57:35 +00001160 // Objective-C type parameters.
1161 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1162 return true;
1163
Guy Benyei11169dd2012-12-18 14:30:41 +00001164 // Issue callbacks for super class.
1165 if (D->getSuperClass() &&
1166 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1167 D->getSuperClassLoc(),
1168 TU)))
1169 return true;
1170
Douglas Gregore9d95f12015-07-07 03:57:35 +00001171 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1172 if (Visit(SuperClassTInfo->getTypeLoc()))
1173 return true;
1174
Guy Benyei11169dd2012-12-18 14:30:41 +00001175 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1176 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1177 E = D->protocol_end(); I != E; ++I, ++PL)
1178 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1179 return true;
1180
1181 return VisitObjCContainerDecl(D);
1182}
1183
1184bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1185 return VisitObjCContainerDecl(D);
1186}
1187
1188bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1189 // 'ID' could be null when dealing with invalid code.
1190 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1191 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1192 return true;
1193
1194 return VisitObjCImplDecl(D);
1195}
1196
1197bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1198#if 0
1199 // Issue callbacks for super class.
1200 // FIXME: No source location information!
1201 if (D->getSuperClass() &&
1202 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1203 D->getSuperClassLoc(),
1204 TU)))
1205 return true;
1206#endif
1207
1208 return VisitObjCImplDecl(D);
1209}
1210
1211bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1212 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1213 if (PD->isIvarNameSpecified())
1214 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1215
1216 return false;
1217}
1218
1219bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1220 return VisitDeclContext(D);
1221}
1222
1223bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1224 // Visit nested-name-specifier.
1225 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1226 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1227 return true;
1228
1229 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1230 D->getTargetNameLoc(), TU));
1231}
1232
1233bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1234 // Visit nested-name-specifier.
1235 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1236 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1237 return true;
1238 }
1239
1240 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1241 return true;
1242
1243 return VisitDeclarationNameInfo(D->getNameInfo());
1244}
1245
1246bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1247 // Visit nested-name-specifier.
1248 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1249 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1250 return true;
1251
1252 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1253 D->getIdentLocation(), TU));
1254}
1255
1256bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1257 // Visit nested-name-specifier.
1258 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1259 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1260 return true;
1261 }
1262
1263 return VisitDeclarationNameInfo(D->getNameInfo());
1264}
1265
1266bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1267 UnresolvedUsingTypenameDecl *D) {
1268 // Visit nested-name-specifier.
1269 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1270 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1271 return true;
1272
1273 return false;
1274}
1275
Olivier Goffart81978012016-06-09 16:15:55 +00001276bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1277 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1278 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001279 if (StringLiteral *Message = D->getMessage())
1280 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1281 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001282 return false;
1283}
1284
Olivier Goffartd211c642016-11-04 06:29:27 +00001285bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1286 if (NamedDecl *FriendD = D->getFriendDecl()) {
1287 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1288 return true;
1289 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1290 if (Visit(TI->getTypeLoc()))
1291 return true;
1292 }
1293 return false;
1294}
1295
Guy Benyei11169dd2012-12-18 14:30:41 +00001296bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1297 switch (Name.getName().getNameKind()) {
1298 case clang::DeclarationName::Identifier:
1299 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001300 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001301 case clang::DeclarationName::CXXOperatorName:
1302 case clang::DeclarationName::CXXUsingDirective:
1303 return false;
Richard Smith35845152017-02-07 01:37:30 +00001304
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 case clang::DeclarationName::CXXConstructorName:
1306 case clang::DeclarationName::CXXDestructorName:
1307 case clang::DeclarationName::CXXConversionFunctionName:
1308 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1309 return Visit(TSInfo->getTypeLoc());
1310 return false;
1311
1312 case clang::DeclarationName::ObjCZeroArgSelector:
1313 case clang::DeclarationName::ObjCOneArgSelector:
1314 case clang::DeclarationName::ObjCMultiArgSelector:
1315 // FIXME: Per-identifier location info?
1316 return false;
1317 }
1318
1319 llvm_unreachable("Invalid DeclarationName::Kind!");
1320}
1321
1322bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1323 SourceRange Range) {
1324 // FIXME: This whole routine is a hack to work around the lack of proper
1325 // source information in nested-name-specifiers (PR5791). Since we do have
1326 // a beginning source location, we can visit the first component of the
1327 // nested-name-specifier, if it's a single-token component.
1328 if (!NNS)
1329 return false;
1330
1331 // Get the first component in the nested-name-specifier.
1332 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1333 NNS = Prefix;
1334
1335 switch (NNS->getKind()) {
1336 case NestedNameSpecifier::Namespace:
1337 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1338 TU));
1339
1340 case NestedNameSpecifier::NamespaceAlias:
1341 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1342 Range.getBegin(), TU));
1343
1344 case NestedNameSpecifier::TypeSpec: {
1345 // If the type has a form where we know that the beginning of the source
1346 // range matches up with a reference cursor. Visit the appropriate reference
1347 // cursor.
1348 const Type *T = NNS->getAsType();
1349 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1350 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1351 if (const TagType *Tag = dyn_cast<TagType>(T))
1352 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1353 if (const TemplateSpecializationType *TST
1354 = dyn_cast<TemplateSpecializationType>(T))
1355 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1356 break;
1357 }
1358
1359 case NestedNameSpecifier::TypeSpecWithTemplate:
1360 case NestedNameSpecifier::Global:
1361 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001362 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001363 break;
1364 }
1365
1366 return false;
1367}
1368
1369bool
1370CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1371 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1372 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1373 Qualifiers.push_back(Qualifier);
1374
1375 while (!Qualifiers.empty()) {
1376 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1377 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1378 switch (NNS->getKind()) {
1379 case NestedNameSpecifier::Namespace:
1380 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1381 Q.getLocalBeginLoc(),
1382 TU)))
1383 return true;
1384
1385 break;
1386
1387 case NestedNameSpecifier::NamespaceAlias:
1388 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1389 Q.getLocalBeginLoc(),
1390 TU)))
1391 return true;
1392
1393 break;
1394
1395 case NestedNameSpecifier::TypeSpec:
1396 case NestedNameSpecifier::TypeSpecWithTemplate:
1397 if (Visit(Q.getTypeLoc()))
1398 return true;
1399
1400 break;
1401
1402 case NestedNameSpecifier::Global:
1403 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001404 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001405 break;
1406 }
1407 }
1408
1409 return false;
1410}
1411
1412bool CursorVisitor::VisitTemplateParameters(
1413 const TemplateParameterList *Params) {
1414 if (!Params)
1415 return false;
1416
1417 for (TemplateParameterList::const_iterator P = Params->begin(),
1418 PEnd = Params->end();
1419 P != PEnd; ++P) {
1420 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1421 return true;
1422 }
1423
1424 return false;
1425}
1426
1427bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1428 switch (Name.getKind()) {
1429 case TemplateName::Template:
1430 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1431
1432 case TemplateName::OverloadedTemplate:
1433 // Visit the overloaded template set.
1434 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1435 return true;
1436
1437 return false;
1438
Richard Smithb23c5e82019-05-09 03:31:27 +00001439 case TemplateName::AssumedTemplate:
1440 // FIXME: Visit DeclarationName?
1441 return false;
1442
Guy Benyei11169dd2012-12-18 14:30:41 +00001443 case TemplateName::DependentTemplate:
1444 // FIXME: Visit nested-name-specifier.
1445 return false;
1446
1447 case TemplateName::QualifiedTemplate:
1448 // FIXME: Visit nested-name-specifier.
1449 return Visit(MakeCursorTemplateRef(
1450 Name.getAsQualifiedTemplateName()->getDecl(),
1451 Loc, TU));
1452
1453 case TemplateName::SubstTemplateTemplateParm:
1454 return Visit(MakeCursorTemplateRef(
1455 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1456 Loc, TU));
1457
1458 case TemplateName::SubstTemplateTemplateParmPack:
1459 return Visit(MakeCursorTemplateRef(
1460 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1461 Loc, TU));
1462 }
1463
1464 llvm_unreachable("Invalid TemplateName::Kind!");
1465}
1466
1467bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1468 switch (TAL.getArgument().getKind()) {
1469 case TemplateArgument::Null:
1470 case TemplateArgument::Integral:
1471 case TemplateArgument::Pack:
1472 return false;
1473
1474 case TemplateArgument::Type:
1475 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1476 return Visit(TSInfo->getTypeLoc());
1477 return false;
1478
1479 case TemplateArgument::Declaration:
1480 if (Expr *E = TAL.getSourceDeclExpression())
1481 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1482 return false;
1483
1484 case TemplateArgument::NullPtr:
1485 if (Expr *E = TAL.getSourceNullPtrExpression())
1486 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1487 return false;
1488
1489 case TemplateArgument::Expression:
1490 if (Expr *E = TAL.getSourceExpression())
1491 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1492 return false;
1493
1494 case TemplateArgument::Template:
1495 case TemplateArgument::TemplateExpansion:
1496 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1497 return true;
1498
1499 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1500 TAL.getTemplateNameLoc());
1501 }
1502
1503 llvm_unreachable("Invalid TemplateArgument::Kind!");
1504}
1505
1506bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1507 return VisitDeclContext(D);
1508}
1509
1510bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1511 return Visit(TL.getUnqualifiedLoc());
1512}
1513
1514bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1515 ASTContext &Context = AU->getASTContext();
1516
1517 // Some builtin types (such as Objective-C's "id", "sel", and
1518 // "Class") have associated declarations. Create cursors for those.
1519 QualType VisitType;
1520 switch (TL.getTypePtr()->getKind()) {
1521
1522 case BuiltinType::Void:
1523 case BuiltinType::NullPtr:
1524 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001525#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1526 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001527#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001528#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1529 case BuiltinType::Id:
1530#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001531 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001532 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001533 case BuiltinType::OCLClkEvent:
1534 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001535 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001536#define SVE_TYPE(Name, Id, SingletonId) \
1537 case BuiltinType::Id:
1538#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00001539#define BUILTIN_TYPE(Id, SingletonId)
1540#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1541#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1542#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1543#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1544#include "clang/AST/BuiltinTypes.def"
1545 break;
1546
1547 case BuiltinType::ObjCId:
1548 VisitType = Context.getObjCIdType();
1549 break;
1550
1551 case BuiltinType::ObjCClass:
1552 VisitType = Context.getObjCClassType();
1553 break;
1554
1555 case BuiltinType::ObjCSel:
1556 VisitType = Context.getObjCSelType();
1557 break;
1558 }
1559
1560 if (!VisitType.isNull()) {
1561 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1562 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1563 TU));
1564 }
1565
1566 return false;
1567}
1568
1569bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1570 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1571}
1572
1573bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1574 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1575}
1576
1577bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1578 if (TL.isDefinition())
1579 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1580
1581 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1582}
1583
1584bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1585 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1586}
1587
1588bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001589 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001590}
1591
Manman Rene6be26c2016-09-13 17:25:08 +00001592bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001593 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001594 return true;
1595 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1596 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1597 TU)))
1598 return true;
1599 }
1600
1601 return false;
1602}
1603
Guy Benyei11169dd2012-12-18 14:30:41 +00001604bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1605 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1606 return true;
1607
Douglas Gregore9d95f12015-07-07 03:57:35 +00001608 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1609 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1610 return true;
1611 }
1612
Guy Benyei11169dd2012-12-18 14:30:41 +00001613 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1614 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1615 TU)))
1616 return true;
1617 }
1618
1619 return false;
1620}
1621
1622bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1623 return Visit(TL.getPointeeLoc());
1624}
1625
1626bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1627 return Visit(TL.getInnerLoc());
1628}
1629
Leonard Chanc72aaf62019-05-07 03:20:17 +00001630bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1631 return Visit(TL.getInnerLoc());
1632}
1633
Guy Benyei11169dd2012-12-18 14:30:41 +00001634bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1635 return Visit(TL.getPointeeLoc());
1636}
1637
1638bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1639 return Visit(TL.getPointeeLoc());
1640}
1641
1642bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1643 return Visit(TL.getPointeeLoc());
1644}
1645
1646bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1647 return Visit(TL.getPointeeLoc());
1648}
1649
1650bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1651 return Visit(TL.getPointeeLoc());
1652}
1653
1654bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1655 return Visit(TL.getModifiedLoc());
1656}
1657
1658bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1659 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001660 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 return true;
1662
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001663 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1664 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001665 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1666 return true;
1667
1668 return false;
1669}
1670
1671bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1672 if (Visit(TL.getElementLoc()))
1673 return true;
1674
1675 if (Expr *Size = TL.getSizeExpr())
1676 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1677
1678 return false;
1679}
1680
Reid Kleckner8a365022013-06-24 17:51:48 +00001681bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1682 return Visit(TL.getOriginalLoc());
1683}
1684
Reid Kleckner0503a872013-12-05 01:23:43 +00001685bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1686 return Visit(TL.getOriginalLoc());
1687}
1688
Richard Smith600b5262017-01-26 20:40:47 +00001689bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1690 DeducedTemplateSpecializationTypeLoc TL) {
1691 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1692 TL.getTemplateNameLoc()))
1693 return true;
1694
1695 return false;
1696}
1697
Guy Benyei11169dd2012-12-18 14:30:41 +00001698bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1699 TemplateSpecializationTypeLoc TL) {
1700 // Visit the template name.
1701 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1702 TL.getTemplateNameLoc()))
1703 return true;
1704
1705 // Visit the template arguments.
1706 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1707 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1708 return true;
1709
1710 return false;
1711}
1712
1713bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1714 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1715}
1716
1717bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1718 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1719 return Visit(TSInfo->getTypeLoc());
1720
1721 return false;
1722}
1723
1724bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1725 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1726 return Visit(TSInfo->getTypeLoc());
1727
1728 return false;
1729}
1730
1731bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001732 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001733}
1734
1735bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1736 DependentTemplateSpecializationTypeLoc TL) {
1737 // Visit the nested-name-specifier, if there is one.
1738 if (TL.getQualifierLoc() &&
1739 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1740 return true;
1741
1742 // Visit the template arguments.
1743 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1744 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1745 return true;
1746
1747 return false;
1748}
1749
1750bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1751 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1752 return true;
1753
1754 return Visit(TL.getNamedTypeLoc());
1755}
1756
1757bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1758 return Visit(TL.getPatternLoc());
1759}
1760
1761bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1762 if (Expr *E = TL.getUnderlyingExpr())
1763 return Visit(MakeCXCursor(E, StmtParent, TU));
1764
1765 return false;
1766}
1767
1768bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1769 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1770}
1771
1772bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1773 return Visit(TL.getValueLoc());
1774}
1775
Xiuli Pan9c14e282016-01-09 12:53:17 +00001776bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1777 return Visit(TL.getValueLoc());
1778}
1779
Guy Benyei11169dd2012-12-18 14:30:41 +00001780#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1781bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1782 return Visit##PARENT##Loc(TL); \
1783}
1784
1785DEFAULT_TYPELOC_IMPL(Complex, Type)
1786DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1787DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1788DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1789DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001790DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001791DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001792DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1793DEFAULT_TYPELOC_IMPL(Vector, Type)
1794DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1795DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1796DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1797DEFAULT_TYPELOC_IMPL(Record, TagType)
1798DEFAULT_TYPELOC_IMPL(Enum, TagType)
1799DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1800DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1801DEFAULT_TYPELOC_IMPL(Auto, Type)
1802
1803bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1804 // Visit the nested-name-specifier, if present.
1805 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1806 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1807 return true;
1808
1809 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001810 for (const auto &I : D->bases()) {
1811 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 return true;
1813 }
1814 }
1815
1816 return VisitTagDecl(D);
1817}
1818
1819bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001820 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001821 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1822 !I->isImplicit()) &&
1823 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001824 return true;
1825
1826 return false;
1827}
1828
1829//===----------------------------------------------------------------------===//
1830// Data-recursive visitor methods.
1831//===----------------------------------------------------------------------===//
1832
1833namespace {
1834#define DEF_JOB(NAME, DATA, KIND)\
1835class NAME : public VisitorJob {\
1836public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001837 NAME(const DATA *d, CXCursor parent) : \
1838 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001839 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001840 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001841};
1842
1843DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1844DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1845DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1846DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001847DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1848DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1849DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1850#undef DEF_JOB
1851
James Y Knight04ec5bf2015-12-24 02:59:37 +00001852class ExplicitTemplateArgsVisit : public VisitorJob {
1853public:
1854 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1855 const TemplateArgumentLoc *End, CXCursor parent)
1856 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1857 End) {}
1858 static bool classof(const VisitorJob *VJ) {
1859 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1860 }
1861 const TemplateArgumentLoc *begin() const {
1862 return static_cast<const TemplateArgumentLoc *>(data[0]);
1863 }
1864 const TemplateArgumentLoc *end() {
1865 return static_cast<const TemplateArgumentLoc *>(data[1]);
1866 }
1867};
Guy Benyei11169dd2012-12-18 14:30:41 +00001868class DeclVisit : public VisitorJob {
1869public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001870 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001872 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001873 static bool classof(const VisitorJob *VJ) {
1874 return VJ->getKind() == DeclVisitKind;
1875 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001876 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001877 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001878};
1879class TypeLocVisit : public VisitorJob {
1880public:
1881 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1882 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1883 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1884
1885 static bool classof(const VisitorJob *VJ) {
1886 return VJ->getKind() == TypeLocVisitKind;
1887 }
1888
1889 TypeLoc get() const {
1890 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001891 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001892 }
1893};
1894
1895class LabelRefVisit : public VisitorJob {
1896public:
1897 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1898 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1899 labelLoc.getPtrEncoding()) {}
1900
1901 static bool classof(const VisitorJob *VJ) {
1902 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1903 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001904 const LabelDecl *get() const {
1905 return static_cast<const LabelDecl *>(data[0]);
1906 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001907 SourceLocation getLoc() const {
1908 return SourceLocation::getFromPtrEncoding(data[1]); }
1909};
1910
1911class NestedNameSpecifierLocVisit : public VisitorJob {
1912public:
1913 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1914 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1915 Qualifier.getNestedNameSpecifier(),
1916 Qualifier.getOpaqueData()) { }
1917
1918 static bool classof(const VisitorJob *VJ) {
1919 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1920 }
1921
1922 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001923 return NestedNameSpecifierLoc(
1924 const_cast<NestedNameSpecifier *>(
1925 static_cast<const NestedNameSpecifier *>(data[0])),
1926 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001927 }
1928};
1929
1930class DeclarationNameInfoVisit : public VisitorJob {
1931public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001932 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001933 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 static bool classof(const VisitorJob *VJ) {
1935 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1936 }
1937 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001938 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001939 switch (S->getStmtClass()) {
1940 default:
1941 llvm_unreachable("Unhandled Stmt");
1942 case clang::Stmt::MSDependentExistsStmtClass:
1943 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1944 case Stmt::CXXDependentScopeMemberExprClass:
1945 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1946 case Stmt::DependentScopeDeclRefExprClass:
1947 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001948 case Stmt::OMPCriticalDirectiveClass:
1949 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001950 }
1951 }
1952};
1953class MemberRefVisit : public VisitorJob {
1954public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001955 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001956 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1957 L.getPtrEncoding()) {}
1958 static bool classof(const VisitorJob *VJ) {
1959 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1960 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001961 const FieldDecl *get() const {
1962 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001963 }
1964 SourceLocation getLoc() const {
1965 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1966 }
1967};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001968class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001969 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001970 VisitorWorkList &WL;
1971 CXCursor Parent;
1972public:
1973 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1974 : WL(wl), Parent(parent) {}
1975
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001976 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1977 void VisitBlockExpr(const BlockExpr *B);
1978 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1979 void VisitCompoundStmt(const CompoundStmt *S);
1980 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1981 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1982 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1983 void VisitCXXNewExpr(const CXXNewExpr *E);
1984 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1985 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1986 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1987 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1988 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1989 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1990 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1991 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001992 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001993 void VisitDeclRefExpr(const DeclRefExpr *D);
1994 void VisitDeclStmt(const DeclStmt *S);
1995 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1996 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1997 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1998 void VisitForStmt(const ForStmt *FS);
1999 void VisitGotoStmt(const GotoStmt *GS);
2000 void VisitIfStmt(const IfStmt *If);
2001 void VisitInitListExpr(const InitListExpr *IE);
2002 void VisitMemberExpr(const MemberExpr *M);
2003 void VisitOffsetOfExpr(const OffsetOfExpr *E);
2004 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2005 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
2006 void VisitOverloadExpr(const OverloadExpr *E);
2007 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2008 void VisitStmt(const Stmt *S);
2009 void VisitSwitchStmt(const SwitchStmt *S);
2010 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002011 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2012 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2013 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2014 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2015 void VisitVAArgExpr(const VAArgExpr *E);
2016 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2017 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2018 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2019 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002020 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002021 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002022 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002023 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002024 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002025 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002026 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002027 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002028 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002029 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002030 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002031 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002032 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002033 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002034 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002035 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002036 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002037 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002038 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002039 void
2040 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002041 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002042 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002043 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002044 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002045 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002046 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002047 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002048 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002049 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002050 void
2051 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002052 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002053 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002054 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Alexey Bataev60e51c42019-10-10 20:13:02 +00002055 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002056 void
2057 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002058 void VisitOMPParallelMasterTaskLoopDirective(
2059 const OMPParallelMasterTaskLoopDirective *D);
Alexey Bataev14a388f2019-10-25 10:27:13 -04002060 void VisitOMPParallelMasterTaskLoopSimdDirective(
2061 const OMPParallelMasterTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002062 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002063 void VisitOMPDistributeParallelForDirective(
2064 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002065 void VisitOMPDistributeParallelForSimdDirective(
2066 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002067 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002068 void VisitOMPTargetParallelForSimdDirective(
2069 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002070 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002071 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002072 void VisitOMPTeamsDistributeSimdDirective(
2073 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002074 void VisitOMPTeamsDistributeParallelForSimdDirective(
2075 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002076 void VisitOMPTeamsDistributeParallelForDirective(
2077 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002078 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002079 void VisitOMPTargetTeamsDistributeDirective(
2080 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002081 void VisitOMPTargetTeamsDistributeParallelForDirective(
2082 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002083 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2084 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002085 void VisitOMPTargetTeamsDistributeSimdDirective(
2086 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002087
Guy Benyei11169dd2012-12-18 14:30:41 +00002088private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002089 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002090 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002091 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2092 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002093 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2094 void AddStmt(const Stmt *S);
2095 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002097 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002098 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002099};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002100} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002101
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002102void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002103 // 'S' should always be non-null, since it comes from the
2104 // statement we are visiting.
2105 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2106}
2107
2108void
2109EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2110 if (Qualifier)
2111 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2112}
2113
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002114void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 if (S)
2116 WL.push_back(StmtVisit(S, Parent));
2117}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002118void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 if (D)
2120 WL.push_back(DeclVisit(D, Parent, isFirst));
2121}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002122void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2123 unsigned NumTemplateArgs) {
2124 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002125}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002126void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 if (D)
2128 WL.push_back(MemberRefVisit(D, L, Parent));
2129}
2130void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2131 if (TI)
2132 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2133 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002134void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002135 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002136 for (const Stmt *SubStmt : S->children()) {
2137 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002138 }
2139 if (size == WL.size())
2140 return;
2141 // Now reverse the entries we just added. This will match the DFS
2142 // ordering performed by the worklist.
2143 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2144 std::reverse(I, E);
2145}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002146namespace {
2147class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2148 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002149 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002150 template <typename T>
2151 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002152public:
2153 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2154#define OPENMP_CLAUSE(Name, Class) \
2155 void Visit##Class(const Class *C);
2156#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002157 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002158 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002159};
2160
Alexey Bataev3392d762016-02-16 11:18:12 +00002161void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2162 const OMPClauseWithPreInit *C) {
2163 Visitor->AddStmt(C->getPreInitStmt());
2164}
2165
Alexey Bataev005248a2016-02-25 05:25:57 +00002166void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2167 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002168 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002169 Visitor->AddStmt(C->getPostUpdateExpr());
2170}
2171
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002172void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002173 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002174 Visitor->AddStmt(C->getCondition());
2175}
2176
Alexey Bataev3778b602014-07-17 07:32:53 +00002177void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2178 Visitor->AddStmt(C->getCondition());
2179}
2180
Alexey Bataev568a8332014-03-06 06:15:19 +00002181void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002182 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002183 Visitor->AddStmt(C->getNumThreads());
2184}
2185
Alexey Bataev62c87d22014-03-21 04:51:18 +00002186void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2187 Visitor->AddStmt(C->getSafelen());
2188}
2189
Alexey Bataev66b15b52015-08-21 11:14:16 +00002190void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2191 Visitor->AddStmt(C->getSimdlen());
2192}
2193
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002194void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2195 Visitor->AddStmt(C->getAllocator());
2196}
2197
Alexander Musman8bd31e62014-05-27 15:12:19 +00002198void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2199 Visitor->AddStmt(C->getNumForLoops());
2200}
2201
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002202void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002203
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002204void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2205
Alexey Bataev56dafe82014-06-20 07:16:17 +00002206void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002207 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002208 Visitor->AddStmt(C->getChunkSize());
2209}
2210
Alexey Bataev10e775f2015-07-30 11:36:16 +00002211void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2212 Visitor->AddStmt(C->getNumForLoops());
2213}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002214
Alexey Bataev236070f2014-06-20 11:19:47 +00002215void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2216
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002217void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2218
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002219void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2220
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002221void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2222
Alexey Bataevdea47612014-07-23 07:46:59 +00002223void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2224
Alexey Bataev67a4f222014-07-23 10:25:33 +00002225void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2226
Alexey Bataev459dec02014-07-24 06:46:57 +00002227void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2228
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002229void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2230
Alexey Bataev346265e2015-09-25 10:37:12 +00002231void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2232
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002233void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2234
Alexey Bataevb825de12015-12-07 10:51:44 +00002235void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2236
Kelvin Li1408f912018-09-26 04:28:39 +00002237void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2238 const OMPUnifiedAddressClause *) {}
2239
Patrick Lyster4a370b92018-10-01 13:47:43 +00002240void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2241 const OMPUnifiedSharedMemoryClause *) {}
2242
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002243void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2244 const OMPReverseOffloadClause *) {}
2245
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002246void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2247 const OMPDynamicAllocatorsClause *) {}
2248
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002249void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2250 const OMPAtomicDefaultMemOrderClause *) {}
2251
Michael Wonge710d542015-08-07 16:16:36 +00002252void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2253 Visitor->AddStmt(C->getDevice());
2254}
2255
Kelvin Li099bb8c2015-11-24 20:50:12 +00002256void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002257 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002258 Visitor->AddStmt(C->getNumTeams());
2259}
2260
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002261void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002262 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002263 Visitor->AddStmt(C->getThreadLimit());
2264}
2265
Alexey Bataeva0569352015-12-01 10:17:31 +00002266void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2267 Visitor->AddStmt(C->getPriority());
2268}
2269
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002270void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2271 Visitor->AddStmt(C->getGrainsize());
2272}
2273
Alexey Bataev382967a2015-12-08 12:06:20 +00002274void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2275 Visitor->AddStmt(C->getNumTasks());
2276}
2277
Alexey Bataev28c75412015-12-15 08:19:24 +00002278void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2279 Visitor->AddStmt(C->getHint());
2280}
2281
Alexey Bataev756c1962013-09-24 03:17:45 +00002282template<typename T>
2283void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002284 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002285 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002286 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002287}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002288
Alexey Bataeve04483e2019-03-27 14:14:31 +00002289void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2290 VisitOMPClauseList(C);
2291 Visitor->AddStmt(C->getAllocator());
2292}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002293void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002294 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002295 for (const auto *E : C->private_copies()) {
2296 Visitor->AddStmt(E);
2297 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002298}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002299void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2300 const OMPFirstprivateClause *C) {
2301 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002302 VisitOMPClauseWithPreInit(C);
2303 for (const auto *E : C->private_copies()) {
2304 Visitor->AddStmt(E);
2305 }
2306 for (const auto *E : C->inits()) {
2307 Visitor->AddStmt(E);
2308 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002309}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002310void OMPClauseEnqueue::VisitOMPLastprivateClause(
2311 const OMPLastprivateClause *C) {
2312 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002313 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002314 for (auto *E : C->private_copies()) {
2315 Visitor->AddStmt(E);
2316 }
2317 for (auto *E : C->source_exprs()) {
2318 Visitor->AddStmt(E);
2319 }
2320 for (auto *E : C->destination_exprs()) {
2321 Visitor->AddStmt(E);
2322 }
2323 for (auto *E : C->assignment_ops()) {
2324 Visitor->AddStmt(E);
2325 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002326}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002327void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002328 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002329}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002330void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2331 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002332 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002333 for (auto *E : C->privates()) {
2334 Visitor->AddStmt(E);
2335 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002336 for (auto *E : C->lhs_exprs()) {
2337 Visitor->AddStmt(E);
2338 }
2339 for (auto *E : C->rhs_exprs()) {
2340 Visitor->AddStmt(E);
2341 }
2342 for (auto *E : C->reduction_ops()) {
2343 Visitor->AddStmt(E);
2344 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002345}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002346void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2347 const OMPTaskReductionClause *C) {
2348 VisitOMPClauseList(C);
2349 VisitOMPClauseWithPostUpdate(C);
2350 for (auto *E : C->privates()) {
2351 Visitor->AddStmt(E);
2352 }
2353 for (auto *E : C->lhs_exprs()) {
2354 Visitor->AddStmt(E);
2355 }
2356 for (auto *E : C->rhs_exprs()) {
2357 Visitor->AddStmt(E);
2358 }
2359 for (auto *E : C->reduction_ops()) {
2360 Visitor->AddStmt(E);
2361 }
2362}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002363void OMPClauseEnqueue::VisitOMPInReductionClause(
2364 const OMPInReductionClause *C) {
2365 VisitOMPClauseList(C);
2366 VisitOMPClauseWithPostUpdate(C);
2367 for (auto *E : C->privates()) {
2368 Visitor->AddStmt(E);
2369 }
2370 for (auto *E : C->lhs_exprs()) {
2371 Visitor->AddStmt(E);
2372 }
2373 for (auto *E : C->rhs_exprs()) {
2374 Visitor->AddStmt(E);
2375 }
2376 for (auto *E : C->reduction_ops()) {
2377 Visitor->AddStmt(E);
2378 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002379 for (auto *E : C->taskgroup_descriptors())
2380 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002381}
Alexander Musman8dba6642014-04-22 13:09:42 +00002382void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2383 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002384 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002385 for (const auto *E : C->privates()) {
2386 Visitor->AddStmt(E);
2387 }
Alexander Musman3276a272015-03-21 10:12:56 +00002388 for (const auto *E : C->inits()) {
2389 Visitor->AddStmt(E);
2390 }
2391 for (const auto *E : C->updates()) {
2392 Visitor->AddStmt(E);
2393 }
2394 for (const auto *E : C->finals()) {
2395 Visitor->AddStmt(E);
2396 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002397 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002398 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002399}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002400void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2401 VisitOMPClauseList(C);
2402 Visitor->AddStmt(C->getAlignment());
2403}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002404void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2405 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002406 for (auto *E : C->source_exprs()) {
2407 Visitor->AddStmt(E);
2408 }
2409 for (auto *E : C->destination_exprs()) {
2410 Visitor->AddStmt(E);
2411 }
2412 for (auto *E : C->assignment_ops()) {
2413 Visitor->AddStmt(E);
2414 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002415}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002416void
2417OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2418 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002419 for (auto *E : C->source_exprs()) {
2420 Visitor->AddStmt(E);
2421 }
2422 for (auto *E : C->destination_exprs()) {
2423 Visitor->AddStmt(E);
2424 }
2425 for (auto *E : C->assignment_ops()) {
2426 Visitor->AddStmt(E);
2427 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002428}
Alexey Bataev6125da92014-07-21 11:26:11 +00002429void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2430 VisitOMPClauseList(C);
2431}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002432void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2433 VisitOMPClauseList(C);
2434}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002435void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2436 VisitOMPClauseList(C);
2437}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002438void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2439 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002440 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002441 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002442}
Alexey Bataev3392d762016-02-16 11:18:12 +00002443void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2444 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002445void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2446 VisitOMPClauseList(C);
2447}
Samuel Antaoec172c62016-05-26 17:49:04 +00002448void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2449 VisitOMPClauseList(C);
2450}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002451void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2452 VisitOMPClauseList(C);
2453}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002454void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2455 VisitOMPClauseList(C);
2456}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002457}
Alexey Bataev756c1962013-09-24 03:17:45 +00002458
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002459void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2460 unsigned size = WL.size();
2461 OMPClauseEnqueue Visitor(this);
2462 Visitor.Visit(S);
2463 if (size == WL.size())
2464 return;
2465 // Now reverse the entries we just added. This will match the DFS
2466 // ordering performed by the worklist.
2467 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2468 std::reverse(I, E);
2469}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002470void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2472}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002473void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 AddDecl(B->getBlockDecl());
2475}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002476void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 EnqueueChildren(E);
2478 AddTypeLoc(E->getTypeSourceInfo());
2479}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002480void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002481 for (auto &I : llvm::reverse(S->body()))
2482 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002483}
2484void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002485VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 AddStmt(S->getSubStmt());
2487 AddDeclarationNameInfo(S);
2488 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2489 AddNestedNameSpecifierLoc(QualifierLoc);
2490}
2491
2492void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002493VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002494 if (E->hasExplicitTemplateArgs())
2495 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 AddDeclarationNameInfo(E);
2497 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2498 AddNestedNameSpecifierLoc(QualifierLoc);
2499 if (!E->isImplicitAccess())
2500 AddStmt(E->getBase());
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 // Enqueue the initializer , if any.
2504 AddStmt(E->getInitializer());
2505 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002506 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 // Enqueue the allocated type.
2508 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2509 // Enqueue the placement arguments.
2510 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2511 AddStmt(E->getPlacementArg(I-1));
2512}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002513void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2515 AddStmt(CE->getArg(I-1));
2516 AddStmt(CE->getCallee());
2517 AddStmt(CE->getArg(0));
2518}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002519void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2520 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 // Visit the name of the type being destroyed.
2522 AddTypeLoc(E->getDestroyedTypeInfo());
2523 // Visit the scope type that looks disturbingly like the nested-name-specifier
2524 // but isn't.
2525 AddTypeLoc(E->getScopeTypeInfo());
2526 // Visit the nested-name-specifier.
2527 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2528 AddNestedNameSpecifierLoc(QualifierLoc);
2529 // Visit base expression.
2530 AddStmt(E->getBase());
2531}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002532void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2533 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 AddTypeLoc(E->getTypeSourceInfo());
2535}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002536void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2537 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 EnqueueChildren(E);
2539 AddTypeLoc(E->getTypeSourceInfo());
2540}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002541void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 EnqueueChildren(E);
2543 if (E->isTypeOperand())
2544 AddTypeLoc(E->getTypeOperandSourceInfo());
2545}
2546
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002547void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2548 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 EnqueueChildren(E);
2550 AddTypeLoc(E->getTypeSourceInfo());
2551}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002552void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 EnqueueChildren(E);
2554 if (E->isTypeOperand())
2555 AddTypeLoc(E->getTypeOperandSourceInfo());
2556}
2557
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002558void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 EnqueueChildren(S);
2560 AddDecl(S->getExceptionDecl());
2561}
2562
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002563void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002564 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002565 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002566 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002567}
2568
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002569void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002570 if (DR->hasExplicitTemplateArgs())
2571 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 WL.push_back(DeclRefExprParts(DR, Parent));
2573}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002574void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2575 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002576 if (E->hasExplicitTemplateArgs())
2577 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 AddDeclarationNameInfo(E);
2579 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2580}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002581void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 unsigned size = WL.size();
2583 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002584 for (const auto *D : S->decls()) {
2585 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 isFirst = false;
2587 }
2588 if (size == WL.size())
2589 return;
2590 // Now reverse the entries we just added. This will match the DFS
2591 // ordering performed by the worklist.
2592 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2593 std::reverse(I, E);
2594}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002595void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002597 for (const DesignatedInitExpr::Designator &D :
2598 llvm::reverse(E->designators())) {
2599 if (D.isFieldDesignator()) {
2600 if (FieldDecl *Field = D.getField())
2601 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 continue;
2603 }
David Majnemerf7e36092016-06-23 00:15:04 +00002604 if (D.isArrayDesignator()) {
2605 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 continue;
2607 }
David Majnemerf7e36092016-06-23 00:15:04 +00002608 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2609 AddStmt(E->getArrayRangeEnd(D));
2610 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 }
2612}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002613void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 EnqueueChildren(E);
2615 AddTypeLoc(E->getTypeInfoAsWritten());
2616}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002617void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 AddStmt(FS->getBody());
2619 AddStmt(FS->getInc());
2620 AddStmt(FS->getCond());
2621 AddDecl(FS->getConditionVariable());
2622 AddStmt(FS->getInit());
2623}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002624void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2626}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002627void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 AddStmt(If->getElse());
2629 AddStmt(If->getThen());
2630 AddStmt(If->getCond());
2631 AddDecl(If->getConditionVariable());
2632}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002633void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 // We care about the syntactic form of the initializer list, only.
2635 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2636 IE = Syntactic;
2637 EnqueueChildren(IE);
2638}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002639void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 WL.push_back(MemberExprParts(M, Parent));
2641
2642 // If the base of the member access expression is an implicit 'this', don't
2643 // visit it.
2644 // FIXME: If we ever want to show these implicit accesses, this will be
2645 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002646 if (M->isImplicitAccess())
2647 return;
2648
2649 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002650 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002651 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2652 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2653 if (FD->isAnonymousStructOrUnion()) {
2654 AddStmt(SubME->getBase());
2655 return;
2656 }
2657 }
2658 }
2659
2660 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002661}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002662void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 AddTypeLoc(E->getEncodedTypeSourceInfo());
2664}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002665void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 EnqueueChildren(M);
2667 AddTypeLoc(M->getClassReceiverTypeInfo());
2668}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002669void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 // Visit the components of the offsetof expression.
2671 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 const OffsetOfNode &Node = E->getComponent(I-1);
2673 switch (Node.getKind()) {
2674 case OffsetOfNode::Array:
2675 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2676 break;
2677 case OffsetOfNode::Field:
2678 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2679 break;
2680 case OffsetOfNode::Identifier:
2681 case OffsetOfNode::Base:
2682 continue;
2683 }
2684 }
2685 // Visit the type into which we're computing the offset.
2686 AddTypeLoc(E->getTypeSourceInfo());
2687}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002688void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002689 if (E->hasExplicitTemplateArgs())
2690 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 WL.push_back(OverloadExprParts(E, Parent));
2692}
2693void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002694 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 EnqueueChildren(E);
2696 if (E->isArgumentType())
2697 AddTypeLoc(E->getArgumentTypeInfo());
2698}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002699void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 EnqueueChildren(S);
2701}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002702void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 AddStmt(S->getBody());
2704 AddStmt(S->getCond());
2705 AddDecl(S->getConditionVariable());
2706}
2707
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002708void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 AddStmt(W->getBody());
2710 AddStmt(W->getCond());
2711 AddDecl(W->getConditionVariable());
2712}
2713
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002714void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 for (unsigned I = E->getNumArgs(); I > 0; --I)
2716 AddTypeLoc(E->getArg(I-1));
2717}
2718
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002719void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 AddTypeLoc(E->getQueriedTypeSourceInfo());
2721}
2722
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002723void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 EnqueueChildren(E);
2725}
2726
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002727void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 VisitOverloadExpr(U);
2729 if (!U->isImplicitAccess())
2730 AddStmt(U->getBase());
2731}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002732void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 AddStmt(E->getSubExpr());
2734 AddTypeLoc(E->getWrittenTypeInfo());
2735}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002736void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 WL.push_back(SizeOfPackExprParts(E, Parent));
2738}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002739void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 // If the opaque value has a source expression, just transparently
2741 // visit that. This is useful for (e.g.) pseudo-object expressions.
2742 if (Expr *SourceExpr = E->getSourceExpr())
2743 return Visit(SourceExpr);
2744}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002745void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002746 AddStmt(E->getBody());
2747 WL.push_back(LambdaExprParts(E, Parent));
2748}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002749void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002750 // Treat the expression like its syntactic form.
2751 Visit(E->getSyntacticForm());
2752}
2753
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002754void EnqueueVisitor::VisitOMPExecutableDirective(
2755 const OMPExecutableDirective *D) {
2756 EnqueueChildren(D);
2757 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2758 E = D->clauses().end();
2759 I != E; ++I)
2760 EnqueueChildren(*I);
2761}
2762
Alexander Musman3aaab662014-08-19 11:27:13 +00002763void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2764 VisitOMPExecutableDirective(D);
2765}
2766
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002767void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2768 VisitOMPExecutableDirective(D);
2769}
2770
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002771void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002772 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002773}
2774
Alexey Bataevf29276e2014-06-18 04:14:57 +00002775void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002776 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002777}
2778
Alexander Musmanf82886e2014-09-18 05:12:34 +00002779void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2780 VisitOMPLoopDirective(D);
2781}
2782
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002783void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2784 VisitOMPExecutableDirective(D);
2785}
2786
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002787void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2788 VisitOMPExecutableDirective(D);
2789}
2790
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002791void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2792 VisitOMPExecutableDirective(D);
2793}
2794
Alexander Musman80c22892014-07-17 08:54:58 +00002795void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2796 VisitOMPExecutableDirective(D);
2797}
2798
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002799void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2800 VisitOMPExecutableDirective(D);
2801 AddDeclarationNameInfo(D);
2802}
2803
Alexey Bataev4acb8592014-07-07 13:01:15 +00002804void
2805EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002806 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002807}
2808
Alexander Musmane4e893b2014-09-23 09:33:00 +00002809void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2810 const OMPParallelForSimdDirective *D) {
2811 VisitOMPLoopDirective(D);
2812}
2813
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002814void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2815 const OMPParallelSectionsDirective *D) {
2816 VisitOMPExecutableDirective(D);
2817}
2818
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002819void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2820 VisitOMPExecutableDirective(D);
2821}
2822
Alexey Bataev68446b72014-07-18 07:47:19 +00002823void
2824EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2825 VisitOMPExecutableDirective(D);
2826}
2827
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002828void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2829 VisitOMPExecutableDirective(D);
2830}
2831
Alexey Bataev2df347a2014-07-18 10:17:07 +00002832void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2833 VisitOMPExecutableDirective(D);
2834}
2835
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002836void EnqueueVisitor::VisitOMPTaskgroupDirective(
2837 const OMPTaskgroupDirective *D) {
2838 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002839 if (const Expr *E = D->getReductionRef())
2840 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002841}
2842
Alexey Bataev6125da92014-07-21 11:26:11 +00002843void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2844 VisitOMPExecutableDirective(D);
2845}
2846
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002847void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2848 VisitOMPExecutableDirective(D);
2849}
2850
Alexey Bataev0162e452014-07-22 10:10:35 +00002851void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2852 VisitOMPExecutableDirective(D);
2853}
2854
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002855void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2856 VisitOMPExecutableDirective(D);
2857}
2858
Michael Wong65f367f2015-07-21 13:44:28 +00002859void EnqueueVisitor::VisitOMPTargetDataDirective(const
2860 OMPTargetDataDirective *D) {
2861 VisitOMPExecutableDirective(D);
2862}
2863
Samuel Antaodf67fc42016-01-19 19:15:56 +00002864void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2865 const OMPTargetEnterDataDirective *D) {
2866 VisitOMPExecutableDirective(D);
2867}
2868
Samuel Antao72590762016-01-19 20:04:50 +00002869void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2870 const OMPTargetExitDataDirective *D) {
2871 VisitOMPExecutableDirective(D);
2872}
2873
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002874void EnqueueVisitor::VisitOMPTargetParallelDirective(
2875 const OMPTargetParallelDirective *D) {
2876 VisitOMPExecutableDirective(D);
2877}
2878
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002879void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2880 const OMPTargetParallelForDirective *D) {
2881 VisitOMPLoopDirective(D);
2882}
2883
Alexey Bataev13314bf2014-10-09 04:18:56 +00002884void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2885 VisitOMPExecutableDirective(D);
2886}
2887
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002888void EnqueueVisitor::VisitOMPCancellationPointDirective(
2889 const OMPCancellationPointDirective *D) {
2890 VisitOMPExecutableDirective(D);
2891}
2892
Alexey Bataev80909872015-07-02 11:25:17 +00002893void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2894 VisitOMPExecutableDirective(D);
2895}
2896
Alexey Bataev49f6e782015-12-01 04:18:41 +00002897void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2898 VisitOMPLoopDirective(D);
2899}
2900
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002901void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2902 const OMPTaskLoopSimdDirective *D) {
2903 VisitOMPLoopDirective(D);
2904}
2905
Alexey Bataev60e51c42019-10-10 20:13:02 +00002906void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2907 const OMPMasterTaskLoopDirective *D) {
2908 VisitOMPLoopDirective(D);
2909}
2910
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002911void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2912 const OMPMasterTaskLoopSimdDirective *D) {
2913 VisitOMPLoopDirective(D);
2914}
2915
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002916void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2917 const OMPParallelMasterTaskLoopDirective *D) {
2918 VisitOMPLoopDirective(D);
2919}
2920
Alexey Bataev14a388f2019-10-25 10:27:13 -04002921void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
2922 const OMPParallelMasterTaskLoopSimdDirective *D) {
2923 VisitOMPLoopDirective(D);
2924}
2925
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002926void EnqueueVisitor::VisitOMPDistributeDirective(
2927 const OMPDistributeDirective *D) {
2928 VisitOMPLoopDirective(D);
2929}
2930
Carlo Bertolli9925f152016-06-27 14:55:37 +00002931void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2932 const OMPDistributeParallelForDirective *D) {
2933 VisitOMPLoopDirective(D);
2934}
2935
Kelvin Li4a39add2016-07-05 05:00:15 +00002936void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2937 const OMPDistributeParallelForSimdDirective *D) {
2938 VisitOMPLoopDirective(D);
2939}
2940
Kelvin Li787f3fc2016-07-06 04:45:38 +00002941void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2942 const OMPDistributeSimdDirective *D) {
2943 VisitOMPLoopDirective(D);
2944}
2945
Kelvin Lia579b912016-07-14 02:54:56 +00002946void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2947 const OMPTargetParallelForSimdDirective *D) {
2948 VisitOMPLoopDirective(D);
2949}
2950
Kelvin Li986330c2016-07-20 22:57:10 +00002951void EnqueueVisitor::VisitOMPTargetSimdDirective(
2952 const OMPTargetSimdDirective *D) {
2953 VisitOMPLoopDirective(D);
2954}
2955
Kelvin Li02532872016-08-05 14:37:37 +00002956void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2957 const OMPTeamsDistributeDirective *D) {
2958 VisitOMPLoopDirective(D);
2959}
2960
Kelvin Li4e325f72016-10-25 12:50:55 +00002961void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2962 const OMPTeamsDistributeSimdDirective *D) {
2963 VisitOMPLoopDirective(D);
2964}
2965
Kelvin Li579e41c2016-11-30 23:51:03 +00002966void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2967 const OMPTeamsDistributeParallelForSimdDirective *D) {
2968 VisitOMPLoopDirective(D);
2969}
2970
Kelvin Li7ade93f2016-12-09 03:24:30 +00002971void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2972 const OMPTeamsDistributeParallelForDirective *D) {
2973 VisitOMPLoopDirective(D);
2974}
2975
Kelvin Libf594a52016-12-17 05:48:59 +00002976void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2977 const OMPTargetTeamsDirective *D) {
2978 VisitOMPExecutableDirective(D);
2979}
2980
Kelvin Li83c451e2016-12-25 04:52:54 +00002981void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2982 const OMPTargetTeamsDistributeDirective *D) {
2983 VisitOMPLoopDirective(D);
2984}
2985
Kelvin Li80e8f562016-12-29 22:16:30 +00002986void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2987 const OMPTargetTeamsDistributeParallelForDirective *D) {
2988 VisitOMPLoopDirective(D);
2989}
2990
Kelvin Li1851df52017-01-03 05:23:48 +00002991void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2992 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2993 VisitOMPLoopDirective(D);
2994}
2995
Kelvin Lida681182017-01-10 18:08:18 +00002996void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2997 const OMPTargetTeamsDistributeSimdDirective *D) {
2998 VisitOMPLoopDirective(D);
2999}
3000
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003001void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
3003}
3004
3005bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3006 if (RegionOfInterest.isValid()) {
3007 SourceRange Range = getRawCursorExtent(C);
3008 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3009 return false;
3010 }
3011 return true;
3012}
3013
3014bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3015 while (!WL.empty()) {
3016 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003017 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003018
3019 // Set the Parent field, then back to its old value once we're done.
3020 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3021
3022 switch (LI.getKind()) {
3023 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003024 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 if (!D)
3026 continue;
3027
3028 // For now, perform default visitation for Decls.
3029 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3030 cast<DeclVisit>(&LI)->isFirst())))
3031 return true;
3032
3033 continue;
3034 }
3035 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003036 for (const TemplateArgumentLoc &Arg :
3037 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3038 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 return true;
3040 }
3041 continue;
3042 }
3043 case VisitorJob::TypeLocVisitKind: {
3044 // Perform default visitation for TypeLocs.
3045 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3046 return true;
3047 continue;
3048 }
3049 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003050 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 if (LabelStmt *stmt = LS->getStmt()) {
3052 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3053 TU))) {
3054 return true;
3055 }
3056 }
3057 continue;
3058 }
3059
3060 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3061 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3062 if (VisitNestedNameSpecifierLoc(V->get()))
3063 return true;
3064 continue;
3065 }
3066
3067 case VisitorJob::DeclarationNameInfoVisitKind: {
3068 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3069 ->get()))
3070 return true;
3071 continue;
3072 }
3073 case VisitorJob::MemberRefVisitKind: {
3074 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3075 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3076 return true;
3077 continue;
3078 }
3079 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003080 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 if (!S)
3082 continue;
3083
3084 // Update the current cursor.
3085 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3086 if (!IsInRegionOfInterest(Cursor))
3087 continue;
3088 switch (Visitor(Cursor, Parent, ClientData)) {
3089 case CXChildVisit_Break: return true;
3090 case CXChildVisit_Continue: break;
3091 case CXChildVisit_Recurse:
3092 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003093 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 EnqueueWorkList(WL, S);
3095 break;
3096 }
3097 continue;
3098 }
3099 case VisitorJob::MemberExprPartsKind: {
3100 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003101 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003102
3103 // Visit the nested-name-specifier
3104 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3105 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3106 return true;
3107
3108 // Visit the declaration name.
3109 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3110 return true;
3111
3112 // Visit the explicitly-specified template arguments, if any.
3113 if (M->hasExplicitTemplateArgs()) {
3114 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3115 *ArgEnd = Arg + M->getNumTemplateArgs();
3116 Arg != ArgEnd; ++Arg) {
3117 if (VisitTemplateArgumentLoc(*Arg))
3118 return true;
3119 }
3120 }
3121 continue;
3122 }
3123 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003124 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 // Visit nested-name-specifier, if present.
3126 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3127 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3128 return true;
3129 // Visit declaration name.
3130 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3131 return true;
3132 continue;
3133 }
3134 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003135 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 // Visit the nested-name-specifier.
3137 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3138 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3139 return true;
3140 // Visit the declaration name.
3141 if (VisitDeclarationNameInfo(O->getNameInfo()))
3142 return true;
3143 // Visit the overloaded declaration reference.
3144 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3145 return true;
3146 continue;
3147 }
3148 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003149 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 NamedDecl *Pack = E->getPack();
3151 if (isa<TemplateTypeParmDecl>(Pack)) {
3152 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3153 E->getPackLoc(), TU)))
3154 return true;
3155
3156 continue;
3157 }
3158
3159 if (isa<TemplateTemplateParmDecl>(Pack)) {
3160 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3161 E->getPackLoc(), TU)))
3162 return true;
3163
3164 continue;
3165 }
3166
3167 // Non-type template parameter packs and function parameter packs are
3168 // treated like DeclRefExpr cursors.
3169 continue;
3170 }
3171
3172 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003173 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003174 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003175 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3176 CEnd = E->explicit_capture_end();
3177 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003178 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003179 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003180
Guy Benyei11169dd2012-12-18 14:30:41 +00003181 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3182 C->getLocation(),
3183 TU)))
3184 return true;
3185 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003186 // Visit init captures
3187 for (auto InitExpr : E->capture_inits()) {
3188 if (Visit(InitExpr))
3189 return true;
3190 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003191
Haojian Wuef87c262018-12-18 15:29:12 +00003192 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003194 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3195 if (E->hasExplicitParameters()) {
3196 // Visit parameters.
3197 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3198 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003199 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003200 }
3201 if (E->hasExplicitResultType()) {
3202 // Visit result type.
3203 if (Visit(Proto.getReturnLoc()))
3204 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003205 }
3206 }
3207 break;
3208 }
3209
3210 case VisitorJob::PostChildrenVisitKind:
3211 if (PostChildrenVisitor(Parent, ClientData))
3212 return true;
3213 break;
3214 }
3215 }
3216 return false;
3217}
3218
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003219bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003220 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 if (!WorkListFreeList.empty()) {
3222 WL = WorkListFreeList.back();
3223 WL->clear();
3224 WorkListFreeList.pop_back();
3225 }
3226 else {
3227 WL = new VisitorWorkList();
3228 WorkListCache.push_back(WL);
3229 }
3230 EnqueueWorkList(*WL, S);
3231 bool result = RunVisitorWorkList(*WL);
3232 WorkListFreeList.push_back(WL);
3233 return result;
3234}
3235
3236namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003237typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003238RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3239 const DeclarationNameInfo &NI, SourceRange QLoc,
3240 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003241 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3242 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3243 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3244
3245 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3246
3247 RefNamePieces Pieces;
3248
3249 if (WantQualifier && QLoc.isValid())
3250 Pieces.push_back(QLoc);
3251
3252 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3253 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003254
3255 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3256 Pieces.push_back(*TemplateArgsLoc);
3257
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 if (Kind == DeclarationName::CXXOperatorName) {
3259 Pieces.push_back(SourceLocation::getFromRawEncoding(
3260 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3261 Pieces.push_back(SourceLocation::getFromRawEncoding(
3262 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3263 }
3264
3265 if (WantSinglePiece) {
3266 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3267 Pieces.clear();
3268 Pieces.push_back(R);
3269 }
3270
3271 return Pieces;
3272}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003273}
Guy Benyei11169dd2012-12-18 14:30:41 +00003274
3275//===----------------------------------------------------------------------===//
3276// Misc. API hooks.
3277//===----------------------------------------------------------------------===//
3278
Chandler Carruth66660742014-06-27 16:37:27 +00003279namespace {
3280struct RegisterFatalErrorHandler {
3281 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003282 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003283 }
3284};
3285}
3286
3287static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3288
Guy Benyei11169dd2012-12-18 14:30:41 +00003289CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3290 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 // We use crash recovery to make some of our APIs more reliable, implicitly
3292 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003293 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3294 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003295
Chandler Carruth66660742014-06-27 16:37:27 +00003296 // Look through the managed static to trigger construction of the managed
3297 // static which registers our fatal error handler. This ensures it is only
3298 // registered once.
3299 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003300
Adrian Prantlbc068582015-07-08 01:00:30 +00003301 // Initialize targets for clang module support.
3302 llvm::InitializeAllTargets();
3303 llvm::InitializeAllTargetMCs();
3304 llvm::InitializeAllAsmPrinters();
3305 llvm::InitializeAllAsmParsers();
3306
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003307 CIndexer *CIdxr = new CIndexer();
3308
Guy Benyei11169dd2012-12-18 14:30:41 +00003309 if (excludeDeclarationsFromPCH)
3310 CIdxr->setOnlyLocalDecls();
3311 if (displayDiagnostics)
3312 CIdxr->setDisplayDiagnostics();
3313
3314 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3315 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3316 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3317 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3318 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3319 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3320
3321 return CIdxr;
3322}
3323
3324void clang_disposeIndex(CXIndex CIdx) {
3325 if (CIdx)
3326 delete static_cast<CIndexer *>(CIdx);
3327}
3328
3329void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3330 if (CIdx)
3331 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3332}
3333
3334unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3335 if (CIdx)
3336 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3337 return 0;
3338}
3339
Alex Lorenz08615792017-12-04 21:56:36 +00003340void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3341 const char *Path) {
3342 if (CIdx)
3343 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3344}
3345
Guy Benyei11169dd2012-12-18 14:30:41 +00003346void clang_toggleCrashRecovery(unsigned isEnabled) {
3347 if (isEnabled)
3348 llvm::CrashRecoveryContext::Enable();
3349 else
3350 llvm::CrashRecoveryContext::Disable();
3351}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003352
Guy Benyei11169dd2012-12-18 14:30:41 +00003353CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3354 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003355 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003356 enum CXErrorCode Result =
3357 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003358 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003359 assert((TU && Result == CXError_Success) ||
3360 (!TU && Result != CXError_Success));
3361 return TU;
3362}
3363
3364enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3365 const char *ast_filename,
3366 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003367 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003368 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003369
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003370 if (!CIdx || !ast_filename || !out_TU)
3371 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003372
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003373 LOG_FUNC_SECTION {
3374 *Log << ast_filename;
3375 }
3376
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3378 FileSystemOptions FileSystemOpts;
3379
Justin Bognerd512c1e2014-10-15 00:33:06 +00003380 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3381 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003382 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003383 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3384 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003385 FileSystemOpts, /*UseDebugInfo=*/false,
3386 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003387 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003388 /*AllowPCHWithCompilerErrors=*/true,
3389 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003390 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003391 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003392}
3393
3394unsigned clang_defaultEditingTranslationUnitOptions() {
3395 return CXTranslationUnit_PrecompiledPreamble |
3396 CXTranslationUnit_CacheCompletionResults;
3397}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003398
Guy Benyei11169dd2012-12-18 14:30:41 +00003399CXTranslationUnit
3400clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3401 const char *source_filename,
3402 int num_command_line_args,
3403 const char * const *command_line_args,
3404 unsigned num_unsaved_files,
3405 struct CXUnsavedFile *unsaved_files) {
3406 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3407 return clang_parseTranslationUnit(CIdx, source_filename,
3408 command_line_args, num_command_line_args,
3409 unsaved_files, num_unsaved_files,
3410 Options);
3411}
3412
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003413static CXErrorCode
3414clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3415 const char *const *command_line_args,
3416 int num_command_line_args,
3417 ArrayRef<CXUnsavedFile> unsaved_files,
3418 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003419 // Set up the initial return values.
3420 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003421 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003422
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003423 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003424 if (!CIdx || !out_TU)
3425 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003426
Guy Benyei11169dd2012-12-18 14:30:41 +00003427 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3428
3429 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3430 setThreadBackgroundPriority();
3431
3432 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003433 bool CreatePreambleOnFirstParse =
3434 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003435 // FIXME: Add a flag for modules.
3436 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003437 = (options & (CXTranslationUnit_Incomplete |
3438 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003439 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003440 = options & CXTranslationUnit_CacheCompletionResults;
3441 bool IncludeBriefCommentsInCodeCompletion
3442 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003443 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3444 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003445 bool RetainExcludedCB = options &
3446 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003447 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3448 if (options & CXTranslationUnit_SkipFunctionBodies) {
3449 SkipFunctionBodies =
3450 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3451 ? SkipFunctionBodiesScope::Preamble
3452 : SkipFunctionBodiesScope::PreambleAndMainFile;
3453 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003454
3455 // Configure the diagnostics.
3456 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003457 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003458
Manuel Klimek016c0242016-03-01 10:56:19 +00003459 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003460 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003461
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003462 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3463 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3464 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3465
Guy Benyei11169dd2012-12-18 14:30:41 +00003466 // Recover resources if we crash before exiting this function.
3467 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3468 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003469 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003470
Ahmed Charlesb8984322014-03-07 20:03:18 +00003471 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3472 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003473
3474 // Recover resources if we crash before exiting this function.
3475 llvm::CrashRecoveryContextCleanupRegistrar<
3476 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3477
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003478 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003479 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003480 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003481 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 }
3483
Ahmed Charlesb8984322014-03-07 20:03:18 +00003484 std::unique_ptr<std::vector<const char *>> Args(
3485 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003486
3487 // Recover resources if we crash before exiting this method.
3488 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3489 ArgsCleanup(Args.get());
3490
3491 // Since the Clang C library is primarily used by batch tools dealing with
3492 // (often very broken) source code, where spell-checking can have a
3493 // significant negative impact on performance (particularly when
3494 // precompiled headers are involved), we disable it by default.
3495 // Only do this if we haven't found a spell-checking-related argument.
3496 bool FoundSpellCheckingArgument = false;
3497 for (int I = 0; I != num_command_line_args; ++I) {
3498 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3499 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3500 FoundSpellCheckingArgument = true;
3501 break;
3502 }
3503 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003504 Args->insert(Args->end(), command_line_args,
3505 command_line_args + num_command_line_args);
3506
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003507 if (!FoundSpellCheckingArgument)
3508 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3509
Guy Benyei11169dd2012-12-18 14:30:41 +00003510 // The 'source_filename' argument is optional. If the caller does not
3511 // specify it then it is assumed that the source file is specified
3512 // in the actual argument list.
3513 // Put the source file after command_line_args otherwise if '-x' flag is
3514 // present it will be unused.
3515 if (source_filename)
3516 Args->push_back(source_filename);
3517
3518 // Do we need the detailed preprocessing record?
3519 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3520 Args->push_back("-Xclang");
3521 Args->push_back("-detailed-preprocessing-record");
3522 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003523
3524 // Suppress any editor placeholder diagnostics.
3525 Args->push_back("-fallow-editor-placeholders");
3526
Guy Benyei11169dd2012-12-18 14:30:41 +00003527 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003528 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003529 // Unless the user specified that they want the preamble on the first parse
3530 // set it up to be created on the first reparse. This makes the first parse
3531 // faster, trading for a slower (first) reparse.
3532 unsigned PrecompilePreambleAfterNParses =
3533 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003534
Alex Lorenz08615792017-12-04 21:56:36 +00003535 LibclangInvocationReporter InvocationReporter(
3536 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003537 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3538 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003539 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003540 Args->data(), Args->data() + Args->size(),
3541 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003542 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003543 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003544 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3545 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003546 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003547 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003548 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3549 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003550
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003551 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003552 if (!Unit && !ErrUnit)
3553 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003554
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 if (NumErrors != Diags->getClient()->getNumErrors()) {
3556 // Make sure to check that 'Unit' is non-NULL.
3557 if (CXXIdx->getDisplayDiagnostics())
3558 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3559 }
3560
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003561 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3562 return CXError_ASTReadError;
3563
David Blaikieea4395e2017-01-06 19:49:01 +00003564 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003565 if (CXTranslationUnitImpl *TU = *out_TU) {
3566 TU->ParsingOptions = options;
3567 TU->Arguments.reserve(Args->size());
3568 for (const char *Arg : *Args)
3569 TU->Arguments.push_back(Arg);
3570 return CXError_Success;
3571 }
3572 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003573}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003574
3575CXTranslationUnit
3576clang_parseTranslationUnit(CXIndex CIdx,
3577 const char *source_filename,
3578 const char *const *command_line_args,
3579 int num_command_line_args,
3580 struct CXUnsavedFile *unsaved_files,
3581 unsigned num_unsaved_files,
3582 unsigned options) {
3583 CXTranslationUnit TU;
3584 enum CXErrorCode Result = clang_parseTranslationUnit2(
3585 CIdx, source_filename, command_line_args, num_command_line_args,
3586 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003587 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003588 assert((TU && Result == CXError_Success) ||
3589 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003590 return TU;
3591}
3592
3593enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003594 CXIndex CIdx, const char *source_filename,
3595 const char *const *command_line_args, int num_command_line_args,
3596 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3597 unsigned options, CXTranslationUnit *out_TU) {
3598 SmallVector<const char *, 4> Args;
3599 Args.push_back("clang");
3600 Args.append(command_line_args, command_line_args + num_command_line_args);
3601 return clang_parseTranslationUnit2FullArgv(
3602 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3603 num_unsaved_files, options, out_TU);
3604}
3605
3606enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3607 CXIndex CIdx, const char *source_filename,
3608 const char *const *command_line_args, int num_command_line_args,
3609 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3610 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003611 LOG_FUNC_SECTION {
3612 *Log << source_filename << ": ";
3613 for (int i = 0; i != num_command_line_args; ++i)
3614 *Log << command_line_args[i] << " ";
3615 }
3616
Alp Toker9d85b182014-07-07 01:23:14 +00003617 if (num_unsaved_files && !unsaved_files)
3618 return CXError_InvalidArguments;
3619
Alp Toker5c532982014-07-07 22:42:03 +00003620 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003621 auto ParseTranslationUnitImpl = [=, &result] {
3622 result = clang_parseTranslationUnit_Impl(
3623 CIdx, source_filename, command_line_args, num_command_line_args,
3624 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3625 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003626
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 llvm::CrashRecoveryContext CRC;
3628
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003629 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3631 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3632 fprintf(stderr, " 'command_line_args' : [");
3633 for (int i = 0; i != num_command_line_args; ++i) {
3634 if (i)
3635 fprintf(stderr, ", ");
3636 fprintf(stderr, "'%s'", command_line_args[i]);
3637 }
3638 fprintf(stderr, "],\n");
3639 fprintf(stderr, " 'unsaved_files' : [");
3640 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3641 if (i)
3642 fprintf(stderr, ", ");
3643 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3644 unsaved_files[i].Length);
3645 }
3646 fprintf(stderr, "],\n");
3647 fprintf(stderr, " 'options' : %d,\n", options);
3648 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003649
3650 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003651 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003652 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003653 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 }
Alp Toker5c532982014-07-07 22:42:03 +00003655
3656 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003657}
3658
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003659CXString clang_Type_getObjCEncoding(CXType CT) {
3660 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3661 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3662 std::string encoding;
3663 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3664 encoding);
3665
3666 return cxstring::createDup(encoding);
3667}
3668
3669static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3670 if (C.kind == CXCursor_MacroDefinition) {
3671 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3672 return MDR->getName();
3673 } else if (C.kind == CXCursor_MacroExpansion) {
3674 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3675 return ME.getName();
3676 }
3677 return nullptr;
3678}
3679
3680unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3681 const IdentifierInfo *II = getMacroIdentifier(C);
3682 if (!II) {
3683 return false;
3684 }
3685 ASTUnit *ASTU = getCursorASTUnit(C);
3686 Preprocessor &PP = ASTU->getPreprocessor();
3687 if (const MacroInfo *MI = PP.getMacroInfo(II))
3688 return MI->isFunctionLike();
3689 return false;
3690}
3691
3692unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3693 const IdentifierInfo *II = getMacroIdentifier(C);
3694 if (!II) {
3695 return false;
3696 }
3697 ASTUnit *ASTU = getCursorASTUnit(C);
3698 Preprocessor &PP = ASTU->getPreprocessor();
3699 if (const MacroInfo *MI = PP.getMacroInfo(II))
3700 return MI->isBuiltinMacro();
3701 return false;
3702}
3703
3704unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3705 const Decl *D = getCursorDecl(C);
3706 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3707 if (!FD) {
3708 return false;
3709 }
3710 return FD->isInlined();
3711}
3712
3713static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3714 if (callExpr->getNumArgs() != 1) {
3715 return nullptr;
3716 }
3717
3718 StringLiteral *S = nullptr;
3719 auto *arg = callExpr->getArg(0);
3720 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3721 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3722 auto *subExpr = I->getSubExprAsWritten();
3723
3724 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3725 return nullptr;
3726 }
3727
3728 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3729 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3730 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3731 } else {
3732 return nullptr;
3733 }
3734 return S;
3735}
3736
David Blaikie59272572016-04-13 18:23:33 +00003737struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003738 CXEvalResultKind EvalType;
3739 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003740 unsigned long long unsignedVal;
3741 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003742 double floatVal;
3743 char *stringVal;
3744 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003745 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003746 ~ExprEvalResult() {
3747 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3748 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003749 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003750 }
3751 }
3752};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003753
3754void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003755 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003756}
3757
3758CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3759 if (!E) {
3760 return CXEval_UnExposed;
3761 }
3762 return ((ExprEvalResult *)E)->EvalType;
3763}
3764
3765int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003766 return clang_EvalResult_getAsLongLong(E);
3767}
3768
3769long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003770 if (!E) {
3771 return 0;
3772 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003773 ExprEvalResult *Result = (ExprEvalResult*)E;
3774 if (Result->IsUnsignedInt)
3775 return Result->EvalData.unsignedVal;
3776 return Result->EvalData.intVal;
3777}
3778
3779unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3780 return ((ExprEvalResult *)E)->IsUnsignedInt;
3781}
3782
3783unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3784 if (!E) {
3785 return 0;
3786 }
3787
3788 ExprEvalResult *Result = (ExprEvalResult*)E;
3789 if (Result->IsUnsignedInt)
3790 return Result->EvalData.unsignedVal;
3791 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003792}
3793
3794double clang_EvalResult_getAsDouble(CXEvalResult E) {
3795 if (!E) {
3796 return 0;
3797 }
3798 return ((ExprEvalResult *)E)->EvalData.floatVal;
3799}
3800
3801const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3802 if (!E) {
3803 return nullptr;
3804 }
3805 return ((ExprEvalResult *)E)->EvalData.stringVal;
3806}
3807
3808static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3809 Expr::EvalResult ER;
3810 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003811 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003812 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003813
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003814 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003815 if (expr->isValueDependent())
3816 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003817 if (!expr->EvaluateAsRValue(ER, ctx))
3818 return nullptr;
3819
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003820 QualType rettype;
3821 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003822 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003823 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003824 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003825
David Blaikiebbc00882016-04-13 18:36:19 +00003826 if (ER.Val.isInt()) {
3827 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003828
3829 auto& val = ER.Val.getInt();
3830 if (val.isUnsigned()) {
3831 result->IsUnsignedInt = true;
3832 result->EvalData.unsignedVal = val.getZExtValue();
3833 } else {
3834 result->EvalData.intVal = val.getExtValue();
3835 }
3836
David Blaikiebbc00882016-04-13 18:36:19 +00003837 return result.release();
3838 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003839
David Blaikiebbc00882016-04-13 18:36:19 +00003840 if (ER.Val.isFloat()) {
3841 llvm::SmallVector<char, 100> Buffer;
3842 ER.Val.getFloat().toString(Buffer);
3843 std::string floatStr(Buffer.data(), Buffer.size());
3844 result->EvalType = CXEval_Float;
3845 bool ignored;
3846 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003847 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003848 llvm::APFloat::rmNearestTiesToEven, &ignored);
3849 result->EvalData.floatVal = apFloat.convertToDouble();
3850 return result.release();
3851 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003852
David Blaikiebbc00882016-04-13 18:36:19 +00003853 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3854 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3855 auto *subExpr = I->getSubExprAsWritten();
3856 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3857 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003858 const StringLiteral *StrE = nullptr;
3859 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003860 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003861
3862 if (ObjCExpr) {
3863 StrE = ObjCExpr->getString();
3864 result->EvalType = CXEval_ObjCStrLiteral;
3865 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003866 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003867 result->EvalType = CXEval_StrLiteral;
3868 }
3869
3870 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003871 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003872 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3873 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003874 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003875 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003876 }
3877 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3878 expr->getStmtClass() == Stmt::StringLiteralClass) {
3879 const StringLiteral *StrE = nullptr;
3880 const ObjCStringLiteral *ObjCExpr;
3881 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003882
David Blaikiebbc00882016-04-13 18:36:19 +00003883 if (ObjCExpr) {
3884 StrE = ObjCExpr->getString();
3885 result->EvalType = CXEval_ObjCStrLiteral;
3886 } else {
3887 StrE = cast<StringLiteral>(expr);
3888 result->EvalType = CXEval_StrLiteral;
3889 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003890
David Blaikiebbc00882016-04-13 18:36:19 +00003891 std::string strRef(StrE->getString().str());
3892 result->EvalData.stringVal = new char[strRef.size() + 1];
3893 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3894 result->EvalData.stringVal[strRef.size()] = '\0';
3895 return result.release();
3896 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003897
David Blaikiebbc00882016-04-13 18:36:19 +00003898 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3899 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003900
David Blaikiebbc00882016-04-13 18:36:19 +00003901 rettype = CC->getType();
3902 if (rettype.getAsString() == "CFStringRef" &&
3903 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003904
David Blaikiebbc00882016-04-13 18:36:19 +00003905 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3906 StringLiteral *S = getCFSTR_value(callExpr);
3907 if (S) {
3908 std::string strLiteral(S->getString().str());
3909 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003910
David Blaikiebbc00882016-04-13 18:36:19 +00003911 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3912 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3913 strLiteral.size());
3914 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003915 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003916 }
3917 }
3918
David Blaikiebbc00882016-04-13 18:36:19 +00003919 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3920 callExpr = static_cast<CallExpr *>(expr);
3921 rettype = callExpr->getCallReturnType(ctx);
3922
3923 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3924 return nullptr;
3925
3926 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3927 if (callExpr->getNumArgs() == 1 &&
3928 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3929 return nullptr;
3930 } else if (rettype.getAsString() == "CFStringRef") {
3931
3932 StringLiteral *S = getCFSTR_value(callExpr);
3933 if (S) {
3934 std::string strLiteral(S->getString().str());
3935 result->EvalType = CXEval_CFStr;
3936 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3937 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3938 strLiteral.size());
3939 result->EvalData.stringVal[strLiteral.size()] = '\0';
3940 return result.release();
3941 }
3942 }
3943 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3944 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3945 ValueDecl *V = D->getDecl();
3946 if (V->getKind() == Decl::Function) {
3947 std::string strName = V->getNameAsString();
3948 result->EvalType = CXEval_Other;
3949 result->EvalData.stringVal = new char[strName.size() + 1];
3950 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3951 result->EvalData.stringVal[strName.size()] = '\0';
3952 return result.release();
3953 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003954 }
3955
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003956 return nullptr;
3957}
3958
Alex Lorenz65317e12019-01-08 22:32:51 +00003959static const Expr *evaluateDeclExpr(const Decl *D) {
3960 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003961 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003962 if (auto *Var = dyn_cast<VarDecl>(D))
3963 return Var->getInit();
3964 else if (auto *Field = dyn_cast<FieldDecl>(D))
3965 return Field->getInClassInitializer();
3966 return nullptr;
3967}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003968
Alex Lorenz65317e12019-01-08 22:32:51 +00003969static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3970 assert(CS && "invalid compound statement");
3971 for (auto *bodyIterator : CS->body()) {
3972 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3973 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003974 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003975 return nullptr;
3976}
3977
Alex Lorenz65317e12019-01-08 22:32:51 +00003978CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3979 if (const Expr *E =
3980 clang_getCursorKind(C) == CXCursor_CompoundStmt
3981 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3982 : evaluateDeclExpr(getCursorDecl(C)))
3983 return const_cast<CXEvalResult>(
3984 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3985 return nullptr;
3986}
3987
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003988unsigned clang_Cursor_hasAttrs(CXCursor C) {
3989 const Decl *D = getCursorDecl(C);
3990 if (!D) {
3991 return 0;
3992 }
3993
3994 if (D->hasAttrs()) {
3995 return 1;
3996 }
3997
3998 return 0;
3999}
Guy Benyei11169dd2012-12-18 14:30:41 +00004000unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4001 return CXSaveTranslationUnit_None;
4002}
4003
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004004static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4005 const char *FileName,
4006 unsigned options) {
4007 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004008 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4009 setThreadBackgroundPriority();
4010
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004011 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4012 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004013}
4014
4015int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4016 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004017 LOG_FUNC_SECTION {
4018 *Log << TU << ' ' << FileName;
4019 }
4020
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004021 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004022 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004024 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004025
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004026 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004027 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4028 if (!CXXUnit->hasSema())
4029 return CXSaveError_InvalidTU;
4030
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004031 CXSaveError result;
4032 auto SaveTranslationUnitImpl = [=, &result]() {
4033 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4034 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004035
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004036 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004037 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004038
4039 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4040 PrintLibclangResourceUsage(TU);
4041
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004042 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 }
4044
4045 // We have an AST that has invalid nodes due to compiler errors.
4046 // Use a crash recovery thread for protection.
4047
4048 llvm::CrashRecoveryContext CRC;
4049
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004050 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004051 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4052 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4053 fprintf(stderr, " 'options' : %d,\n", options);
4054 fprintf(stderr, "}\n");
4055
4056 return CXSaveError_Unknown;
4057
4058 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4059 PrintLibclangResourceUsage(TU);
4060 }
4061
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004062 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004063}
4064
4065void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4066 if (CTUnit) {
4067 // If the translation unit has been marked as unsafe to free, just discard
4068 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004069 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4070 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004071 return;
4072
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004073 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004074 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4076 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004077 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 delete CTUnit;
4079 }
4080}
4081
Erik Verbruggen346066b2017-05-30 14:25:54 +00004082unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4083 if (CTUnit) {
4084 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4085
4086 if (Unit && Unit->isUnsafeToFree())
4087 return false;
4088
4089 Unit->ResetForParse();
4090 return true;
4091 }
4092
4093 return false;
4094}
4095
Guy Benyei11169dd2012-12-18 14:30:41 +00004096unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4097 return CXReparse_None;
4098}
4099
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004100static CXErrorCode
4101clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4102 ArrayRef<CXUnsavedFile> unsaved_files,
4103 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004104 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004105 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004106 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004107 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004108 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004109
4110 // Reset the associated diagnostics.
4111 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004112 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004113
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004114 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4116 setThreadBackgroundPriority();
4117
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004118 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004119 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004120
4121 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4122 new std::vector<ASTUnit::RemappedFile>());
4123
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 // Recover resources if we crash before exiting this function.
4125 llvm::CrashRecoveryContextCleanupRegistrar<
4126 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004127
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004128 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004129 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004130 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004131 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004132 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004133
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004134 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4135 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004136 return CXError_Success;
4137 if (isASTReadError(CXXUnit))
4138 return CXError_ASTReadError;
4139 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004140}
4141
4142int clang_reparseTranslationUnit(CXTranslationUnit TU,
4143 unsigned num_unsaved_files,
4144 struct CXUnsavedFile *unsaved_files,
4145 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004146 LOG_FUNC_SECTION {
4147 *Log << TU;
4148 }
4149
Alp Toker9d85b182014-07-07 01:23:14 +00004150 if (num_unsaved_files && !unsaved_files)
4151 return CXError_InvalidArguments;
4152
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004153 CXErrorCode result;
4154 auto ReparseTranslationUnitImpl = [=, &result]() {
4155 result = clang_reparseTranslationUnit_Impl(
4156 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4157 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004158
Guy Benyei11169dd2012-12-18 14:30:41 +00004159 llvm::CrashRecoveryContext CRC;
4160
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004161 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004163 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004164 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004165 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4166 PrintLibclangResourceUsage(TU);
4167
Alp Toker5c532982014-07-07 22:42:03 +00004168 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004169}
4170
4171
4172CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004173 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004174 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004175 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004176 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004177
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004178 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004179 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004180}
4181
4182CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004183 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004184 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004185 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004186 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004187
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004188 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004189 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4190}
4191
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004192CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4193 if (isNotUsableTU(CTUnit)) {
4194 LOG_BAD_TU(CTUnit);
4195 return nullptr;
4196 }
4197
4198 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4199 impl->TranslationUnit = CTUnit;
4200 return impl;
4201}
4202
4203CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4204 if (!TargetInfo)
4205 return cxstring::createEmpty();
4206
4207 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4208 assert(!isNotUsableTU(CTUnit) &&
4209 "Unexpected unusable translation unit in TargetInfo");
4210
4211 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4212 std::string Triple =
4213 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4214 return cxstring::createDup(Triple);
4215}
4216
4217int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4218 if (!TargetInfo)
4219 return -1;
4220
4221 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4222 assert(!isNotUsableTU(CTUnit) &&
4223 "Unexpected unusable translation unit in TargetInfo");
4224
4225 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4226 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4227}
4228
4229void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4230 if (!TargetInfo)
4231 return;
4232
4233 delete TargetInfo;
4234}
4235
Guy Benyei11169dd2012-12-18 14:30:41 +00004236//===----------------------------------------------------------------------===//
4237// CXFile Operations.
4238//===----------------------------------------------------------------------===//
4239
Guy Benyei11169dd2012-12-18 14:30:41 +00004240CXString clang_getFileName(CXFile SFile) {
4241 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004242 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004243
4244 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004245 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004246}
4247
4248time_t clang_getFileTime(CXFile SFile) {
4249 if (!SFile)
4250 return 0;
4251
4252 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4253 return FEnt->getModificationTime();
4254}
4255
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004256CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004257 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004258 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004259 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004260 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004261
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004262 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004263
4264 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004265 auto File = FMgr.getFile(file_name);
4266 if (!File)
4267 return nullptr;
4268 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004269}
4270
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004271const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4272 size_t *size) {
4273 if (isNotUsableTU(TU)) {
4274 LOG_BAD_TU(TU);
4275 return nullptr;
4276 }
4277
4278 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4279 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4280 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004281 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004282 if (Invalid) {
4283 if (size)
4284 *size = 0;
4285 return nullptr;
4286 }
4287 if (size)
4288 *size = buf->getBufferSize();
4289 return buf->getBufferStart();
4290}
4291
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004292unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4293 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004294 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004295 LOG_BAD_TU(TU);
4296 return 0;
4297 }
4298
4299 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 return 0;
4301
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004302 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 FileEntry *FEnt = static_cast<FileEntry *>(file);
4304 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4305 .isFileMultipleIncludeGuarded(FEnt);
4306}
4307
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004308int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4309 if (!file || !outID)
4310 return 1;
4311
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004312 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004313 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4314 outID->data[0] = ID.getDevice();
4315 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004316 outID->data[2] = FEnt->getModificationTime();
4317 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004318}
4319
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004320int clang_File_isEqual(CXFile file1, CXFile file2) {
4321 if (file1 == file2)
4322 return true;
4323
4324 if (!file1 || !file2)
4325 return false;
4326
4327 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4328 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4329 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4330}
4331
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004332CXString clang_File_tryGetRealPathName(CXFile SFile) {
4333 if (!SFile)
4334 return cxstring::createNull();
4335
4336 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4337 return cxstring::createRef(FEnt->tryGetRealPathName());
4338}
4339
Guy Benyei11169dd2012-12-18 14:30:41 +00004340//===----------------------------------------------------------------------===//
4341// CXCursor Operations.
4342//===----------------------------------------------------------------------===//
4343
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004344static const Decl *getDeclFromExpr(const Stmt *E) {
4345 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 return getDeclFromExpr(CE->getSubExpr());
4347
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004348 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004350 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004352 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004354 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 if (PRE->isExplicitProperty())
4356 return PRE->getExplicitProperty();
4357 // It could be messaging both getter and setter as in:
4358 // ++myobj.myprop;
4359 // in which case prefer to associate the setter since it is less obvious
4360 // from inspecting the source that the setter is going to get called.
4361 if (PRE->isMessagingSetter())
4362 return PRE->getImplicitPropertySetter();
4363 return PRE->getImplicitPropertyGetter();
4364 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004365 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004367 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 if (Expr *Src = OVE->getSourceExpr())
4369 return getDeclFromExpr(Src);
4370
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004371 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004373 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 if (!CE->isElidable())
4375 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004376 if (const CXXInheritedCtorInitExpr *CE =
4377 dyn_cast<CXXInheritedCtorInitExpr>(E))
4378 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004379 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 return OME->getMethodDecl();
4381
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004382 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004384 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4386 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004387 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4389 isa<ParmVarDecl>(SizeOfPack->getPack()))
4390 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004391
4392 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004393}
4394
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004395static SourceLocation getLocationFromExpr(const Expr *E) {
4396 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 return getLocationFromExpr(CE->getSubExpr());
4398
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004399 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004401 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004403 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004405 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004407 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004408 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004409 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004411
4412 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004413}
4414
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004415extern "C" {
4416
Guy Benyei11169dd2012-12-18 14:30:41 +00004417unsigned clang_visitChildren(CXCursor parent,
4418 CXCursorVisitor visitor,
4419 CXClientData client_data) {
4420 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4421 /*VisitPreprocessorLast=*/false);
4422 return CursorVis.VisitChildren(parent);
4423}
4424
4425#ifndef __has_feature
4426#define __has_feature(x) 0
4427#endif
4428#if __has_feature(blocks)
4429typedef enum CXChildVisitResult
4430 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4431
4432static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4433 CXClientData client_data) {
4434 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4435 return block(cursor, parent);
4436}
4437#else
4438// If we are compiled with a compiler that doesn't have native blocks support,
4439// define and call the block manually, so the
4440typedef struct _CXChildVisitResult
4441{
4442 void *isa;
4443 int flags;
4444 int reserved;
4445 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4446 CXCursor);
4447} *CXCursorVisitorBlock;
4448
4449static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4450 CXClientData client_data) {
4451 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4452 return block->invoke(block, cursor, parent);
4453}
4454#endif
4455
4456
4457unsigned clang_visitChildrenWithBlock(CXCursor parent,
4458 CXCursorVisitorBlock block) {
4459 return clang_visitChildren(parent, visitWithBlock, block);
4460}
4461
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004462static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004464 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004465
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004466 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004468 if (const ObjCPropertyImplDecl *PropImpl =
4469 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004471 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004472
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004473 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004475 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004476
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004477 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 }
4479
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004480 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004481 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004482
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004483 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4485 // and returns different names. NamedDecl returns the class name and
4486 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004487 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004488
4489 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004490 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004491
4492 SmallString<1024> S;
4493 llvm::raw_svector_ostream os(S);
4494 ND->printName(os);
4495
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004496 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004497}
4498
4499CXString clang_getCursorSpelling(CXCursor C) {
4500 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004501 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004502
4503 if (clang_isReference(C.kind)) {
4504 switch (C.kind) {
4505 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004506 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004507 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 }
4509 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004510 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004511 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 }
4513 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004514 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004516 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 }
4518 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004519 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004520 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 }
4522 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004523 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 assert(Type && "Missing type decl");
4525
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004526 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 getAsString());
4528 }
4529 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004530 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 assert(Template && "Missing template decl");
4532
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004533 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 }
4535
4536 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004537 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 assert(NS && "Missing namespace decl");
4539
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004540 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 }
4542
4543 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004544 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 assert(Field && "Missing member decl");
4546
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004547 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 }
4549
4550 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004551 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004552 assert(Label && "Missing label");
4553
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004554 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 }
4556
4557 case CXCursor_OverloadedDeclRef: {
4558 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004559 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4560 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004561 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004562 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004564 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004565 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 OverloadedTemplateStorage *Ovl
4567 = Storage.get<OverloadedTemplateStorage*>();
4568 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004569 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004570 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 }
4572
4573 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004574 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 assert(Var && "Missing variable decl");
4576
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004577 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 }
4579
4580 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004581 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 }
4583 }
4584
4585 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004586 const Expr *E = getCursorExpr(C);
4587
4588 if (C.kind == CXCursor_ObjCStringLiteral ||
4589 C.kind == CXCursor_StringLiteral) {
4590 const StringLiteral *SLit;
4591 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4592 SLit = OSL->getString();
4593 } else {
4594 SLit = cast<StringLiteral>(E);
4595 }
4596 SmallString<256> Buf;
4597 llvm::raw_svector_ostream OS(Buf);
4598 SLit->outputString(OS);
4599 return cxstring::createDup(OS.str());
4600 }
4601
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004602 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 if (D)
4604 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004605 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 }
4607
4608 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004609 const Stmt *S = getCursorStmt(C);
4610 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004611 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004612
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004613 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 }
4615
4616 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004617 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 ->getNameStart());
4619
4620 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004621 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 ->getNameStart());
4623
4624 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004625 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004626
4627 if (clang_isDeclaration(C.kind))
4628 return getDeclSpelling(getCursorDecl(C));
4629
4630 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004631 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004632 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 }
4634
4635 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004636 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004637 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 }
4639
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004640 if (C.kind == CXCursor_PackedAttr) {
4641 return cxstring::createRef("packed");
4642 }
4643
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004644 if (C.kind == CXCursor_VisibilityAttr) {
4645 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4646 switch (AA->getVisibility()) {
4647 case VisibilityAttr::VisibilityType::Default:
4648 return cxstring::createRef("default");
4649 case VisibilityAttr::VisibilityType::Hidden:
4650 return cxstring::createRef("hidden");
4651 case VisibilityAttr::VisibilityType::Protected:
4652 return cxstring::createRef("protected");
4653 }
4654 llvm_unreachable("unknown visibility type");
4655 }
4656
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004657 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004658}
4659
4660CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4661 unsigned pieceIndex,
4662 unsigned options) {
4663 if (clang_Cursor_isNull(C))
4664 return clang_getNullRange();
4665
4666 ASTContext &Ctx = getCursorContext(C);
4667
4668 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004669 const Stmt *S = getCursorStmt(C);
4670 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 if (pieceIndex > 0)
4672 return clang_getNullRange();
4673 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4674 }
4675
4676 return clang_getNullRange();
4677 }
4678
4679 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004680 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4682 if (pieceIndex >= ME->getNumSelectorLocs())
4683 return clang_getNullRange();
4684 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4685 }
4686 }
4687
4688 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4689 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004690 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4692 if (pieceIndex >= MD->getNumSelectorLocs())
4693 return clang_getNullRange();
4694 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4695 }
4696 }
4697
4698 if (C.kind == CXCursor_ObjCCategoryDecl ||
4699 C.kind == CXCursor_ObjCCategoryImplDecl) {
4700 if (pieceIndex > 0)
4701 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004702 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4704 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004705 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004706 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4707 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4708 }
4709
4710 if (C.kind == CXCursor_ModuleImportDecl) {
4711 if (pieceIndex > 0)
4712 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004713 if (const ImportDecl *ImportD =
4714 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4716 if (!Locs.empty())
4717 return cxloc::translateSourceRange(Ctx,
4718 SourceRange(Locs.front(), Locs.back()));
4719 }
4720 return clang_getNullRange();
4721 }
4722
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004723 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004724 C.kind == CXCursor_ConversionFunction ||
4725 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004726 if (pieceIndex > 0)
4727 return clang_getNullRange();
4728 if (const FunctionDecl *FD =
4729 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4730 DeclarationNameInfo FunctionName = FD->getNameInfo();
4731 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4732 }
4733 return clang_getNullRange();
4734 }
4735
Guy Benyei11169dd2012-12-18 14:30:41 +00004736 // FIXME: A CXCursor_InclusionDirective should give the location of the
4737 // filename, but we don't keep track of this.
4738
4739 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4740 // but we don't keep track of this.
4741
4742 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4743 // but we don't keep track of this.
4744
4745 // Default handling, give the location of the cursor.
4746
4747 if (pieceIndex > 0)
4748 return clang_getNullRange();
4749
4750 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4751 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4752 return cxloc::translateSourceRange(Ctx, Loc);
4753}
4754
Eli Bendersky44a206f2014-07-31 18:04:56 +00004755CXString clang_Cursor_getMangling(CXCursor C) {
4756 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4757 return cxstring::createEmpty();
4758
Eli Bendersky44a206f2014-07-31 18:04:56 +00004759 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004760 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004761 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4762 return cxstring::createEmpty();
4763
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004764 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004765 ASTNameGenerator ASTNameGen(Ctx);
4766 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004767}
4768
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004769CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4770 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4771 return nullptr;
4772
4773 const Decl *D = getCursorDecl(C);
4774 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4775 return nullptr;
4776
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004777 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004778 ASTNameGenerator ASTNameGen(Ctx);
4779 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004780 return cxstring::createSet(Manglings);
4781}
4782
Dave Lee1a532c92017-09-22 16:58:57 +00004783CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4784 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4785 return nullptr;
4786
4787 const Decl *D = getCursorDecl(C);
4788 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4789 return nullptr;
4790
4791 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004792 ASTNameGenerator ASTNameGen(Ctx);
4793 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004794 return cxstring::createSet(Manglings);
4795}
4796
Jonathan Coe45ef5032018-01-16 10:19:56 +00004797CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4798 if (clang_Cursor_isNull(C))
4799 return 0;
4800 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4801}
4802
4803void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4804 if (Policy)
4805 delete static_cast<PrintingPolicy *>(Policy);
4806}
4807
4808unsigned
4809clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4810 enum CXPrintingPolicyProperty Property) {
4811 if (!Policy)
4812 return 0;
4813
4814 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4815 switch (Property) {
4816 case CXPrintingPolicy_Indentation:
4817 return P->Indentation;
4818 case CXPrintingPolicy_SuppressSpecifiers:
4819 return P->SuppressSpecifiers;
4820 case CXPrintingPolicy_SuppressTagKeyword:
4821 return P->SuppressTagKeyword;
4822 case CXPrintingPolicy_IncludeTagDefinition:
4823 return P->IncludeTagDefinition;
4824 case CXPrintingPolicy_SuppressScope:
4825 return P->SuppressScope;
4826 case CXPrintingPolicy_SuppressUnwrittenScope:
4827 return P->SuppressUnwrittenScope;
4828 case CXPrintingPolicy_SuppressInitializers:
4829 return P->SuppressInitializers;
4830 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4831 return P->ConstantArraySizeAsWritten;
4832 case CXPrintingPolicy_AnonymousTagLocations:
4833 return P->AnonymousTagLocations;
4834 case CXPrintingPolicy_SuppressStrongLifetime:
4835 return P->SuppressStrongLifetime;
4836 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4837 return P->SuppressLifetimeQualifiers;
4838 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4839 return P->SuppressTemplateArgsInCXXConstructors;
4840 case CXPrintingPolicy_Bool:
4841 return P->Bool;
4842 case CXPrintingPolicy_Restrict:
4843 return P->Restrict;
4844 case CXPrintingPolicy_Alignof:
4845 return P->Alignof;
4846 case CXPrintingPolicy_UnderscoreAlignof:
4847 return P->UnderscoreAlignof;
4848 case CXPrintingPolicy_UseVoidForZeroParams:
4849 return P->UseVoidForZeroParams;
4850 case CXPrintingPolicy_TerseOutput:
4851 return P->TerseOutput;
4852 case CXPrintingPolicy_PolishForDeclaration:
4853 return P->PolishForDeclaration;
4854 case CXPrintingPolicy_Half:
4855 return P->Half;
4856 case CXPrintingPolicy_MSWChar:
4857 return P->MSWChar;
4858 case CXPrintingPolicy_IncludeNewlines:
4859 return P->IncludeNewlines;
4860 case CXPrintingPolicy_MSVCFormatting:
4861 return P->MSVCFormatting;
4862 case CXPrintingPolicy_ConstantsAsWritten:
4863 return P->ConstantsAsWritten;
4864 case CXPrintingPolicy_SuppressImplicitBase:
4865 return P->SuppressImplicitBase;
4866 case CXPrintingPolicy_FullyQualifiedName:
4867 return P->FullyQualifiedName;
4868 }
4869
4870 assert(false && "Invalid CXPrintingPolicyProperty");
4871 return 0;
4872}
4873
4874void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4875 enum CXPrintingPolicyProperty Property,
4876 unsigned Value) {
4877 if (!Policy)
4878 return;
4879
4880 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4881 switch (Property) {
4882 case CXPrintingPolicy_Indentation:
4883 P->Indentation = Value;
4884 return;
4885 case CXPrintingPolicy_SuppressSpecifiers:
4886 P->SuppressSpecifiers = Value;
4887 return;
4888 case CXPrintingPolicy_SuppressTagKeyword:
4889 P->SuppressTagKeyword = Value;
4890 return;
4891 case CXPrintingPolicy_IncludeTagDefinition:
4892 P->IncludeTagDefinition = Value;
4893 return;
4894 case CXPrintingPolicy_SuppressScope:
4895 P->SuppressScope = Value;
4896 return;
4897 case CXPrintingPolicy_SuppressUnwrittenScope:
4898 P->SuppressUnwrittenScope = Value;
4899 return;
4900 case CXPrintingPolicy_SuppressInitializers:
4901 P->SuppressInitializers = Value;
4902 return;
4903 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4904 P->ConstantArraySizeAsWritten = Value;
4905 return;
4906 case CXPrintingPolicy_AnonymousTagLocations:
4907 P->AnonymousTagLocations = Value;
4908 return;
4909 case CXPrintingPolicy_SuppressStrongLifetime:
4910 P->SuppressStrongLifetime = Value;
4911 return;
4912 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4913 P->SuppressLifetimeQualifiers = Value;
4914 return;
4915 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4916 P->SuppressTemplateArgsInCXXConstructors = Value;
4917 return;
4918 case CXPrintingPolicy_Bool:
4919 P->Bool = Value;
4920 return;
4921 case CXPrintingPolicy_Restrict:
4922 P->Restrict = Value;
4923 return;
4924 case CXPrintingPolicy_Alignof:
4925 P->Alignof = Value;
4926 return;
4927 case CXPrintingPolicy_UnderscoreAlignof:
4928 P->UnderscoreAlignof = Value;
4929 return;
4930 case CXPrintingPolicy_UseVoidForZeroParams:
4931 P->UseVoidForZeroParams = Value;
4932 return;
4933 case CXPrintingPolicy_TerseOutput:
4934 P->TerseOutput = Value;
4935 return;
4936 case CXPrintingPolicy_PolishForDeclaration:
4937 P->PolishForDeclaration = Value;
4938 return;
4939 case CXPrintingPolicy_Half:
4940 P->Half = Value;
4941 return;
4942 case CXPrintingPolicy_MSWChar:
4943 P->MSWChar = Value;
4944 return;
4945 case CXPrintingPolicy_IncludeNewlines:
4946 P->IncludeNewlines = Value;
4947 return;
4948 case CXPrintingPolicy_MSVCFormatting:
4949 P->MSVCFormatting = Value;
4950 return;
4951 case CXPrintingPolicy_ConstantsAsWritten:
4952 P->ConstantsAsWritten = Value;
4953 return;
4954 case CXPrintingPolicy_SuppressImplicitBase:
4955 P->SuppressImplicitBase = Value;
4956 return;
4957 case CXPrintingPolicy_FullyQualifiedName:
4958 P->FullyQualifiedName = Value;
4959 return;
4960 }
4961
4962 assert(false && "Invalid CXPrintingPolicyProperty");
4963}
4964
4965CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4966 if (clang_Cursor_isNull(C))
4967 return cxstring::createEmpty();
4968
4969 if (clang_isDeclaration(C.kind)) {
4970 const Decl *D = getCursorDecl(C);
4971 if (!D)
4972 return cxstring::createEmpty();
4973
4974 SmallString<128> Str;
4975 llvm::raw_svector_ostream OS(Str);
4976 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4977 D->print(OS, UserPolicy ? *UserPolicy
4978 : getCursorContext(C).getPrintingPolicy());
4979
4980 return cxstring::createDup(OS.str());
4981 }
4982
4983 return cxstring::createEmpty();
4984}
4985
Guy Benyei11169dd2012-12-18 14:30:41 +00004986CXString clang_getCursorDisplayName(CXCursor C) {
4987 if (!clang_isDeclaration(C.kind))
4988 return clang_getCursorSpelling(C);
4989
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004990 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004992 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004993
4994 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004995 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004996 D = FunTmpl->getTemplatedDecl();
4997
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004998 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004999 SmallString<64> Str;
5000 llvm::raw_svector_ostream OS(Str);
5001 OS << *Function;
5002 if (Function->getPrimaryTemplate())
5003 OS << "<>";
5004 OS << "(";
5005 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5006 if (I)
5007 OS << ", ";
5008 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5009 }
5010
5011 if (Function->isVariadic()) {
5012 if (Function->getNumParams())
5013 OS << ", ";
5014 OS << "...";
5015 }
5016 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005017 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 }
5019
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005020 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 SmallString<64> Str;
5022 llvm::raw_svector_ostream OS(Str);
5023 OS << *ClassTemplate;
5024 OS << "<";
5025 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5026 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5027 if (I)
5028 OS << ", ";
5029
5030 NamedDecl *Param = Params->getParam(I);
5031 if (Param->getIdentifier()) {
5032 OS << Param->getIdentifier()->getName();
5033 continue;
5034 }
5035
5036 // There is no parameter name, which makes this tricky. Try to come up
5037 // with something useful that isn't too long.
5038 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5039 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
5040 else if (NonTypeTemplateParmDecl *NTTP
5041 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5042 OS << NTTP->getType().getAsString(Policy);
5043 else
5044 OS << "template<...> class";
5045 }
5046
5047 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005048 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 }
5050
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005051 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5053 // If the type was explicitly written, use that.
5054 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005055 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005056
Benjamin Kramer9170e912013-02-22 15:46:01 +00005057 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 llvm::raw_svector_ostream OS(Str);
5059 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005060 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5061 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005062 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 }
5064
5065 return clang_getCursorSpelling(C);
5066}
5067
5068CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5069 switch (Kind) {
5070 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005071 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005073 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005075 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005077 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005079 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005081 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005083 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005085 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005087 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005089 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005091 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005093 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005097 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005101 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005134 case CXCursor_FixedPointLiteral:
5135 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005150 case CXCursor_OMPArraySectionExpr:
5151 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005202 case CXCursor_ObjCAvailabilityCheckExpr:
5203 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005204 case CXCursor_ObjCSelfExpr:
5205 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005232 case CXCursor_BuiltinBitCastExpr:
5233 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005257 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005265 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005277 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005296 case CXCursor_SEHLeaveStmt:
5297 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005307 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005309 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005311 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005313 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005315 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005317 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005319 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005321 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005323 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005325 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005326 case CXCursor_PackedAttr:
5327 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005328 case CXCursor_PureAttr:
5329 return cxstring::createRef("attribute(pure)");
5330 case CXCursor_ConstAttr:
5331 return cxstring::createRef("attribute(const)");
5332 case CXCursor_NoDuplicateAttr:
5333 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005334 case CXCursor_CUDAConstantAttr:
5335 return cxstring::createRef("attribute(constant)");
5336 case CXCursor_CUDADeviceAttr:
5337 return cxstring::createRef("attribute(device)");
5338 case CXCursor_CUDAGlobalAttr:
5339 return cxstring::createRef("attribute(global)");
5340 case CXCursor_CUDAHostAttr:
5341 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005342 case CXCursor_CUDASharedAttr:
5343 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005344 case CXCursor_VisibilityAttr:
5345 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005346 case CXCursor_DLLExport:
5347 return cxstring::createRef("attribute(dllexport)");
5348 case CXCursor_DLLImport:
5349 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005350 case CXCursor_NSReturnsRetained:
5351 return cxstring::createRef("attribute(ns_returns_retained)");
5352 case CXCursor_NSReturnsNotRetained:
5353 return cxstring::createRef("attribute(ns_returns_not_retained)");
5354 case CXCursor_NSReturnsAutoreleased:
5355 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5356 case CXCursor_NSConsumesSelf:
5357 return cxstring::createRef("attribute(ns_consumes_self)");
5358 case CXCursor_NSConsumed:
5359 return cxstring::createRef("attribute(ns_consumed)");
5360 case CXCursor_ObjCException:
5361 return cxstring::createRef("attribute(objc_exception)");
5362 case CXCursor_ObjCNSObject:
5363 return cxstring::createRef("attribute(NSObject)");
5364 case CXCursor_ObjCIndependentClass:
5365 return cxstring::createRef("attribute(objc_independent_class)");
5366 case CXCursor_ObjCPreciseLifetime:
5367 return cxstring::createRef("attribute(objc_precise_lifetime)");
5368 case CXCursor_ObjCReturnsInnerPointer:
5369 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5370 case CXCursor_ObjCRequiresSuper:
5371 return cxstring::createRef("attribute(objc_requires_super)");
5372 case CXCursor_ObjCRootClass:
5373 return cxstring::createRef("attribute(objc_root_class)");
5374 case CXCursor_ObjCSubclassingRestricted:
5375 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5376 case CXCursor_ObjCExplicitProtocolImpl:
5377 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5378 case CXCursor_ObjCDesignatedInitializer:
5379 return cxstring::createRef("attribute(objc_designated_initializer)");
5380 case CXCursor_ObjCRuntimeVisible:
5381 return cxstring::createRef("attribute(objc_runtime_visible)");
5382 case CXCursor_ObjCBoxable:
5383 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005384 case CXCursor_FlagEnum:
5385 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005386 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005387 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005388 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005389 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005390 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005391 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005392 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005393 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005394 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005395 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005396 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005397 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005398 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005399 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005400 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005401 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005402 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005403 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005404 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005405 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005406 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005407 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005408 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005409 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005410 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005411 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005412 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005413 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005414 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005415 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005416 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005417 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005418 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005419 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005420 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005421 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005422 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005423 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005425 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005426 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005427 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005428 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005429 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005431 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005432 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005433 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005434 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005435 return cxstring::createRef("OMPParallelDirective");
5436 case CXCursor_OMPSimdDirective:
5437 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005438 case CXCursor_OMPForDirective:
5439 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005440 case CXCursor_OMPForSimdDirective:
5441 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005442 case CXCursor_OMPSectionsDirective:
5443 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005444 case CXCursor_OMPSectionDirective:
5445 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005446 case CXCursor_OMPSingleDirective:
5447 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005448 case CXCursor_OMPMasterDirective:
5449 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005450 case CXCursor_OMPCriticalDirective:
5451 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005452 case CXCursor_OMPParallelForDirective:
5453 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005454 case CXCursor_OMPParallelForSimdDirective:
5455 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005456 case CXCursor_OMPParallelSectionsDirective:
5457 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005458 case CXCursor_OMPTaskDirective:
5459 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005460 case CXCursor_OMPTaskyieldDirective:
5461 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005462 case CXCursor_OMPBarrierDirective:
5463 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005464 case CXCursor_OMPTaskwaitDirective:
5465 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005466 case CXCursor_OMPTaskgroupDirective:
5467 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005468 case CXCursor_OMPFlushDirective:
5469 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005470 case CXCursor_OMPOrderedDirective:
5471 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005472 case CXCursor_OMPAtomicDirective:
5473 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005474 case CXCursor_OMPTargetDirective:
5475 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005476 case CXCursor_OMPTargetDataDirective:
5477 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005478 case CXCursor_OMPTargetEnterDataDirective:
5479 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005480 case CXCursor_OMPTargetExitDataDirective:
5481 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005482 case CXCursor_OMPTargetParallelDirective:
5483 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005484 case CXCursor_OMPTargetParallelForDirective:
5485 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005486 case CXCursor_OMPTargetUpdateDirective:
5487 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005488 case CXCursor_OMPTeamsDirective:
5489 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005490 case CXCursor_OMPCancellationPointDirective:
5491 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005492 case CXCursor_OMPCancelDirective:
5493 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005494 case CXCursor_OMPTaskLoopDirective:
5495 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005496 case CXCursor_OMPTaskLoopSimdDirective:
5497 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005498 case CXCursor_OMPMasterTaskLoopDirective:
5499 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005500 case CXCursor_OMPMasterTaskLoopSimdDirective:
5501 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005502 case CXCursor_OMPParallelMasterTaskLoopDirective:
5503 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Alexey Bataev14a388f2019-10-25 10:27:13 -04005504 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5505 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005506 case CXCursor_OMPDistributeDirective:
5507 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005508 case CXCursor_OMPDistributeParallelForDirective:
5509 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005510 case CXCursor_OMPDistributeParallelForSimdDirective:
5511 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005512 case CXCursor_OMPDistributeSimdDirective:
5513 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005514 case CXCursor_OMPTargetParallelForSimdDirective:
5515 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005516 case CXCursor_OMPTargetSimdDirective:
5517 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005518 case CXCursor_OMPTeamsDistributeDirective:
5519 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005520 case CXCursor_OMPTeamsDistributeSimdDirective:
5521 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005522 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5523 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005524 case CXCursor_OMPTeamsDistributeParallelForDirective:
5525 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005526 case CXCursor_OMPTargetTeamsDirective:
5527 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005528 case CXCursor_OMPTargetTeamsDistributeDirective:
5529 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005530 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5531 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005532 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5533 return cxstring::createRef(
5534 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005535 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5536 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005537 case CXCursor_OverloadCandidate:
5538 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005539 case CXCursor_TypeAliasTemplateDecl:
5540 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005541 case CXCursor_StaticAssert:
5542 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005543 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005544 return cxstring::createRef("FriendDecl");
5545 case CXCursor_ConvergentAttr:
5546 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005547 case CXCursor_WarnUnusedAttr:
5548 return cxstring::createRef("attribute(warn_unused)");
5549 case CXCursor_WarnUnusedResultAttr:
5550 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005551 case CXCursor_AlignedAttr:
5552 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005553 }
5554
5555 llvm_unreachable("Unhandled CXCursorKind");
5556}
5557
5558struct GetCursorData {
5559 SourceLocation TokenBeginLoc;
5560 bool PointsAtMacroArgExpansion;
5561 bool VisitedObjCPropertyImplDecl;
5562 SourceLocation VisitedDeclaratorDeclStartLoc;
5563 CXCursor &BestCursor;
5564
5565 GetCursorData(SourceManager &SM,
5566 SourceLocation tokenBegin, CXCursor &outputCursor)
5567 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5568 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5569 VisitedObjCPropertyImplDecl = false;
5570 }
5571};
5572
5573static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5574 CXCursor parent,
5575 CXClientData client_data) {
5576 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5577 CXCursor *BestCursor = &Data->BestCursor;
5578
5579 // If we point inside a macro argument we should provide info of what the
5580 // token is so use the actual cursor, don't replace it with a macro expansion
5581 // cursor.
5582 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5583 return CXChildVisit_Recurse;
5584
5585 if (clang_isDeclaration(cursor.kind)) {
5586 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005587 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005588 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5589 if (MD->isImplicit())
5590 return CXChildVisit_Break;
5591
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005592 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005593 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5594 // Check that when we have multiple @class references in the same line,
5595 // that later ones do not override the previous ones.
5596 // If we have:
5597 // @class Foo, Bar;
5598 // source ranges for both start at '@', so 'Bar' will end up overriding
5599 // 'Foo' even though the cursor location was at 'Foo'.
5600 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5601 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005602 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005603 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5604 if (PrevID != ID &&
5605 !PrevID->isThisDeclarationADefinition() &&
5606 !ID->isThisDeclarationADefinition())
5607 return CXChildVisit_Break;
5608 }
5609
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005610 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005611 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5612 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5613 // Check that when we have multiple declarators in the same line,
5614 // that later ones do not override the previous ones.
5615 // If we have:
5616 // int Foo, Bar;
5617 // source ranges for both start at 'int', so 'Bar' will end up overriding
5618 // 'Foo' even though the cursor location was at 'Foo'.
5619 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5620 return CXChildVisit_Break;
5621 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5622
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005623 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005624 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5625 (void)PropImp;
5626 // Check that when we have multiple @synthesize in the same line,
5627 // that later ones do not override the previous ones.
5628 // If we have:
5629 // @synthesize Foo, Bar;
5630 // source ranges for both start at '@', so 'Bar' will end up overriding
5631 // 'Foo' even though the cursor location was at 'Foo'.
5632 if (Data->VisitedObjCPropertyImplDecl)
5633 return CXChildVisit_Break;
5634 Data->VisitedObjCPropertyImplDecl = true;
5635 }
5636 }
5637
5638 if (clang_isExpression(cursor.kind) &&
5639 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005640 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005641 // Avoid having the cursor of an expression replace the declaration cursor
5642 // when the expression source range overlaps the declaration range.
5643 // This can happen for C++ constructor expressions whose range generally
5644 // include the variable declaration, e.g.:
5645 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5646 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5647 D->getLocation() == Data->TokenBeginLoc)
5648 return CXChildVisit_Break;
5649 }
5650 }
5651
5652 // If our current best cursor is the construction of a temporary object,
5653 // don't replace that cursor with a type reference, because we want
5654 // clang_getCursor() to point at the constructor.
5655 if (clang_isExpression(BestCursor->kind) &&
5656 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5657 cursor.kind == CXCursor_TypeRef) {
5658 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5659 // as having the actual point on the type reference.
5660 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5661 return CXChildVisit_Recurse;
5662 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005663
5664 // If we already have an Objective-C superclass reference, don't
5665 // update it further.
5666 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5667 return CXChildVisit_Break;
5668
Guy Benyei11169dd2012-12-18 14:30:41 +00005669 *BestCursor = cursor;
5670 return CXChildVisit_Recurse;
5671}
5672
5673CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005674 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005675 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005676 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005677 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005678
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005679 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005680 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5681
5682 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5683 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5684
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005685 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005686 CXFile SearchFile;
5687 unsigned SearchLine, SearchColumn;
5688 CXFile ResultFile;
5689 unsigned ResultLine, ResultColumn;
5690 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5691 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5692 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005693
5694 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5695 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005696 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005697 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005698 SearchFileName = clang_getFileName(SearchFile);
5699 ResultFileName = clang_getFileName(ResultFile);
5700 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5701 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005702 *Log << llvm::format("(%s:%d:%d) = %s",
5703 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5704 clang_getCString(KindSpelling))
5705 << llvm::format("(%s:%d:%d):%s%s",
5706 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5707 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005708 clang_disposeString(SearchFileName);
5709 clang_disposeString(ResultFileName);
5710 clang_disposeString(KindSpelling);
5711 clang_disposeString(USR);
5712
5713 CXCursor Definition = clang_getCursorDefinition(Result);
5714 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5715 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5716 CXString DefinitionKindSpelling
5717 = clang_getCursorKindSpelling(Definition.kind);
5718 CXFile DefinitionFile;
5719 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005720 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005721 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005722 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005723 *Log << llvm::format(" -> %s(%s:%d:%d)",
5724 clang_getCString(DefinitionKindSpelling),
5725 clang_getCString(DefinitionFileName),
5726 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005727 clang_disposeString(DefinitionFileName);
5728 clang_disposeString(DefinitionKindSpelling);
5729 }
5730 }
5731
5732 return Result;
5733}
5734
5735CXCursor clang_getNullCursor(void) {
5736 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5737}
5738
5739unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005740 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5741 // can't set consistently. For example, when visiting a DeclStmt we will set
5742 // it but we don't set it on the result of clang_getCursorDefinition for
5743 // a reference of the same declaration.
5744 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5745 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5746 // to provide that kind of info.
5747 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005748 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005749 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005750 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005751
Guy Benyei11169dd2012-12-18 14:30:41 +00005752 return X == Y;
5753}
5754
5755unsigned clang_hashCursor(CXCursor C) {
5756 unsigned Index = 0;
5757 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5758 Index = 1;
5759
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005760 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005761 std::make_pair(C.kind, C.data[Index]));
5762}
5763
5764unsigned clang_isInvalid(enum CXCursorKind K) {
5765 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5766}
5767
5768unsigned clang_isDeclaration(enum CXCursorKind K) {
5769 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005770 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5771}
5772
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005773unsigned clang_isInvalidDeclaration(CXCursor C) {
5774 if (clang_isDeclaration(C.kind)) {
5775 if (const Decl *D = getCursorDecl(C))
5776 return D->isInvalidDecl();
5777 }
5778
5779 return 0;
5780}
5781
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005782unsigned clang_isReference(enum CXCursorKind K) {
5783 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5784}
Guy Benyei11169dd2012-12-18 14:30:41 +00005785
5786unsigned clang_isExpression(enum CXCursorKind K) {
5787 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5788}
5789
5790unsigned clang_isStatement(enum CXCursorKind K) {
5791 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5792}
5793
5794unsigned clang_isAttribute(enum CXCursorKind K) {
5795 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5796}
5797
5798unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5799 return K == CXCursor_TranslationUnit;
5800}
5801
5802unsigned clang_isPreprocessing(enum CXCursorKind K) {
5803 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5804}
5805
5806unsigned clang_isUnexposed(enum CXCursorKind K) {
5807 switch (K) {
5808 case CXCursor_UnexposedDecl:
5809 case CXCursor_UnexposedExpr:
5810 case CXCursor_UnexposedStmt:
5811 case CXCursor_UnexposedAttr:
5812 return true;
5813 default:
5814 return false;
5815 }
5816}
5817
5818CXCursorKind clang_getCursorKind(CXCursor C) {
5819 return C.kind;
5820}
5821
5822CXSourceLocation clang_getCursorLocation(CXCursor C) {
5823 if (clang_isReference(C.kind)) {
5824 switch (C.kind) {
5825 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005826 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005827 = getCursorObjCSuperClassRef(C);
5828 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5829 }
5830
5831 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005832 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005833 = getCursorObjCProtocolRef(C);
5834 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5835 }
5836
5837 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005838 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005839 = getCursorObjCClassRef(C);
5840 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5841 }
5842
5843 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005844 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005845 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5846 }
5847
5848 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005849 std::pair<const TemplateDecl *, SourceLocation> P =
5850 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005851 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5852 }
5853
5854 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005855 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005856 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5857 }
5858
5859 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005860 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005861 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5862 }
5863
5864 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005865 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005866 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5867 }
5868
5869 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005870 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005871 if (!BaseSpec)
5872 return clang_getNullLocation();
5873
5874 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5875 return cxloc::translateSourceLocation(getCursorContext(C),
5876 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005877
Guy Benyei11169dd2012-12-18 14:30:41 +00005878 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005879 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005880 }
5881
5882 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005883 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005884 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5885 }
5886
5887 case CXCursor_OverloadedDeclRef:
5888 return cxloc::translateSourceLocation(getCursorContext(C),
5889 getCursorOverloadedDeclRef(C).second);
5890
5891 default:
5892 // FIXME: Need a way to enumerate all non-reference cases.
5893 llvm_unreachable("Missed a reference kind");
5894 }
5895 }
5896
5897 if (clang_isExpression(C.kind))
5898 return cxloc::translateSourceLocation(getCursorContext(C),
5899 getLocationFromExpr(getCursorExpr(C)));
5900
5901 if (clang_isStatement(C.kind))
5902 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005903 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005904
5905 if (C.kind == CXCursor_PreprocessingDirective) {
5906 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5907 return cxloc::translateSourceLocation(getCursorContext(C), L);
5908 }
5909
5910 if (C.kind == CXCursor_MacroExpansion) {
5911 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005912 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005913 return cxloc::translateSourceLocation(getCursorContext(C), L);
5914 }
5915
5916 if (C.kind == CXCursor_MacroDefinition) {
5917 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5918 return cxloc::translateSourceLocation(getCursorContext(C), L);
5919 }
5920
5921 if (C.kind == CXCursor_InclusionDirective) {
5922 SourceLocation L
5923 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5924 return cxloc::translateSourceLocation(getCursorContext(C), L);
5925 }
5926
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005927 if (clang_isAttribute(C.kind)) {
5928 SourceLocation L
5929 = cxcursor::getCursorAttr(C)->getLocation();
5930 return cxloc::translateSourceLocation(getCursorContext(C), L);
5931 }
5932
Guy Benyei11169dd2012-12-18 14:30:41 +00005933 if (!clang_isDeclaration(C.kind))
5934 return clang_getNullLocation();
5935
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005936 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005937 if (!D)
5938 return clang_getNullLocation();
5939
5940 SourceLocation Loc = D->getLocation();
5941 // FIXME: Multiple variables declared in a single declaration
5942 // currently lack the information needed to correctly determine their
5943 // ranges when accounting for the type-specifier. We use context
5944 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5945 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005946 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005947 if (!cxcursor::isFirstInDeclGroup(C))
5948 Loc = VD->getLocation();
5949 }
5950
5951 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005952 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005953 Loc = MD->getSelectorStartLoc();
5954
5955 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5956}
5957
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005958} // end extern "C"
5959
Guy Benyei11169dd2012-12-18 14:30:41 +00005960CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5961 assert(TU);
5962
5963 // Guard against an invalid SourceLocation, or we may assert in one
5964 // of the following calls.
5965 if (SLoc.isInvalid())
5966 return clang_getNullCursor();
5967
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005968 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005969
5970 // Translate the given source location to make it point at the beginning of
5971 // the token under the cursor.
5972 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5973 CXXUnit->getASTContext().getLangOpts());
5974
5975 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5976 if (SLoc.isValid()) {
5977 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5978 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5979 /*VisitPreprocessorLast=*/true,
5980 /*VisitIncludedEntities=*/false,
5981 SourceLocation(SLoc));
5982 CursorVis.visitFileRegion();
5983 }
5984
5985 return Result;
5986}
5987
5988static SourceRange getRawCursorExtent(CXCursor C) {
5989 if (clang_isReference(C.kind)) {
5990 switch (C.kind) {
5991 case CXCursor_ObjCSuperClassRef:
5992 return getCursorObjCSuperClassRef(C).second;
5993
5994 case CXCursor_ObjCProtocolRef:
5995 return getCursorObjCProtocolRef(C).second;
5996
5997 case CXCursor_ObjCClassRef:
5998 return getCursorObjCClassRef(C).second;
5999
6000 case CXCursor_TypeRef:
6001 return getCursorTypeRef(C).second;
6002
6003 case CXCursor_TemplateRef:
6004 return getCursorTemplateRef(C).second;
6005
6006 case CXCursor_NamespaceRef:
6007 return getCursorNamespaceRef(C).second;
6008
6009 case CXCursor_MemberRef:
6010 return getCursorMemberRef(C).second;
6011
6012 case CXCursor_CXXBaseSpecifier:
6013 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6014
6015 case CXCursor_LabelRef:
6016 return getCursorLabelRef(C).second;
6017
6018 case CXCursor_OverloadedDeclRef:
6019 return getCursorOverloadedDeclRef(C).second;
6020
6021 case CXCursor_VariableRef:
6022 return getCursorVariableRef(C).second;
6023
6024 default:
6025 // FIXME: Need a way to enumerate all non-reference cases.
6026 llvm_unreachable("Missed a reference kind");
6027 }
6028 }
6029
6030 if (clang_isExpression(C.kind))
6031 return getCursorExpr(C)->getSourceRange();
6032
6033 if (clang_isStatement(C.kind))
6034 return getCursorStmt(C)->getSourceRange();
6035
6036 if (clang_isAttribute(C.kind))
6037 return getCursorAttr(C)->getRange();
6038
6039 if (C.kind == CXCursor_PreprocessingDirective)
6040 return cxcursor::getCursorPreprocessingDirective(C);
6041
6042 if (C.kind == CXCursor_MacroExpansion) {
6043 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006044 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006045 return TU->mapRangeFromPreamble(Range);
6046 }
6047
6048 if (C.kind == CXCursor_MacroDefinition) {
6049 ASTUnit *TU = getCursorASTUnit(C);
6050 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6051 return TU->mapRangeFromPreamble(Range);
6052 }
6053
6054 if (C.kind == CXCursor_InclusionDirective) {
6055 ASTUnit *TU = getCursorASTUnit(C);
6056 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6057 return TU->mapRangeFromPreamble(Range);
6058 }
6059
6060 if (C.kind == CXCursor_TranslationUnit) {
6061 ASTUnit *TU = getCursorASTUnit(C);
6062 FileID MainID = TU->getSourceManager().getMainFileID();
6063 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6064 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6065 return SourceRange(Start, End);
6066 }
6067
6068 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006069 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006070 if (!D)
6071 return SourceRange();
6072
6073 SourceRange R = D->getSourceRange();
6074 // FIXME: Multiple variables declared in a single declaration
6075 // currently lack the information needed to correctly determine their
6076 // ranges when accounting for the type-specifier. We use context
6077 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6078 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006079 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 if (!cxcursor::isFirstInDeclGroup(C))
6081 R.setBegin(VD->getLocation());
6082 }
6083 return R;
6084 }
6085 return SourceRange();
6086}
6087
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006088/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006089/// the decl-specifier-seq for declarations.
6090static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6091 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006092 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 if (!D)
6094 return SourceRange();
6095
6096 SourceRange R = D->getSourceRange();
6097
6098 // Adjust the start of the location for declarations preceded by
6099 // declaration specifiers.
6100 SourceLocation StartLoc;
6101 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6102 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006103 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006104 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006106 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006107 }
6108
6109 if (StartLoc.isValid() && R.getBegin().isValid() &&
6110 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6111 R.setBegin(StartLoc);
6112
6113 // FIXME: Multiple variables declared in a single declaration
6114 // currently lack the information needed to correctly determine their
6115 // ranges when accounting for the type-specifier. We use context
6116 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6117 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006118 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006119 if (!cxcursor::isFirstInDeclGroup(C))
6120 R.setBegin(VD->getLocation());
6121 }
6122
6123 return R;
6124 }
6125
6126 return getRawCursorExtent(C);
6127}
6128
Guy Benyei11169dd2012-12-18 14:30:41 +00006129CXSourceRange clang_getCursorExtent(CXCursor C) {
6130 SourceRange R = getRawCursorExtent(C);
6131 if (R.isInvalid())
6132 return clang_getNullRange();
6133
6134 return cxloc::translateSourceRange(getCursorContext(C), R);
6135}
6136
6137CXCursor clang_getCursorReferenced(CXCursor C) {
6138 if (clang_isInvalid(C.kind))
6139 return clang_getNullCursor();
6140
6141 CXTranslationUnit tu = getCursorTU(C);
6142 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006143 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 if (!D)
6145 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006146 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006147 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006148 if (const ObjCPropertyImplDecl *PropImpl =
6149 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006150 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6151 return MakeCXCursor(Property, tu);
6152
6153 return C;
6154 }
6155
6156 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006157 const Expr *E = getCursorExpr(C);
6158 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006159 if (D) {
6160 CXCursor declCursor = MakeCXCursor(D, tu);
6161 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6162 declCursor);
6163 return declCursor;
6164 }
6165
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006166 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 return MakeCursorOverloadedDeclRef(Ovl, tu);
6168
6169 return clang_getNullCursor();
6170 }
6171
6172 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006173 const Stmt *S = getCursorStmt(C);
6174 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 if (LabelDecl *label = Goto->getLabel())
6176 if (LabelStmt *labelS = label->getStmt())
6177 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6178
6179 return clang_getNullCursor();
6180 }
Richard Smith66a81862015-05-04 02:25:31 +00006181
Guy Benyei11169dd2012-12-18 14:30:41 +00006182 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006183 if (const MacroDefinitionRecord *Def =
6184 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006185 return MakeMacroDefinitionCursor(Def, tu);
6186 }
6187
6188 if (!clang_isReference(C.kind))
6189 return clang_getNullCursor();
6190
6191 switch (C.kind) {
6192 case CXCursor_ObjCSuperClassRef:
6193 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6194
6195 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006196 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6197 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006198 return MakeCXCursor(Def, tu);
6199
6200 return MakeCXCursor(Prot, tu);
6201 }
6202
6203 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006204 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6205 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006206 return MakeCXCursor(Def, tu);
6207
6208 return MakeCXCursor(Class, tu);
6209 }
6210
6211 case CXCursor_TypeRef:
6212 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6213
6214 case CXCursor_TemplateRef:
6215 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6216
6217 case CXCursor_NamespaceRef:
6218 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6219
6220 case CXCursor_MemberRef:
6221 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6222
6223 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006224 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006225 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6226 tu ));
6227 }
6228
6229 case CXCursor_LabelRef:
6230 // FIXME: We end up faking the "parent" declaration here because we
6231 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006232 return MakeCXCursor(getCursorLabelRef(C).first,
6233 cxtu::getASTUnit(tu)->getASTContext()
6234 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 tu);
6236
6237 case CXCursor_OverloadedDeclRef:
6238 return C;
6239
6240 case CXCursor_VariableRef:
6241 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6242
6243 default:
6244 // We would prefer to enumerate all non-reference cursor kinds here.
6245 llvm_unreachable("Unhandled reference cursor kind");
6246 }
6247}
6248
6249CXCursor clang_getCursorDefinition(CXCursor C) {
6250 if (clang_isInvalid(C.kind))
6251 return clang_getNullCursor();
6252
6253 CXTranslationUnit TU = getCursorTU(C);
6254
6255 bool WasReference = false;
6256 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6257 C = clang_getCursorReferenced(C);
6258 WasReference = true;
6259 }
6260
6261 if (C.kind == CXCursor_MacroExpansion)
6262 return clang_getCursorReferenced(C);
6263
6264 if (!clang_isDeclaration(C.kind))
6265 return clang_getNullCursor();
6266
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006267 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006268 if (!D)
6269 return clang_getNullCursor();
6270
6271 switch (D->getKind()) {
6272 // Declaration kinds that don't really separate the notions of
6273 // declaration and definition.
6274 case Decl::Namespace:
6275 case Decl::Typedef:
6276 case Decl::TypeAlias:
6277 case Decl::TypeAliasTemplate:
6278 case Decl::TemplateTypeParm:
6279 case Decl::EnumConstant:
6280 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006281 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006282 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 case Decl::IndirectField:
6284 case Decl::ObjCIvar:
6285 case Decl::ObjCAtDefsField:
6286 case Decl::ImplicitParam:
6287 case Decl::ParmVar:
6288 case Decl::NonTypeTemplateParm:
6289 case Decl::TemplateTemplateParm:
6290 case Decl::ObjCCategoryImpl:
6291 case Decl::ObjCImplementation:
6292 case Decl::AccessSpec:
6293 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006294 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006295 case Decl::ObjCPropertyImpl:
6296 case Decl::FileScopeAsm:
6297 case Decl::StaticAssert:
6298 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006299 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006300 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006301 case Decl::Label: // FIXME: Is this right??
6302 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006303 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006304 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006305 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006306 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006307 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006308 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006309 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006310 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006311 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006312 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006313 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006314 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006315 case Decl::Concept:
Guy Benyei11169dd2012-12-18 14:30:41 +00006316 return C;
6317
6318 // Declaration kinds that don't make any sense here, but are
6319 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006320 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006321 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006322 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006323 break;
6324
6325 // Declaration kinds for which the definition is not resolvable.
6326 case Decl::UnresolvedUsingTypename:
6327 case Decl::UnresolvedUsingValue:
6328 break;
6329
6330 case Decl::UsingDirective:
6331 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6332 TU);
6333
6334 case Decl::NamespaceAlias:
6335 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6336
6337 case Decl::Enum:
6338 case Decl::Record:
6339 case Decl::CXXRecord:
6340 case Decl::ClassTemplateSpecialization:
6341 case Decl::ClassTemplatePartialSpecialization:
6342 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6343 return MakeCXCursor(Def, TU);
6344 return clang_getNullCursor();
6345
6346 case Decl::Function:
6347 case Decl::CXXMethod:
6348 case Decl::CXXConstructor:
6349 case Decl::CXXDestructor:
6350 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006351 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006353 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006354 return clang_getNullCursor();
6355 }
6356
Larisse Voufo39a1e502013-08-06 01:03:05 +00006357 case Decl::Var:
6358 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006359 case Decl::VarTemplatePartialSpecialization:
6360 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006361 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006362 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006363 return MakeCXCursor(Def, TU);
6364 return clang_getNullCursor();
6365 }
6366
6367 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006368 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006369 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6370 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6371 return clang_getNullCursor();
6372 }
6373
6374 case Decl::ClassTemplate: {
6375 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6376 ->getDefinition())
6377 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6378 TU);
6379 return clang_getNullCursor();
6380 }
6381
Larisse Voufo39a1e502013-08-06 01:03:05 +00006382 case Decl::VarTemplate: {
6383 if (VarDecl *Def =
6384 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6385 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6386 return clang_getNullCursor();
6387 }
6388
Guy Benyei11169dd2012-12-18 14:30:41 +00006389 case Decl::Using:
6390 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6391 D->getLocation(), TU);
6392
6393 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006394 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006395 return clang_getCursorDefinition(
6396 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6397 TU));
6398
6399 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006400 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 if (Method->isThisDeclarationADefinition())
6402 return C;
6403
6404 // Dig out the method definition in the associated
6405 // @implementation, if we have it.
6406 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006407 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6409 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6410 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6411 Method->isInstanceMethod()))
6412 if (Def->isThisDeclarationADefinition())
6413 return MakeCXCursor(Def, TU);
6414
6415 return clang_getNullCursor();
6416 }
6417
6418 case Decl::ObjCCategory:
6419 if (ObjCCategoryImplDecl *Impl
6420 = cast<ObjCCategoryDecl>(D)->getImplementation())
6421 return MakeCXCursor(Impl, TU);
6422 return clang_getNullCursor();
6423
6424 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006425 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006426 return MakeCXCursor(Def, TU);
6427 return clang_getNullCursor();
6428
6429 case Decl::ObjCInterface: {
6430 // There are two notions of a "definition" for an Objective-C
6431 // class: the interface and its implementation. When we resolved a
6432 // reference to an Objective-C class, produce the @interface as
6433 // the definition; when we were provided with the interface,
6434 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006435 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006436 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006437 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006438 return MakeCXCursor(Def, TU);
6439 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6440 return MakeCXCursor(Impl, TU);
6441 return clang_getNullCursor();
6442 }
6443
6444 case Decl::ObjCProperty:
6445 // FIXME: We don't really know where to find the
6446 // ObjCPropertyImplDecls that implement this property.
6447 return clang_getNullCursor();
6448
6449 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006450 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006452 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006453 return MakeCXCursor(Def, TU);
6454
6455 return clang_getNullCursor();
6456
6457 case Decl::Friend:
6458 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6459 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6460 return clang_getNullCursor();
6461
6462 case Decl::FriendTemplate:
6463 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6464 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6465 return clang_getNullCursor();
6466 }
6467
6468 return clang_getNullCursor();
6469}
6470
6471unsigned clang_isCursorDefinition(CXCursor C) {
6472 if (!clang_isDeclaration(C.kind))
6473 return 0;
6474
6475 return clang_getCursorDefinition(C) == C;
6476}
6477
6478CXCursor clang_getCanonicalCursor(CXCursor C) {
6479 if (!clang_isDeclaration(C.kind))
6480 return C;
6481
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006482 if (const Decl *D = getCursorDecl(C)) {
6483 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6485 return MakeCXCursor(CatD, getCursorTU(C));
6486
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006487 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6488 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006489 return MakeCXCursor(IFD, getCursorTU(C));
6490
6491 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6492 }
6493
6494 return C;
6495}
6496
6497int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6498 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6499}
6500
6501unsigned clang_getNumOverloadedDecls(CXCursor C) {
6502 if (C.kind != CXCursor_OverloadedDeclRef)
6503 return 0;
6504
6505 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006506 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006507 return E->getNumDecls();
6508
6509 if (OverloadedTemplateStorage *S
6510 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6511 return S->size();
6512
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006513 const Decl *D = Storage.get<const Decl *>();
6514 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006515 return Using->shadow_size();
6516
6517 return 0;
6518}
6519
6520CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6521 if (cursor.kind != CXCursor_OverloadedDeclRef)
6522 return clang_getNullCursor();
6523
6524 if (index >= clang_getNumOverloadedDecls(cursor))
6525 return clang_getNullCursor();
6526
6527 CXTranslationUnit TU = getCursorTU(cursor);
6528 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006529 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 return MakeCXCursor(E->decls_begin()[index], TU);
6531
6532 if (OverloadedTemplateStorage *S
6533 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6534 return MakeCXCursor(S->begin()[index], TU);
6535
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006536 const Decl *D = Storage.get<const Decl *>();
6537 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006538 // FIXME: This is, unfortunately, linear time.
6539 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6540 std::advance(Pos, index);
6541 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6542 }
6543
6544 return clang_getNullCursor();
6545}
6546
6547void clang_getDefinitionSpellingAndExtent(CXCursor C,
6548 const char **startBuf,
6549 const char **endBuf,
6550 unsigned *startLine,
6551 unsigned *startColumn,
6552 unsigned *endLine,
6553 unsigned *endColumn) {
6554 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006555 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6557
6558 SourceManager &SM = FD->getASTContext().getSourceManager();
6559 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6560 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6561 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6562 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6563 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6564 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6565}
6566
6567
6568CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6569 unsigned PieceIndex) {
6570 RefNamePieces Pieces;
6571
6572 switch (C.kind) {
6573 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006574 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006575 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6576 E->getQualifierLoc().getSourceRange());
6577 break;
6578
6579 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006580 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6581 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6582 Pieces =
6583 buildPieces(NameFlags, false, E->getNameInfo(),
6584 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6585 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006586 break;
6587
6588 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006589 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006590 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006591 const Expr *Callee = OCE->getCallee();
6592 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006593 Callee = ICE->getSubExpr();
6594
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006595 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6597 DRE->getQualifierLoc().getSourceRange());
6598 }
6599 break;
6600
6601 default:
6602 break;
6603 }
6604
6605 if (Pieces.empty()) {
6606 if (PieceIndex == 0)
6607 return clang_getCursorExtent(C);
6608 } else if (PieceIndex < Pieces.size()) {
6609 SourceRange R = Pieces[PieceIndex];
6610 if (R.isValid())
6611 return cxloc::translateSourceRange(getCursorContext(C), R);
6612 }
6613
6614 return clang_getNullRange();
6615}
6616
6617void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006618 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6619 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006620}
6621
6622void clang_executeOnThread(void (*fn)(void*), void *user_data,
6623 unsigned stack_size) {
Sam McCalla9c3c172019-10-23 15:34:48 +02006624 llvm::llvm_execute_on_thread(
6625 fn, user_data,
6626 stack_size == 0 ? llvm::None : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006627}
6628
Guy Benyei11169dd2012-12-18 14:30:41 +00006629//===----------------------------------------------------------------------===//
6630// Token-based Operations.
6631//===----------------------------------------------------------------------===//
6632
6633/* CXToken layout:
6634 * int_data[0]: a CXTokenKind
6635 * int_data[1]: starting token location
6636 * int_data[2]: token length
6637 * int_data[3]: reserved
6638 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6639 * otherwise unused.
6640 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006641CXTokenKind clang_getTokenKind(CXToken CXTok) {
6642 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6643}
6644
6645CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6646 switch (clang_getTokenKind(CXTok)) {
6647 case CXToken_Identifier:
6648 case CXToken_Keyword:
6649 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006650 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 ->getNameStart());
6652
6653 case CXToken_Literal: {
6654 // We have stashed the starting pointer in the ptr_data field. Use it.
6655 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006656 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006657 }
6658
6659 case CXToken_Punctuation:
6660 case CXToken_Comment:
6661 break;
6662 }
6663
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006664 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006665 LOG_BAD_TU(TU);
6666 return cxstring::createEmpty();
6667 }
6668
Guy Benyei11169dd2012-12-18 14:30:41 +00006669 // We have to find the starting buffer pointer the hard way, by
6670 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006671 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006672 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006673 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006674
6675 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6676 std::pair<FileID, unsigned> LocInfo
6677 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6678 bool Invalid = false;
6679 StringRef Buffer
6680 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6681 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006682 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006683
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006684 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006685}
6686
6687CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006688 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006689 LOG_BAD_TU(TU);
6690 return clang_getNullLocation();
6691 }
6692
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006693 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 if (!CXXUnit)
6695 return clang_getNullLocation();
6696
6697 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6698 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6699}
6700
6701CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006702 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006703 LOG_BAD_TU(TU);
6704 return clang_getNullRange();
6705 }
6706
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006707 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006708 if (!CXXUnit)
6709 return clang_getNullRange();
6710
6711 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6712 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6713}
6714
6715static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6716 SmallVectorImpl<CXToken> &CXTokens) {
6717 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6718 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006719 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006720 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006721 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006722
6723 // Cannot tokenize across files.
6724 if (BeginLocInfo.first != EndLocInfo.first)
6725 return;
6726
6727 // Create a lexer
6728 bool Invalid = false;
6729 StringRef Buffer
6730 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6731 if (Invalid)
6732 return;
6733
6734 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6735 CXXUnit->getASTContext().getLangOpts(),
6736 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6737 Lex.SetCommentRetentionState(true);
6738
6739 // Lex tokens until we hit the end of the range.
6740 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6741 Token Tok;
6742 bool previousWasAt = false;
6743 do {
6744 // Lex the next token
6745 Lex.LexFromRawLexer(Tok);
6746 if (Tok.is(tok::eof))
6747 break;
6748
6749 // Initialize the CXToken.
6750 CXToken CXTok;
6751
6752 // - Common fields
6753 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6754 CXTok.int_data[2] = Tok.getLength();
6755 CXTok.int_data[3] = 0;
6756
6757 // - Kind-specific fields
6758 if (Tok.isLiteral()) {
6759 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006760 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006761 } else if (Tok.is(tok::raw_identifier)) {
6762 // Lookup the identifier to determine whether we have a keyword.
6763 IdentifierInfo *II
6764 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6765
6766 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6767 CXTok.int_data[0] = CXToken_Keyword;
6768 }
6769 else {
6770 CXTok.int_data[0] = Tok.is(tok::identifier)
6771 ? CXToken_Identifier
6772 : CXToken_Keyword;
6773 }
6774 CXTok.ptr_data = II;
6775 } else if (Tok.is(tok::comment)) {
6776 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006777 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006778 } else {
6779 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006780 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006781 }
6782 CXTokens.push_back(CXTok);
6783 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006784 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006785}
6786
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006787CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6788 LOG_FUNC_SECTION {
6789 *Log << TU << ' ' << Location;
6790 }
6791
6792 if (isNotUsableTU(TU)) {
6793 LOG_BAD_TU(TU);
6794 return NULL;
6795 }
6796
6797 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6798 if (!CXXUnit)
6799 return NULL;
6800
6801 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6802 if (Begin.isInvalid())
6803 return NULL;
6804 SourceManager &SM = CXXUnit->getSourceManager();
6805 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6806 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6807
6808 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6809
6810 SmallVector<CXToken, 32> CXTokens;
6811 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6812
6813 if (CXTokens.empty())
6814 return NULL;
6815
6816 CXTokens.resize(1);
6817 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6818
6819 memmove(Token, CXTokens.data(), sizeof(CXToken));
6820 return Token;
6821}
6822
Guy Benyei11169dd2012-12-18 14:30:41 +00006823void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6824 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006825 LOG_FUNC_SECTION {
6826 *Log << TU << ' ' << Range;
6827 }
6828
Guy Benyei11169dd2012-12-18 14:30:41 +00006829 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006830 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006831 if (NumTokens)
6832 *NumTokens = 0;
6833
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006834 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006835 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006836 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006837 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006838
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006839 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006840 if (!CXXUnit || !Tokens || !NumTokens)
6841 return;
6842
6843 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6844
6845 SourceRange R = cxloc::translateCXSourceRange(Range);
6846 if (R.isInvalid())
6847 return;
6848
6849 SmallVector<CXToken, 32> CXTokens;
6850 getTokens(CXXUnit, R, CXTokens);
6851
6852 if (CXTokens.empty())
6853 return;
6854
Serge Pavlov52525732018-02-21 02:02:39 +00006855 *Tokens = static_cast<CXToken *>(
6856 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6858 *NumTokens = CXTokens.size();
6859}
6860
6861void clang_disposeTokens(CXTranslationUnit TU,
6862 CXToken *Tokens, unsigned NumTokens) {
6863 free(Tokens);
6864}
6865
Guy Benyei11169dd2012-12-18 14:30:41 +00006866//===----------------------------------------------------------------------===//
6867// Token annotation APIs.
6868//===----------------------------------------------------------------------===//
6869
Guy Benyei11169dd2012-12-18 14:30:41 +00006870static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6871 CXCursor parent,
6872 CXClientData client_data);
6873static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6874 CXClientData client_data);
6875
6876namespace {
6877class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006878 CXToken *Tokens;
6879 CXCursor *Cursors;
6880 unsigned NumTokens;
6881 unsigned TokIdx;
6882 unsigned PreprocessingTokIdx;
6883 CursorVisitor AnnotateVis;
6884 SourceManager &SrcMgr;
6885 bool HasContextSensitiveKeywords;
6886
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006887 struct PostChildrenAction {
6888 CXCursor cursor;
6889 enum Action { Invalid, Ignore, Postpone } action;
6890 };
6891 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6892
Guy Benyei11169dd2012-12-18 14:30:41 +00006893 struct PostChildrenInfo {
6894 CXCursor Cursor;
6895 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006896 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006897 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006898 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006899 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006900 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006901
6902 CXToken &getTok(unsigned Idx) {
6903 assert(Idx < NumTokens);
6904 return Tokens[Idx];
6905 }
6906 const CXToken &getTok(unsigned Idx) const {
6907 assert(Idx < NumTokens);
6908 return Tokens[Idx];
6909 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 bool MoreTokens() const { return TokIdx < NumTokens; }
6911 unsigned NextToken() const { return TokIdx; }
6912 void AdvanceToken() { ++TokIdx; }
6913 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006914 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006915 }
6916 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006917 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006918 }
6919 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006920 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006921 }
6922
6923 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006924 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006925 SourceRange);
6926
6927public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006928 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006929 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006930 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006931 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006932 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 AnnotateTokensVisitor, this,
6934 /*VisitPreprocessorLast=*/true,
6935 /*VisitIncludedEntities=*/false,
6936 RegionOfInterest,
6937 /*VisitDeclsOnly=*/false,
6938 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006939 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 HasContextSensitiveKeywords(false) { }
6941
6942 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6943 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006944 bool IsIgnoredChildCursor(CXCursor cursor) const;
6945 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6946
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006948 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6949 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6950
Guy Benyei11169dd2012-12-18 14:30:41 +00006951 void AnnotateTokens();
6952
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006953 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006954 /// context-sensitive keywords.
6955 bool hasContextSensitiveKeywords() const {
6956 return HasContextSensitiveKeywords;
6957 }
6958
6959 ~AnnotateTokensWorker() {
6960 assert(PostChildrenInfos.empty());
6961 }
6962};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006963}
Guy Benyei11169dd2012-12-18 14:30:41 +00006964
6965void AnnotateTokensWorker::AnnotateTokens() {
6966 // Walk the AST within the region of interest, annotating tokens
6967 // along the way.
6968 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006969}
Guy Benyei11169dd2012-12-18 14:30:41 +00006970
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006971bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6972 if (PostChildrenInfos.empty())
6973 return false;
6974
6975 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6976 if (ChildAction.cursor == cursor &&
6977 ChildAction.action == PostChildrenAction::Ignore) {
6978 return true;
6979 }
6980 }
6981
6982 return false;
6983}
6984
6985const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6986 if (!clang_isExpression(Cursor.kind))
6987 return nullptr;
6988
6989 const Expr *E = getCursorExpr(Cursor);
6990 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6991 const OverloadedOperatorKind Kind = OCE->getOperator();
6992 if (Kind == OO_Call || Kind == OO_Subscript)
6993 return OCE;
6994 }
6995
6996 return nullptr;
6997}
6998
6999AnnotateTokensWorker::PostChildrenActions
7000AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7001 PostChildrenActions actions;
7002
7003 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
7004 // visited before the arguments to the operator call. For the Call and
7005 // Subscript operator the range of this DeclRefExpr includes the whole call
7006 // expression, so that all tokens in that range would be mapped to the
7007 // operator function, including the tokens of the arguments. To avoid that,
7008 // ensure to visit this DeclRefExpr as last node.
7009 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7010 const Expr *Callee = OCE->getCallee();
7011 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7012 const Expr *SubExpr = ICE->getSubExpr();
7013 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007014 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007015 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7016
7017 // Visit the DeclRefExpr as last.
7018 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7019 actions.push_back({cxChild, PostChildrenAction::Postpone});
7020
7021 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7022 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7023 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7024 actions.push_back({cxChild, PostChildrenAction::Ignore});
7025 }
7026 }
7027 }
7028
7029 return actions;
7030}
7031
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007032static inline void updateCursorAnnotation(CXCursor &Cursor,
7033 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007034 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007035 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007036 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007037}
7038
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007039/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007040//// between the cursor location and the source range is the same as
7041/// \arg compResult.
7042///
7043/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7044/// Pass RangeOverlap to annotate tokens inside a range.
7045void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7046 RangeComparisonResult compResult,
7047 SourceRange range) {
7048 while (MoreTokens()) {
7049 const unsigned I = NextToken();
7050 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007051 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7052 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007053
7054 SourceLocation TokLoc = GetTokenLoc(I);
7055 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007056 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007057 AdvanceToken();
7058 continue;
7059 }
7060 break;
7061 }
7062}
7063
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007064/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007065/// \returns true if it advanced beyond all macro tokens, false otherwise.
7066bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007067 CXCursor updateC,
7068 RangeComparisonResult compResult,
7069 SourceRange range) {
7070 assert(MoreTokens());
7071 assert(isFunctionMacroToken(NextToken()) &&
7072 "Should be called only for macro arg tokens");
7073
7074 // This works differently than annotateAndAdvanceTokens; because expanded
7075 // macro arguments can have arbitrary translation-unit source order, we do not
7076 // advance the token index one by one until a token fails the range test.
7077 // We only advance once past all of the macro arg tokens if all of them
7078 // pass the range test. If one of them fails we keep the token index pointing
7079 // at the start of the macro arg tokens so that the failing token will be
7080 // annotated by a subsequent annotation try.
7081
7082 bool atLeastOneCompFail = false;
7083
7084 unsigned I = NextToken();
7085 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7086 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7087 if (TokLoc.isFileID())
7088 continue; // not macro arg token, it's parens or comma.
7089 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7090 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7091 Cursors[I] = updateC;
7092 } else
7093 atLeastOneCompFail = true;
7094 }
7095
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007096 if (atLeastOneCompFail)
7097 return false;
7098
7099 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7100 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007101}
7102
7103enum CXChildVisitResult
7104AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007105 SourceRange cursorRange = getRawCursorExtent(cursor);
7106 if (cursorRange.isInvalid())
7107 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007108
7109 if (IsIgnoredChildCursor(cursor))
7110 return CXChildVisit_Continue;
7111
Guy Benyei11169dd2012-12-18 14:30:41 +00007112 if (!HasContextSensitiveKeywords) {
7113 // Objective-C properties can have context-sensitive keywords.
7114 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007115 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007116 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7117 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7118 }
7119 // Objective-C methods can have context-sensitive keywords.
7120 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7121 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007122 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007123 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7124 if (Method->getObjCDeclQualifier())
7125 HasContextSensitiveKeywords = true;
7126 else {
David Majnemer59f77922016-06-24 04:05:48 +00007127 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007128 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007129 HasContextSensitiveKeywords = true;
7130 break;
7131 }
7132 }
7133 }
7134 }
7135 }
7136 // C++ methods can have context-sensitive keywords.
7137 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007138 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007139 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7140 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7141 HasContextSensitiveKeywords = true;
7142 }
7143 }
7144 // C++ classes can have context-sensitive keywords.
7145 else if (cursor.kind == CXCursor_StructDecl ||
7146 cursor.kind == CXCursor_ClassDecl ||
7147 cursor.kind == CXCursor_ClassTemplate ||
7148 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007149 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007150 if (D->hasAttr<FinalAttr>())
7151 HasContextSensitiveKeywords = true;
7152 }
7153 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007154
7155 // Don't override a property annotation with its getter/setter method.
7156 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7157 parent.kind == CXCursor_ObjCPropertyDecl)
7158 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007159
7160 if (clang_isPreprocessing(cursor.kind)) {
7161 // Items in the preprocessing record are kept separate from items in
7162 // declarations, so we keep a separate token index.
7163 unsigned SavedTokIdx = TokIdx;
7164 TokIdx = PreprocessingTokIdx;
7165
7166 // Skip tokens up until we catch up to the beginning of the preprocessing
7167 // entry.
7168 while (MoreTokens()) {
7169 const unsigned I = NextToken();
7170 SourceLocation TokLoc = GetTokenLoc(I);
7171 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7172 case RangeBefore:
7173 AdvanceToken();
7174 continue;
7175 case RangeAfter:
7176 case RangeOverlap:
7177 break;
7178 }
7179 break;
7180 }
7181
7182 // Look at all of the tokens within this range.
7183 while (MoreTokens()) {
7184 const unsigned I = NextToken();
7185 SourceLocation TokLoc = GetTokenLoc(I);
7186 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7187 case RangeBefore:
7188 llvm_unreachable("Infeasible");
7189 case RangeAfter:
7190 break;
7191 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007192 // For macro expansions, just note where the beginning of the macro
7193 // expansion occurs.
7194 if (cursor.kind == CXCursor_MacroExpansion) {
7195 if (TokLoc == cursorRange.getBegin())
7196 Cursors[I] = cursor;
7197 AdvanceToken();
7198 break;
7199 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007200 // We may have already annotated macro names inside macro definitions.
7201 if (Cursors[I].kind != CXCursor_MacroExpansion)
7202 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007204 continue;
7205 }
7206 break;
7207 }
7208
7209 // Save the preprocessing token index; restore the non-preprocessing
7210 // token index.
7211 PreprocessingTokIdx = TokIdx;
7212 TokIdx = SavedTokIdx;
7213 return CXChildVisit_Recurse;
7214 }
7215
7216 if (cursorRange.isInvalid())
7217 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007218
7219 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007220 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007221 const enum CXCursorKind K = clang_getCursorKind(parent);
7222 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007223 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7224 // Attributes are annotated out-of-order, skip tokens until we reach it.
7225 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007226 ? clang_getNullCursor() : parent;
7227
7228 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7229
7230 // Avoid having the cursor of an expression "overwrite" the annotation of the
7231 // variable declaration that it belongs to.
7232 // This can happen for C++ constructor expressions whose range generally
7233 // include the variable declaration, e.g.:
7234 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007235 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007236 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007237 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007238 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007239 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7240 E->getBeginLoc() == D->getLocation() &&
7241 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007242 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007243 AdvanceToken();
7244 }
7245 }
7246 }
7247
7248 // Before recursing into the children keep some state that we are going
7249 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7250 // extra work after the child nodes are visited.
7251 // Note that we don't call VisitChildren here to avoid traversing statements
7252 // code-recursively which can blow the stack.
7253
7254 PostChildrenInfo Info;
7255 Info.Cursor = cursor;
7256 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007257 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007259 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 PostChildrenInfos.push_back(Info);
7261
7262 return CXChildVisit_Recurse;
7263}
7264
7265bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7266 if (PostChildrenInfos.empty())
7267 return false;
7268 const PostChildrenInfo &Info = PostChildrenInfos.back();
7269 if (!clang_equalCursors(Info.Cursor, cursor))
7270 return false;
7271
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007272 HandlePostPonedChildCursors(Info);
7273
Guy Benyei11169dd2012-12-18 14:30:41 +00007274 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7275 const unsigned AfterChildren = NextToken();
7276 SourceRange cursorRange = Info.CursorRange;
7277
7278 // Scan the tokens that are at the end of the cursor, but are not captured
7279 // but the child cursors.
7280 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7281
7282 // Scan the tokens that are at the beginning of the cursor, but are not
7283 // capture by the child cursors.
7284 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7285 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7286 break;
7287
7288 Cursors[I] = cursor;
7289 }
7290
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007291 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7292 // encountered the attribute cursor.
7293 if (clang_isAttribute(cursor.kind))
7294 TokIdx = Info.BeforeReachingCursorIdx;
7295
Guy Benyei11169dd2012-12-18 14:30:41 +00007296 PostChildrenInfos.pop_back();
7297 return false;
7298}
7299
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007300void AnnotateTokensWorker::HandlePostPonedChildCursors(
7301 const PostChildrenInfo &Info) {
7302 for (const auto &ChildAction : Info.ChildActions) {
7303 if (ChildAction.action == PostChildrenAction::Postpone) {
7304 HandlePostPonedChildCursor(ChildAction.cursor,
7305 Info.BeforeChildrenTokenIdx);
7306 }
7307 }
7308}
7309
7310void AnnotateTokensWorker::HandlePostPonedChildCursor(
7311 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007312 unsigned I = StartTokenIndex;
7313
7314 // The bracket tokens of a Call or Subscript operator are mapped to
7315 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7316 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7317 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007318 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7319 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007320 if (clang_Range_isNull(CXRefNameRange))
7321 break; // All ranges handled.
7322
7323 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7324 while (I < NumTokens) {
7325 const SourceLocation TokenLocation = GetTokenLoc(I);
7326 if (!TokenLocation.isValid())
7327 break;
7328
7329 // Adapt the end range, because LocationCompare() reports
7330 // RangeOverlap even for the not-inclusive end location.
7331 const SourceLocation fixedEnd =
7332 RefNameRange.getEnd().getLocWithOffset(-1);
7333 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7334
7335 const RangeComparisonResult ComparisonResult =
7336 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7337
7338 if (ComparisonResult == RangeOverlap) {
7339 Cursors[I++] = Cursor;
7340 } else if (ComparisonResult == RangeBefore) {
7341 ++I; // Not relevant token, check next one.
7342 } else if (ComparisonResult == RangeAfter) {
7343 break; // All tokens updated for current range, check next.
7344 }
7345 }
7346 }
7347}
7348
Guy Benyei11169dd2012-12-18 14:30:41 +00007349static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7350 CXCursor parent,
7351 CXClientData client_data) {
7352 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7353}
7354
7355static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7356 CXClientData client_data) {
7357 return static_cast<AnnotateTokensWorker*>(client_data)->
7358 postVisitChildren(cursor);
7359}
7360
7361namespace {
7362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007363/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007364/// and mark tokens that are macro arguments. This info is used by the
7365/// AnnotateTokensWorker.
7366class MarkMacroArgTokensVisitor {
7367 SourceManager &SM;
7368 CXToken *Tokens;
7369 unsigned NumTokens;
7370 unsigned CurIdx;
7371
7372public:
7373 MarkMacroArgTokensVisitor(SourceManager &SM,
7374 CXToken *tokens, unsigned numTokens)
7375 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7376
7377 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7378 if (cursor.kind != CXCursor_MacroExpansion)
7379 return CXChildVisit_Continue;
7380
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007381 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007382 if (macroRange.getBegin() == macroRange.getEnd())
7383 return CXChildVisit_Continue; // it's not a function macro.
7384
7385 for (; CurIdx < NumTokens; ++CurIdx) {
7386 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7387 macroRange.getBegin()))
7388 break;
7389 }
7390
7391 if (CurIdx == NumTokens)
7392 return CXChildVisit_Break;
7393
7394 for (; CurIdx < NumTokens; ++CurIdx) {
7395 SourceLocation tokLoc = getTokenLoc(CurIdx);
7396 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7397 break;
7398
7399 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7400 }
7401
7402 if (CurIdx == NumTokens)
7403 return CXChildVisit_Break;
7404
7405 return CXChildVisit_Continue;
7406 }
7407
7408private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007409 CXToken &getTok(unsigned Idx) {
7410 assert(Idx < NumTokens);
7411 return Tokens[Idx];
7412 }
7413 const CXToken &getTok(unsigned Idx) const {
7414 assert(Idx < NumTokens);
7415 return Tokens[Idx];
7416 }
7417
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007419 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007420 }
7421
7422 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7423 // The third field is reserved and currently not used. Use it here
7424 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007425 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007426 }
7427};
7428
7429} // end anonymous namespace
7430
7431static CXChildVisitResult
7432MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7433 CXClientData client_data) {
7434 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7435 parent);
7436}
7437
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007438/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007439/// \returns true if lexing was finished, false otherwise.
7440static bool lexNext(Lexer &Lex, Token &Tok,
7441 unsigned &NextIdx, unsigned NumTokens) {
7442 if (NextIdx >= NumTokens)
7443 return true;
7444
7445 ++NextIdx;
7446 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007447 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007448}
7449
Guy Benyei11169dd2012-12-18 14:30:41 +00007450static void annotatePreprocessorTokens(CXTranslationUnit TU,
7451 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007452 CXCursor *Cursors,
7453 CXToken *Tokens,
7454 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007455 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007456
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007457 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007458 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7459 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007460 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007461 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007462 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007463
7464 if (BeginLocInfo.first != EndLocInfo.first)
7465 return;
7466
7467 StringRef Buffer;
7468 bool Invalid = false;
7469 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7470 if (Buffer.empty() || Invalid)
7471 return;
7472
7473 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7474 CXXUnit->getASTContext().getLangOpts(),
7475 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7476 Buffer.end());
7477 Lex.SetCommentRetentionState(true);
7478
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007479 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007480 // Lex tokens in raw mode until we hit the end of the range, to avoid
7481 // entering #includes or expanding macros.
7482 while (true) {
7483 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007484 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7485 break;
7486 unsigned TokIdx = NextIdx-1;
7487 assert(Tok.getLocation() ==
7488 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007489
7490 reprocess:
7491 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007492 // We have found a preprocessing directive. Annotate the tokens
7493 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007494 //
7495 // FIXME: Some simple tests here could identify macro definitions and
7496 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007497
7498 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007499 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7500 break;
7501
Craig Topper69186e72014-06-08 08:38:04 +00007502 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007503 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007504 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7505 break;
7506
7507 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007508 IdentifierInfo &II =
7509 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007510 SourceLocation MappedTokLoc =
7511 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7512 MI = getMacroInfo(II, MappedTokLoc, TU);
7513 }
7514 }
7515
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007516 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007517 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007518 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7519 finished = true;
7520 break;
7521 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007522 // If we are in a macro definition, check if the token was ever a
7523 // macro name and annotate it if that's the case.
7524 if (MI) {
7525 SourceLocation SaveLoc = Tok.getLocation();
7526 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007527 MacroDefinitionRecord *MacroDef =
7528 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007529 Tok.setLocation(SaveLoc);
7530 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007531 Cursors[NextIdx - 1] =
7532 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007533 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007534 } while (!Tok.isAtStartOfLine());
7535
7536 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7537 assert(TokIdx <= LastIdx);
7538 SourceLocation EndLoc =
7539 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7540 CXCursor Cursor =
7541 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7542
7543 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007544 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007545
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007546 if (finished)
7547 break;
7548 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007549 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007550 }
7551}
7552
7553// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007554static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7555 CXToken *Tokens, unsigned NumTokens,
7556 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007557 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007558 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7559 setThreadBackgroundPriority();
7560
7561 // Determine the region of interest, which contains all of the tokens.
7562 SourceRange RegionOfInterest;
7563 RegionOfInterest.setBegin(
7564 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7565 RegionOfInterest.setEnd(
7566 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7567 Tokens[NumTokens-1])));
7568
Guy Benyei11169dd2012-12-18 14:30:41 +00007569 // Relex the tokens within the source range to look for preprocessing
7570 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007571 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007572
7573 // If begin location points inside a macro argument, set it to the expansion
7574 // location so we can have the full context when annotating semantically.
7575 {
7576 SourceManager &SM = CXXUnit->getSourceManager();
7577 SourceLocation Loc =
7578 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7579 if (Loc.isMacroID())
7580 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7581 }
7582
Guy Benyei11169dd2012-12-18 14:30:41 +00007583 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7584 // Search and mark tokens that are macro argument expansions.
7585 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7586 Tokens, NumTokens);
7587 CursorVisitor MacroArgMarker(TU,
7588 MarkMacroArgTokensVisitorDelegate, &Visitor,
7589 /*VisitPreprocessorLast=*/true,
7590 /*VisitIncludedEntities=*/false,
7591 RegionOfInterest);
7592 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7593 }
7594
7595 // Annotate all of the source locations in the region of interest that map to
7596 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007597 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007598
7599 // FIXME: We use a ridiculous stack size here because the data-recursion
7600 // algorithm uses a large stack frame than the non-data recursive version,
7601 // and AnnotationTokensWorker currently transforms the data-recursion
7602 // algorithm back into a traditional recursion by explicitly calling
7603 // VisitChildren(). We will need to remove this explicit recursive call.
7604 W.AnnotateTokens();
7605
7606 // If we ran into any entities that involve context-sensitive keywords,
7607 // take another pass through the tokens to mark them as such.
7608 if (W.hasContextSensitiveKeywords()) {
7609 for (unsigned I = 0; I != NumTokens; ++I) {
7610 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7611 continue;
7612
7613 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7614 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007615 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007616 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7617 if (Property->getPropertyAttributesAsWritten() != 0 &&
7618 llvm::StringSwitch<bool>(II->getName())
7619 .Case("readonly", true)
7620 .Case("assign", true)
7621 .Case("unsafe_unretained", true)
7622 .Case("readwrite", true)
7623 .Case("retain", true)
7624 .Case("copy", true)
7625 .Case("nonatomic", true)
7626 .Case("atomic", true)
7627 .Case("getter", true)
7628 .Case("setter", true)
7629 .Case("strong", true)
7630 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007631 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007632 .Default(false))
7633 Tokens[I].int_data[0] = CXToken_Keyword;
7634 }
7635 continue;
7636 }
7637
7638 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7639 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7640 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7641 if (llvm::StringSwitch<bool>(II->getName())
7642 .Case("in", true)
7643 .Case("out", true)
7644 .Case("inout", true)
7645 .Case("oneway", true)
7646 .Case("bycopy", true)
7647 .Case("byref", true)
7648 .Default(false))
7649 Tokens[I].int_data[0] = CXToken_Keyword;
7650 continue;
7651 }
7652
7653 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7654 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7655 Tokens[I].int_data[0] = CXToken_Keyword;
7656 continue;
7657 }
7658 }
7659 }
7660}
7661
Guy Benyei11169dd2012-12-18 14:30:41 +00007662void clang_annotateTokens(CXTranslationUnit TU,
7663 CXToken *Tokens, unsigned NumTokens,
7664 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007665 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007666 LOG_BAD_TU(TU);
7667 return;
7668 }
7669 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007670 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007671 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007672 }
7673
7674 LOG_FUNC_SECTION {
7675 *Log << TU << ' ';
7676 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7677 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7678 *Log << clang_getRange(bloc, eloc);
7679 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007680
7681 // Any token we don't specifically annotate will have a NULL cursor.
7682 CXCursor C = clang_getNullCursor();
7683 for (unsigned I = 0; I != NumTokens; ++I)
7684 Cursors[I] = C;
7685
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007686 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007687 if (!CXXUnit)
7688 return;
7689
7690 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007691
7692 auto AnnotateTokensImpl = [=]() {
7693 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7694 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007695 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007696 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007697 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7698 }
7699}
7700
Guy Benyei11169dd2012-12-18 14:30:41 +00007701//===----------------------------------------------------------------------===//
7702// Operations for querying linkage of a cursor.
7703//===----------------------------------------------------------------------===//
7704
Guy Benyei11169dd2012-12-18 14:30:41 +00007705CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7706 if (!clang_isDeclaration(cursor.kind))
7707 return CXLinkage_Invalid;
7708
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007709 const Decl *D = cxcursor::getCursorDecl(cursor);
7710 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007711 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007712 case NoLinkage:
7713 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007714 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007715 case InternalLinkage: return CXLinkage_Internal;
7716 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007717 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 case ExternalLinkage: return CXLinkage_External;
7719 };
7720
7721 return CXLinkage_Invalid;
7722}
Guy Benyei11169dd2012-12-18 14:30:41 +00007723
7724//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007725// Operations for querying visibility of a cursor.
7726//===----------------------------------------------------------------------===//
7727
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007728CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7729 if (!clang_isDeclaration(cursor.kind))
7730 return CXVisibility_Invalid;
7731
7732 const Decl *D = cxcursor::getCursorDecl(cursor);
7733 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7734 switch (ND->getVisibility()) {
7735 case HiddenVisibility: return CXVisibility_Hidden;
7736 case ProtectedVisibility: return CXVisibility_Protected;
7737 case DefaultVisibility: return CXVisibility_Default;
7738 };
7739
7740 return CXVisibility_Invalid;
7741}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007742
7743//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007744// Operations for querying language of a cursor.
7745//===----------------------------------------------------------------------===//
7746
7747static CXLanguageKind getDeclLanguage(const Decl *D) {
7748 if (!D)
7749 return CXLanguage_C;
7750
7751 switch (D->getKind()) {
7752 default:
7753 break;
7754 case Decl::ImplicitParam:
7755 case Decl::ObjCAtDefsField:
7756 case Decl::ObjCCategory:
7757 case Decl::ObjCCategoryImpl:
7758 case Decl::ObjCCompatibleAlias:
7759 case Decl::ObjCImplementation:
7760 case Decl::ObjCInterface:
7761 case Decl::ObjCIvar:
7762 case Decl::ObjCMethod:
7763 case Decl::ObjCProperty:
7764 case Decl::ObjCPropertyImpl:
7765 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007766 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007767 return CXLanguage_ObjC;
7768 case Decl::CXXConstructor:
7769 case Decl::CXXConversion:
7770 case Decl::CXXDestructor:
7771 case Decl::CXXMethod:
7772 case Decl::CXXRecord:
7773 case Decl::ClassTemplate:
7774 case Decl::ClassTemplatePartialSpecialization:
7775 case Decl::ClassTemplateSpecialization:
7776 case Decl::Friend:
7777 case Decl::FriendTemplate:
7778 case Decl::FunctionTemplate:
7779 case Decl::LinkageSpec:
7780 case Decl::Namespace:
7781 case Decl::NamespaceAlias:
7782 case Decl::NonTypeTemplateParm:
7783 case Decl::StaticAssert:
7784 case Decl::TemplateTemplateParm:
7785 case Decl::TemplateTypeParm:
7786 case Decl::UnresolvedUsingTypename:
7787 case Decl::UnresolvedUsingValue:
7788 case Decl::Using:
7789 case Decl::UsingDirective:
7790 case Decl::UsingShadow:
7791 return CXLanguage_CPlusPlus;
7792 }
7793
7794 return CXLanguage_C;
7795}
7796
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007797static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7798 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007799 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007800
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007801 switch (D->getAvailability()) {
7802 case AR_Available:
7803 case AR_NotYetIntroduced:
7804 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007805 return getCursorAvailabilityForDecl(
7806 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007807 return CXAvailability_Available;
7808
7809 case AR_Deprecated:
7810 return CXAvailability_Deprecated;
7811
7812 case AR_Unavailable:
7813 return CXAvailability_NotAvailable;
7814 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007815
7816 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007817}
7818
Guy Benyei11169dd2012-12-18 14:30:41 +00007819enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7820 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007821 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7822 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007823
7824 return CXAvailability_Available;
7825}
7826
7827static CXVersion convertVersion(VersionTuple In) {
7828 CXVersion Out = { -1, -1, -1 };
7829 if (In.empty())
7830 return Out;
7831
7832 Out.Major = In.getMajor();
7833
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007834 Optional<unsigned> Minor = In.getMinor();
7835 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007836 Out.Minor = *Minor;
7837 else
7838 return Out;
7839
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007840 Optional<unsigned> Subminor = In.getSubminor();
7841 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007842 Out.Subminor = *Subminor;
7843
7844 return Out;
7845}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007846
Alex Lorenz1345ea22017-06-12 19:06:30 +00007847static void getCursorPlatformAvailabilityForDecl(
7848 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7849 int *always_unavailable, CXString *unavailable_message,
7850 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007851 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007852 for (auto A : D->attrs()) {
7853 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007854 HadAvailAttr = true;
7855 if (always_deprecated)
7856 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007857 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007858 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007859 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007860 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007861 continue;
7862 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007863
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007864 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007865 HadAvailAttr = true;
7866 if (always_unavailable)
7867 *always_unavailable = 1;
7868 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007869 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007870 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7871 }
7872 continue;
7873 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007874
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007875 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007876 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007877 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007878 }
7879 }
7880
7881 if (!HadAvailAttr)
7882 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7883 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007884 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7885 deprecated_message, always_unavailable, unavailable_message,
7886 AvailabilityAttrs);
7887
7888 if (AvailabilityAttrs.empty())
7889 return;
7890
Fangrui Song55fab262018-09-26 22:16:28 +00007891 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007892 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7893 return LHS->getPlatform()->getName() <
7894 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007895 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007896 ASTContext &Ctx = D->getASTContext();
7897 auto It = std::unique(
7898 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7899 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7900 if (LHS->getPlatform() != RHS->getPlatform())
7901 return false;
7902
7903 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7904 LHS->getDeprecated() == RHS->getDeprecated() &&
7905 LHS->getObsoleted() == RHS->getObsoleted() &&
7906 LHS->getMessage() == RHS->getMessage() &&
7907 LHS->getReplacement() == RHS->getReplacement())
7908 return true;
7909
7910 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7911 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7912 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7913 return false;
7914
7915 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7916 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7917
7918 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7919 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7920 if (LHS->getMessage().empty())
7921 LHS->setMessage(Ctx, RHS->getMessage());
7922 if (LHS->getReplacement().empty())
7923 LHS->setReplacement(Ctx, RHS->getReplacement());
7924 }
7925
7926 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7927 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7928 if (LHS->getMessage().empty())
7929 LHS->setMessage(Ctx, RHS->getMessage());
7930 if (LHS->getReplacement().empty())
7931 LHS->setReplacement(Ctx, RHS->getReplacement());
7932 }
7933
7934 return true;
7935 });
7936 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007937}
7938
Alex Lorenz1345ea22017-06-12 19:06:30 +00007939int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 CXString *deprecated_message,
7941 int *always_unavailable,
7942 CXString *unavailable_message,
7943 CXPlatformAvailability *availability,
7944 int availability_size) {
7945 if (always_deprecated)
7946 *always_deprecated = 0;
7947 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007948 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007949 if (always_unavailable)
7950 *always_unavailable = 0;
7951 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007952 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007953
Guy Benyei11169dd2012-12-18 14:30:41 +00007954 if (!clang_isDeclaration(cursor.kind))
7955 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007956
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007957 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007958 if (!D)
7959 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007960
Alex Lorenz1345ea22017-06-12 19:06:30 +00007961 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7962 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7963 always_unavailable, unavailable_message,
7964 AvailabilityAttrs);
7965 for (const auto &Avail :
7966 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7967 .take_front(availability_size))) {
7968 availability[Avail.index()].Platform =
7969 cxstring::createDup(Avail.value()->getPlatform()->getName());
7970 availability[Avail.index()].Introduced =
7971 convertVersion(Avail.value()->getIntroduced());
7972 availability[Avail.index()].Deprecated =
7973 convertVersion(Avail.value()->getDeprecated());
7974 availability[Avail.index()].Obsoleted =
7975 convertVersion(Avail.value()->getObsoleted());
7976 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7977 availability[Avail.index()].Message =
7978 cxstring::createDup(Avail.value()->getMessage());
7979 }
7980
7981 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007982}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007983
Guy Benyei11169dd2012-12-18 14:30:41 +00007984void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7985 clang_disposeString(availability->Platform);
7986 clang_disposeString(availability->Message);
7987}
7988
7989CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7990 if (clang_isDeclaration(cursor.kind))
7991 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7992
7993 return CXLanguage_Invalid;
7994}
7995
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007996CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7997 const Decl *D = cxcursor::getCursorDecl(cursor);
7998 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7999 switch (VD->getTLSKind()) {
8000 case VarDecl::TLS_None:
8001 return CXTLS_None;
8002 case VarDecl::TLS_Dynamic:
8003 return CXTLS_Dynamic;
8004 case VarDecl::TLS_Static:
8005 return CXTLS_Static;
8006 }
8007 }
8008
8009 return CXTLS_None;
8010}
8011
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008012 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008013 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008014 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008015static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008016 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008017 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008018
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008019 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008020 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8021 return FunTmpl;
8022
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008023 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008024 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8025 return ClassTmpl;
8026
8027 return D;
8028}
8029
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008030
8031enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8032 StorageClass sc = SC_None;
8033 const Decl *D = getCursorDecl(C);
8034 if (D) {
8035 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8036 sc = FD->getStorageClass();
8037 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8038 sc = VD->getStorageClass();
8039 } else {
8040 return CX_SC_Invalid;
8041 }
8042 } else {
8043 return CX_SC_Invalid;
8044 }
8045 switch (sc) {
8046 case SC_None:
8047 return CX_SC_None;
8048 case SC_Extern:
8049 return CX_SC_Extern;
8050 case SC_Static:
8051 return CX_SC_Static;
8052 case SC_PrivateExtern:
8053 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008054 case SC_Auto:
8055 return CX_SC_Auto;
8056 case SC_Register:
8057 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008058 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008059 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008060}
8061
Guy Benyei11169dd2012-12-18 14:30:41 +00008062CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8063 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008064 if (const Decl *D = getCursorDecl(cursor)) {
8065 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008066 if (!DC)
8067 return clang_getNullCursor();
8068
8069 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8070 getCursorTU(cursor));
8071 }
8072 }
8073
8074 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008075 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008076 return MakeCXCursor(D, getCursorTU(cursor));
8077 }
8078
8079 return clang_getNullCursor();
8080}
8081
8082CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8083 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008084 if (const Decl *D = getCursorDecl(cursor)) {
8085 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008086 if (!DC)
8087 return clang_getNullCursor();
8088
8089 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8090 getCursorTU(cursor));
8091 }
8092 }
8093
8094 // FIXME: Note that we can't easily compute the lexical context of a
8095 // statement or expression, so we return nothing.
8096 return clang_getNullCursor();
8097}
8098
8099CXFile clang_getIncludedFile(CXCursor cursor) {
8100 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008101 return nullptr;
8102
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008103 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008104 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008105}
8106
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008107unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8108 if (C.kind != CXCursor_ObjCPropertyDecl)
8109 return CXObjCPropertyAttr_noattr;
8110
8111 unsigned Result = CXObjCPropertyAttr_noattr;
8112 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8113 ObjCPropertyDecl::PropertyAttributeKind Attr =
8114 PD->getPropertyAttributesAsWritten();
8115
8116#define SET_CXOBJCPROP_ATTR(A) \
8117 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8118 Result |= CXObjCPropertyAttr_##A
8119 SET_CXOBJCPROP_ATTR(readonly);
8120 SET_CXOBJCPROP_ATTR(getter);
8121 SET_CXOBJCPROP_ATTR(assign);
8122 SET_CXOBJCPROP_ATTR(readwrite);
8123 SET_CXOBJCPROP_ATTR(retain);
8124 SET_CXOBJCPROP_ATTR(copy);
8125 SET_CXOBJCPROP_ATTR(nonatomic);
8126 SET_CXOBJCPROP_ATTR(setter);
8127 SET_CXOBJCPROP_ATTR(atomic);
8128 SET_CXOBJCPROP_ATTR(weak);
8129 SET_CXOBJCPROP_ATTR(strong);
8130 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008131 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008132#undef SET_CXOBJCPROP_ATTR
8133
8134 return Result;
8135}
8136
Michael Wu6e88f532018-08-03 05:38:29 +00008137CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8138 if (C.kind != CXCursor_ObjCPropertyDecl)
8139 return cxstring::createNull();
8140
8141 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8142 Selector sel = PD->getGetterName();
8143 if (sel.isNull())
8144 return cxstring::createNull();
8145
8146 return cxstring::createDup(sel.getAsString());
8147}
8148
8149CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8150 if (C.kind != CXCursor_ObjCPropertyDecl)
8151 return cxstring::createNull();
8152
8153 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8154 Selector sel = PD->getSetterName();
8155 if (sel.isNull())
8156 return cxstring::createNull();
8157
8158 return cxstring::createDup(sel.getAsString());
8159}
8160
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008161unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8162 if (!clang_isDeclaration(C.kind))
8163 return CXObjCDeclQualifier_None;
8164
8165 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8166 const Decl *D = getCursorDecl(C);
8167 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8168 QT = MD->getObjCDeclQualifier();
8169 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8170 QT = PD->getObjCDeclQualifier();
8171 if (QT == Decl::OBJC_TQ_None)
8172 return CXObjCDeclQualifier_None;
8173
8174 unsigned Result = CXObjCDeclQualifier_None;
8175 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8176 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8177 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8178 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8179 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8180 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8181
8182 return Result;
8183}
8184
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008185unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8186 if (!clang_isDeclaration(C.kind))
8187 return 0;
8188
8189 const Decl *D = getCursorDecl(C);
8190 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8191 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8192 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8193 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8194
8195 return 0;
8196}
8197
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008198unsigned clang_Cursor_isVariadic(CXCursor C) {
8199 if (!clang_isDeclaration(C.kind))
8200 return 0;
8201
8202 const Decl *D = getCursorDecl(C);
8203 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8204 return FD->isVariadic();
8205 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8206 return MD->isVariadic();
8207
8208 return 0;
8209}
8210
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008211unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8212 CXString *language, CXString *definedIn,
8213 unsigned *isGenerated) {
8214 if (!clang_isDeclaration(C.kind))
8215 return 0;
8216
8217 const Decl *D = getCursorDecl(C);
8218
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008219 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008220 if (language)
8221 *language = cxstring::createDup(attr->getLanguage());
8222 if (definedIn)
8223 *definedIn = cxstring::createDup(attr->getDefinedIn());
8224 if (isGenerated)
8225 *isGenerated = attr->getGeneratedDeclaration();
8226 return 1;
8227 }
8228 return 0;
8229}
8230
Guy Benyei11169dd2012-12-18 14:30:41 +00008231CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8232 if (!clang_isDeclaration(C.kind))
8233 return clang_getNullRange();
8234
8235 const Decl *D = getCursorDecl(C);
8236 ASTContext &Context = getCursorContext(C);
8237 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8238 if (!RC)
8239 return clang_getNullRange();
8240
8241 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8242}
8243
8244CXString clang_Cursor_getRawCommentText(CXCursor C) {
8245 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008246 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008247
8248 const Decl *D = getCursorDecl(C);
8249 ASTContext &Context = getCursorContext(C);
8250 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8251 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8252 StringRef();
8253
8254 // Don't duplicate the string because RawText points directly into source
8255 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008256 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008257}
8258
8259CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8260 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008261 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008262
8263 const Decl *D = getCursorDecl(C);
8264 const ASTContext &Context = getCursorContext(C);
8265 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8266
8267 if (RC) {
8268 StringRef BriefText = RC->getBriefText(Context);
8269
8270 // Don't duplicate the string because RawComment ensures that this memory
8271 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008272 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008273 }
8274
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008275 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008276}
8277
Guy Benyei11169dd2012-12-18 14:30:41 +00008278CXModule clang_Cursor_getModule(CXCursor C) {
8279 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008280 if (const ImportDecl *ImportD =
8281 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008282 return ImportD->getImportedModule();
8283 }
8284
Craig Topper69186e72014-06-08 08:38:04 +00008285 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008286}
8287
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008288CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8289 if (isNotUsableTU(TU)) {
8290 LOG_BAD_TU(TU);
8291 return nullptr;
8292 }
8293 if (!File)
8294 return nullptr;
8295 FileEntry *FE = static_cast<FileEntry *>(File);
8296
8297 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8298 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8299 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8300
Richard Smithfeb54b62014-10-23 02:01:19 +00008301 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008302}
8303
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008304CXFile clang_Module_getASTFile(CXModule CXMod) {
8305 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008306 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008307 Module *Mod = static_cast<Module*>(CXMod);
8308 return const_cast<FileEntry *>(Mod->getASTFile());
8309}
8310
Guy Benyei11169dd2012-12-18 14:30:41 +00008311CXModule clang_Module_getParent(CXModule CXMod) {
8312 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008313 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008314 Module *Mod = static_cast<Module*>(CXMod);
8315 return Mod->Parent;
8316}
8317
8318CXString clang_Module_getName(CXModule CXMod) {
8319 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008320 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008321 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008322 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008323}
8324
8325CXString clang_Module_getFullName(CXModule CXMod) {
8326 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008327 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008328 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008329 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008330}
8331
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008332int clang_Module_isSystem(CXModule CXMod) {
8333 if (!CXMod)
8334 return 0;
8335 Module *Mod = static_cast<Module*>(CXMod);
8336 return Mod->IsSystem;
8337}
8338
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008339unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8340 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008341 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008342 LOG_BAD_TU(TU);
8343 return 0;
8344 }
8345 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008346 return 0;
8347 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008348 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8349 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8350 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008351}
8352
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008353CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8354 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008355 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008356 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008357 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008358 }
8359 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008360 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008361 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008362 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008363
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008364 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8365 if (Index < TopHeaders.size())
8366 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008367
Craig Topper69186e72014-06-08 08:38:04 +00008368 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008369}
8370
Guy Benyei11169dd2012-12-18 14:30:41 +00008371//===----------------------------------------------------------------------===//
8372// C++ AST instrospection.
8373//===----------------------------------------------------------------------===//
8374
Jonathan Coe29565352016-04-27 12:48:25 +00008375unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8376 if (!clang_isDeclaration(C.kind))
8377 return 0;
8378
8379 const Decl *D = cxcursor::getCursorDecl(C);
8380 const CXXConstructorDecl *Constructor =
8381 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8382 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8383}
8384
8385unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8386 if (!clang_isDeclaration(C.kind))
8387 return 0;
8388
8389 const Decl *D = cxcursor::getCursorDecl(C);
8390 const CXXConstructorDecl *Constructor =
8391 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8392 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8393}
8394
8395unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8396 if (!clang_isDeclaration(C.kind))
8397 return 0;
8398
8399 const Decl *D = cxcursor::getCursorDecl(C);
8400 const CXXConstructorDecl *Constructor =
8401 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8402 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8403}
8404
8405unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8406 if (!clang_isDeclaration(C.kind))
8407 return 0;
8408
8409 const Decl *D = cxcursor::getCursorDecl(C);
8410 const CXXConstructorDecl *Constructor =
8411 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8412 // Passing 'false' excludes constructors marked 'explicit'.
8413 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8414}
8415
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008416unsigned clang_CXXField_isMutable(CXCursor C) {
8417 if (!clang_isDeclaration(C.kind))
8418 return 0;
8419
8420 if (const auto D = cxcursor::getCursorDecl(C))
8421 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8422 return FD->isMutable() ? 1 : 0;
8423 return 0;
8424}
8425
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008426unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8427 if (!clang_isDeclaration(C.kind))
8428 return 0;
8429
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008430 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008431 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008432 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008433 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8434}
8435
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008436unsigned clang_CXXMethod_isConst(CXCursor C) {
8437 if (!clang_isDeclaration(C.kind))
8438 return 0;
8439
8440 const Decl *D = cxcursor::getCursorDecl(C);
8441 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008442 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008443 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008444}
8445
Jonathan Coe29565352016-04-27 12:48:25 +00008446unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8447 if (!clang_isDeclaration(C.kind))
8448 return 0;
8449
8450 const Decl *D = cxcursor::getCursorDecl(C);
8451 const CXXMethodDecl *Method =
8452 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8453 return (Method && Method->isDefaulted()) ? 1 : 0;
8454}
8455
Guy Benyei11169dd2012-12-18 14:30:41 +00008456unsigned clang_CXXMethod_isStatic(CXCursor C) {
8457 if (!clang_isDeclaration(C.kind))
8458 return 0;
8459
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008460 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008461 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008462 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008463 return (Method && Method->isStatic()) ? 1 : 0;
8464}
8465
8466unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8467 if (!clang_isDeclaration(C.kind))
8468 return 0;
8469
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008470 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008471 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008472 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008473 return (Method && Method->isVirtual()) ? 1 : 0;
8474}
Guy Benyei11169dd2012-12-18 14:30:41 +00008475
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008476unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8477 if (!clang_isDeclaration(C.kind))
8478 return 0;
8479
8480 const auto *D = cxcursor::getCursorDecl(C);
8481 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8482 if (RD)
8483 RD = RD->getDefinition();
8484 return (RD && RD->isAbstract()) ? 1 : 0;
8485}
8486
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008487unsigned clang_EnumDecl_isScoped(CXCursor C) {
8488 if (!clang_isDeclaration(C.kind))
8489 return 0;
8490
8491 const Decl *D = cxcursor::getCursorDecl(C);
8492 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8493 return (Enum && Enum->isScoped()) ? 1 : 0;
8494}
8495
Guy Benyei11169dd2012-12-18 14:30:41 +00008496//===----------------------------------------------------------------------===//
8497// Attribute introspection.
8498//===----------------------------------------------------------------------===//
8499
Guy Benyei11169dd2012-12-18 14:30:41 +00008500CXType clang_getIBOutletCollectionType(CXCursor C) {
8501 if (C.kind != CXCursor_IBOutletCollectionAttr)
8502 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8503
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008504 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008505 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8506
8507 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8508}
Guy Benyei11169dd2012-12-18 14:30:41 +00008509
8510//===----------------------------------------------------------------------===//
8511// Inspecting memory usage.
8512//===----------------------------------------------------------------------===//
8513
8514typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8515
8516static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8517 enum CXTUResourceUsageKind k,
8518 unsigned long amount) {
8519 CXTUResourceUsageEntry entry = { k, amount };
8520 entries.push_back(entry);
8521}
8522
Guy Benyei11169dd2012-12-18 14:30:41 +00008523const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8524 const char *str = "";
8525 switch (kind) {
8526 case CXTUResourceUsage_AST:
8527 str = "ASTContext: expressions, declarations, and types";
8528 break;
8529 case CXTUResourceUsage_Identifiers:
8530 str = "ASTContext: identifiers";
8531 break;
8532 case CXTUResourceUsage_Selectors:
8533 str = "ASTContext: selectors";
8534 break;
8535 case CXTUResourceUsage_GlobalCompletionResults:
8536 str = "Code completion: cached global results";
8537 break;
8538 case CXTUResourceUsage_SourceManagerContentCache:
8539 str = "SourceManager: content cache allocator";
8540 break;
8541 case CXTUResourceUsage_AST_SideTables:
8542 str = "ASTContext: side tables";
8543 break;
8544 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8545 str = "SourceManager: malloc'ed memory buffers";
8546 break;
8547 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8548 str = "SourceManager: mmap'ed memory buffers";
8549 break;
8550 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8551 str = "ExternalASTSource: malloc'ed memory buffers";
8552 break;
8553 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8554 str = "ExternalASTSource: mmap'ed memory buffers";
8555 break;
8556 case CXTUResourceUsage_Preprocessor:
8557 str = "Preprocessor: malloc'ed memory";
8558 break;
8559 case CXTUResourceUsage_PreprocessingRecord:
8560 str = "Preprocessor: PreprocessingRecord";
8561 break;
8562 case CXTUResourceUsage_SourceManager_DataStructures:
8563 str = "SourceManager: data structures and tables";
8564 break;
8565 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8566 str = "Preprocessor: header search tables";
8567 break;
8568 }
8569 return str;
8570}
8571
8572CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008573 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008574 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008575 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008576 return usage;
8577 }
8578
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008579 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008580 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008581 ASTContext &astContext = astUnit->getASTContext();
8582
8583 // How much memory is used by AST nodes and types?
8584 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8585 (unsigned long) astContext.getASTAllocatedMemory());
8586
8587 // How much memory is used by identifiers?
8588 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8589 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8590
8591 // How much memory is used for selectors?
8592 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8593 (unsigned long) astContext.Selectors.getTotalMemory());
8594
8595 // How much memory is used by ASTContext's side tables?
8596 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8597 (unsigned long) astContext.getSideTableAllocatedMemory());
8598
8599 // How much memory is used for caching global code completion results?
8600 unsigned long completionBytes = 0;
8601 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008602 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008603 completionBytes = completionAllocator->getTotalMemory();
8604 }
8605 createCXTUResourceUsageEntry(*entries,
8606 CXTUResourceUsage_GlobalCompletionResults,
8607 completionBytes);
8608
8609 // How much memory is being used by SourceManager's content cache?
8610 createCXTUResourceUsageEntry(*entries,
8611 CXTUResourceUsage_SourceManagerContentCache,
8612 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8613
8614 // How much memory is being used by the MemoryBuffer's in SourceManager?
8615 const SourceManager::MemoryBufferSizes &srcBufs =
8616 astUnit->getSourceManager().getMemoryBufferSizes();
8617
8618 createCXTUResourceUsageEntry(*entries,
8619 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8620 (unsigned long) srcBufs.malloc_bytes);
8621 createCXTUResourceUsageEntry(*entries,
8622 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8623 (unsigned long) srcBufs.mmap_bytes);
8624 createCXTUResourceUsageEntry(*entries,
8625 CXTUResourceUsage_SourceManager_DataStructures,
8626 (unsigned long) astContext.getSourceManager()
8627 .getDataStructureSizes());
8628
8629 // How much memory is being used by the ExternalASTSource?
8630 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8631 const ExternalASTSource::MemoryBufferSizes &sizes =
8632 esrc->getMemoryBufferSizes();
8633
8634 createCXTUResourceUsageEntry(*entries,
8635 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8636 (unsigned long) sizes.malloc_bytes);
8637 createCXTUResourceUsageEntry(*entries,
8638 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8639 (unsigned long) sizes.mmap_bytes);
8640 }
8641
8642 // How much memory is being used by the Preprocessor?
8643 Preprocessor &pp = astUnit->getPreprocessor();
8644 createCXTUResourceUsageEntry(*entries,
8645 CXTUResourceUsage_Preprocessor,
8646 pp.getTotalMemory());
8647
8648 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8649 createCXTUResourceUsageEntry(*entries,
8650 CXTUResourceUsage_PreprocessingRecord,
8651 pRec->getTotalMemory());
8652 }
8653
8654 createCXTUResourceUsageEntry(*entries,
8655 CXTUResourceUsage_Preprocessor_HeaderSearch,
8656 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008657
Guy Benyei11169dd2012-12-18 14:30:41 +00008658 CXTUResourceUsage usage = { (void*) entries.get(),
8659 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008660 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008661 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008662 return usage;
8663}
8664
8665void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8666 if (usage.data)
8667 delete (MemUsageEntries*) usage.data;
8668}
8669
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008670CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8671 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008672 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008673 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008674
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008675 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008676 LOG_BAD_TU(TU);
8677 return skipped;
8678 }
8679
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008680 if (!file)
8681 return skipped;
8682
8683 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8684 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8685 if (!ppRec)
8686 return skipped;
8687
8688 ASTContext &Ctx = astUnit->getASTContext();
8689 SourceManager &sm = Ctx.getSourceManager();
8690 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8691 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008692 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008693
8694 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8695 std::vector<SourceRange> wantedRanges;
8696 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8697 i != ei; ++i) {
8698 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8699 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008700 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8701 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008702 }
8703
8704 skipped->count = wantedRanges.size();
8705 skipped->ranges = new CXSourceRange[skipped->count];
8706 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8707 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8708
8709 return skipped;
8710}
8711
Cameron Desrochersd8091282016-08-18 15:43:55 +00008712CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8713 CXSourceRangeList *skipped = new CXSourceRangeList;
8714 skipped->count = 0;
8715 skipped->ranges = nullptr;
8716
8717 if (isNotUsableTU(TU)) {
8718 LOG_BAD_TU(TU);
8719 return skipped;
8720 }
8721
8722 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8723 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8724 if (!ppRec)
8725 return skipped;
8726
8727 ASTContext &Ctx = astUnit->getASTContext();
8728
8729 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8730
8731 skipped->count = SkippedRanges.size();
8732 skipped->ranges = new CXSourceRange[skipped->count];
8733 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8734 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8735
8736 return skipped;
8737}
8738
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008739void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8740 if (ranges) {
8741 delete[] ranges->ranges;
8742 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008743 }
8744}
8745
Guy Benyei11169dd2012-12-18 14:30:41 +00008746void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8747 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8748 for (unsigned I = 0; I != Usage.numEntries; ++I)
8749 fprintf(stderr, " %s: %lu\n",
8750 clang_getTUResourceUsageName(Usage.entries[I].kind),
8751 Usage.entries[I].amount);
8752
8753 clang_disposeCXTUResourceUsage(Usage);
8754}
8755
8756//===----------------------------------------------------------------------===//
8757// Misc. utility functions.
8758//===----------------------------------------------------------------------===//
8759
Richard Smith0a7b2972018-07-03 21:34:13 +00008760/// Default to using our desired 8 MB stack size on "safety" threads.
8761static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008762
8763namespace clang {
8764
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008765bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008766 unsigned Size) {
8767 if (!Size)
8768 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008769 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008770 return CRC.RunSafelyOnThread(Fn, Size);
8771 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008772}
8773
8774unsigned GetSafetyThreadStackSize() {
8775 return SafetyStackThreadSize;
8776}
8777
8778void SetSafetyThreadStackSize(unsigned Value) {
8779 SafetyStackThreadSize = Value;
8780}
8781
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008782}
Guy Benyei11169dd2012-12-18 14:30:41 +00008783
8784void clang::setThreadBackgroundPriority() {
8785 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8786 return;
8787
Nico Weber18cfd9f2019-04-21 19:18:41 +00008788#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008789 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008790#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008791}
8792
8793void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8794 if (!Unit)
8795 return;
8796
8797 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8798 DEnd = Unit->stored_diag_end();
8799 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008800 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008801 CXString Msg = clang_formatDiagnostic(&Diag,
8802 clang_defaultDiagnosticDisplayOptions());
8803 fprintf(stderr, "%s\n", clang_getCString(Msg));
8804 clang_disposeString(Msg);
8805 }
Nico Weber1865df42018-04-27 19:11:14 +00008806#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008807 // On Windows, force a flush, since there may be multiple copies of
8808 // stderr and stdout in the file system, all with different buffers
8809 // but writing to the same device.
8810 fflush(stderr);
8811#endif
8812}
8813
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008814MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8815 SourceLocation MacroDefLoc,
8816 CXTranslationUnit TU){
8817 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008818 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008819 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008820 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008821
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008822 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008823 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008824 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008825 if (MD) {
8826 for (MacroDirective::DefInfo
8827 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8828 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8829 return Def.getMacroInfo();
8830 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008831 }
8832
Craig Topper69186e72014-06-08 08:38:04 +00008833 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008834}
8835
Richard Smith66a81862015-05-04 02:25:31 +00008836const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008837 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008838 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008839 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008840 const IdentifierInfo *II = MacroDef->getName();
8841 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008842 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008843
8844 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8845}
8846
Richard Smith66a81862015-05-04 02:25:31 +00008847MacroDefinitionRecord *
8848cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8849 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008850 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008851 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008852 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008853 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008854
8855 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008856 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008857 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8858 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008859 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008860
8861 // Check that the token is inside the definition and not its argument list.
8862 SourceManager &SM = Unit->getSourceManager();
8863 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008864 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008865 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008866 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008867
8868 Preprocessor &PP = Unit->getPreprocessor();
8869 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8870 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008871 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008872
Alp Toker2d57cea2014-05-17 04:53:25 +00008873 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008874 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008875 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008876
8877 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008878 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008879 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008880
Richard Smith20e883e2015-04-29 23:20:19 +00008881 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008882 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008883 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008884
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008885 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008886}
8887
Richard Smith66a81862015-05-04 02:25:31 +00008888MacroDefinitionRecord *
8889cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8890 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008891 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008892 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008893
8894 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008895 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008896 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008897 Preprocessor &PP = Unit->getPreprocessor();
8898 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008899 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008900 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8901 Token Tok;
8902 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008903 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008904
8905 return checkForMacroInMacroDefinition(MI, Tok, TU);
8906}
8907
Guy Benyei11169dd2012-12-18 14:30:41 +00008908CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008909 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008910}
8911
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008912Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8913 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008914 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008915 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008916 if (Unit->isMainFileAST())
8917 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008918 return *this;
8919 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008920 } else {
8921 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008922 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008923 return *this;
8924}
8925
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008926Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8927 *this << FE->getName();
8928 return *this;
8929}
8930
8931Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8932 CXString cursorName = clang_getCursorDisplayName(cursor);
8933 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8934 clang_disposeString(cursorName);
8935 return *this;
8936}
8937
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008938Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8939 CXFile File;
8940 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008941 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008942 CXString FileName = clang_getFileName(File);
8943 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8944 clang_disposeString(FileName);
8945 return *this;
8946}
8947
8948Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8949 CXSourceLocation BLoc = clang_getRangeStart(range);
8950 CXSourceLocation ELoc = clang_getRangeEnd(range);
8951
8952 CXFile BFile;
8953 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008954 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008955
8956 CXFile EFile;
8957 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008958 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008959
8960 CXString BFileName = clang_getFileName(BFile);
8961 if (BFile == EFile) {
8962 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8963 BLine, BColumn, ELine, EColumn);
8964 } else {
8965 CXString EFileName = clang_getFileName(EFile);
8966 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8967 BLine, BColumn)
8968 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8969 ELine, EColumn);
8970 clang_disposeString(EFileName);
8971 }
8972 clang_disposeString(BFileName);
8973 return *this;
8974}
8975
8976Logger &cxindex::Logger::operator<<(CXString Str) {
8977 *this << clang_getCString(Str);
8978 return *this;
8979}
8980
8981Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8982 LogOS << Fmt;
8983 return *this;
8984}
8985
Benjamin Kramer762bc332019-08-07 14:44:40 +00008986static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00008987
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008988cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00008989 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008990
8991 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8992
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008993 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008994 OS << "[libclang:" << Name << ':';
8995
Alp Toker1a86ad22014-07-06 06:24:00 +00008996#ifdef USE_DARWIN_THREADS
8997 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008998 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8999 OS << tid << ':';
9000#endif
9001
9002 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
9003 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00009004 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009005
9006 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00009007 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009008 OS << "--------------------------------------------------\n";
9009 }
9010}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00009011
9012#ifdef CLANG_TOOL_EXTRA_BUILD
9013// This anchor is used to force the linker to link the clang-tidy plugin.
9014extern volatile int ClangTidyPluginAnchorSource;
9015static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9016 ClangTidyPluginAnchorSource;
9017
9018// This anchor is used to force the linker to link the clang-include-fixer
9019// plugin.
9020extern volatile int ClangIncludeFixerPluginAnchorSource;
9021static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9022 ClangIncludeFixerPluginAnchorSource;
9023#endif