blob: 48e8b61515812f9f6f84a1a7769e2ad4b3270e5b [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;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000632 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000633 if (!V.hasValue())
634 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000635 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000636 }
637 return false;
638}
639
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000640Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
641 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
642
643 // Ignore synthesized ivars here, otherwise if we have something like:
644 // @synthesize prop = _prop;
645 // and '_prop' is not declared, we will encounter a '_prop' ivar before
646 // encountering the 'prop' synthesize declaration and we will think that
647 // we passed the region-of-interest.
648 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
649 if (ivarD->getSynthesize())
650 return None;
651 }
652
653 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
654 // declarations is a mismatch with the compiler semantics.
655 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
656 auto *ID = cast<ObjCInterfaceDecl>(D);
657 if (!ID->isThisDeclarationADefinition())
658 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
659
660 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
661 auto *PD = cast<ObjCProtocolDecl>(D);
662 if (!PD->isThisDeclarationADefinition())
663 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
664 }
665
666 const Optional<bool> V = shouldVisitCursor(Cursor);
667 if (!V.hasValue())
668 return None;
669 if (!V.getValue())
670 return false;
671 if (Visit(Cursor, true))
672 return true;
673 return None;
674}
675
Guy Benyei11169dd2012-12-18 14:30:41 +0000676bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
677 llvm_unreachable("Translation units are visited directly by Visit()");
678}
679
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000680bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
681 if (VisitTemplateParameters(D->getTemplateParameters()))
682 return true;
683
684 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
685}
686
Guy Benyei11169dd2012-12-18 14:30:41 +0000687bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
688 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
689 return Visit(TSInfo->getTypeLoc());
690
691 return false;
692}
693
694bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
695 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
696 return Visit(TSInfo->getTypeLoc());
697
698 return false;
699}
700
701bool CursorVisitor::VisitTagDecl(TagDecl *D) {
702 return VisitDeclContext(D);
703}
704
705bool CursorVisitor::VisitClassTemplateSpecializationDecl(
706 ClassTemplateSpecializationDecl *D) {
707 bool ShouldVisitBody = false;
708 switch (D->getSpecializationKind()) {
709 case TSK_Undeclared:
710 case TSK_ImplicitInstantiation:
711 // Nothing to visit
712 return false;
713
714 case TSK_ExplicitInstantiationDeclaration:
715 case TSK_ExplicitInstantiationDefinition:
716 break;
717
718 case TSK_ExplicitSpecialization:
719 ShouldVisitBody = true;
720 break;
721 }
722
723 // Visit the template arguments used in the specialization.
724 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
725 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000726 if (TemplateSpecializationTypeLoc TSTLoc =
727 TL.getAs<TemplateSpecializationTypeLoc>()) {
728 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
729 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 return true;
731 }
732 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000733
734 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735}
736
737bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
738 ClassTemplatePartialSpecializationDecl *D) {
739 // FIXME: Visit the "outer" template parameter lists on the TagDecl
740 // before visiting these template parameters.
741 if (VisitTemplateParameters(D->getTemplateParameters()))
742 return true;
743
744 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000745 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
746 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
747 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000748 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
749 return true;
750
751 return VisitCXXRecordDecl(D);
752}
753
754bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
755 // Visit the default argument.
756 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
757 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
758 if (Visit(DefArg->getTypeLoc()))
759 return true;
760
761 return false;
762}
763
764bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
765 if (Expr *Init = D->getInitExpr())
766 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
767 return false;
768}
769
770bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000771 unsigned NumParamList = DD->getNumTemplateParameterLists();
772 for (unsigned i = 0; i < NumParamList; i++) {
773 TemplateParameterList* Params = DD->getTemplateParameterList(i);
774 if (VisitTemplateParameters(Params))
775 return true;
776 }
777
Guy Benyei11169dd2012-12-18 14:30:41 +0000778 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
779 if (Visit(TSInfo->getTypeLoc()))
780 return true;
781
782 // Visit the nested-name-specifier, if present.
783 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
784 if (VisitNestedNameSpecifierLoc(QualifierLoc))
785 return true;
786
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000787 return false;
788}
789
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000790static bool HasTrailingReturnType(FunctionDecl *ND) {
791 const QualType Ty = ND->getType();
792 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
793 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
794 return FT->hasTrailingReturn();
795 }
796
797 return false;
798}
799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000800/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000801static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
802 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000803 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
804}
805
Guy Benyei11169dd2012-12-18 14:30:41 +0000806bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000807 unsigned NumParamList = ND->getNumTemplateParameterLists();
808 for (unsigned i = 0; i < NumParamList; i++) {
809 TemplateParameterList* Params = ND->getTemplateParameterList(i);
810 if (VisitTemplateParameters(Params))
811 return true;
812 }
813
Guy Benyei11169dd2012-12-18 14:30:41 +0000814 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
815 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000816 // written. This requires a bit of work.
817 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
818 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000819 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000820
821 // If we have a function declared directly (without the use of a typedef),
822 // visit just the return type. Otherwise, just visit the function's type
823 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000824 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
825 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000826 (!FTL && Visit(TL)))
827 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000828
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000829 // Visit the nested-name-specifier, if present.
830 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
831 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000832 return true;
833
834 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000835 if (!isa<CXXDestructorDecl>(ND))
836 if (VisitDeclarationNameInfo(ND->getNameInfo()))
837 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000838
839 // FIXME: Visit explicitly-specified template arguments!
840
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000841 // Visit the function parameters, if we have a function type.
842 if (FTL && VisitFunctionTypeLoc(FTL, true))
843 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000844
845 // Visit the function's trailing return type.
846 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
847 return true;
848
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000849 // FIXME: Attributes?
850 }
851
Guy Benyei11169dd2012-12-18 14:30:41 +0000852 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
853 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
854 // Find the initializers that were written in the source.
855 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000856 for (auto *I : Constructor->inits()) {
857 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000858 continue;
859
Aaron Ballman0ad78302014-03-13 17:34:31 +0000860 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000861 }
862
863 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000864 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
865 &CompareCXXCtorInitializers);
866
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 // Visit the initializers in source order
868 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
869 CXXCtorInitializer *Init = WrittenInits[I];
870 if (Init->isAnyMemberInitializer()) {
871 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
872 Init->getMemberLocation(), TU)))
873 return true;
874 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
875 if (Visit(TInfo->getTypeLoc()))
876 return true;
877 }
878
879 // Visit the initializer value.
880 if (Expr *Initializer = Init->getInit())
881 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
882 return true;
883 }
884 }
885
886 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
887 return true;
888 }
889
890 return false;
891}
892
893bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
894 if (VisitDeclaratorDecl(D))
895 return true;
896
897 if (Expr *BitWidth = D->getBitWidth())
898 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
899
Benjamin Kramer99f97592017-11-15 12:20:41 +0000900 if (Expr *Init = D->getInClassInitializer())
901 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
902
Guy Benyei11169dd2012-12-18 14:30:41 +0000903 return false;
904}
905
906bool CursorVisitor::VisitVarDecl(VarDecl *D) {
907 if (VisitDeclaratorDecl(D))
908 return true;
909
910 if (Expr *Init = D->getInit())
911 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
912
913 return false;
914}
915
916bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
917 if (VisitDeclaratorDecl(D))
918 return true;
919
920 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
921 if (Expr *DefArg = D->getDefaultArgument())
922 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
923
924 return false;
925}
926
927bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
928 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
929 // before visiting these template parameters.
930 if (VisitTemplateParameters(D->getTemplateParameters()))
931 return true;
932
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000933 auto* FD = D->getTemplatedDecl();
934 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000935}
936
937bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
938 // FIXME: Visit the "outer" template parameter lists on the TagDecl
939 // before visiting these template parameters.
940 if (VisitTemplateParameters(D->getTemplateParameters()))
941 return true;
942
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000943 auto* CD = D->getTemplatedDecl();
944 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000945}
946
947bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
948 if (VisitTemplateParameters(D->getTemplateParameters()))
949 return true;
950
951 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
952 VisitTemplateArgumentLoc(D->getDefaultArgument()))
953 return true;
954
955 return false;
956}
957
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000958bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
959 // Visit the bound, if it's explicit.
960 if (D->hasExplicitBound()) {
961 if (auto TInfo = D->getTypeSourceInfo()) {
962 if (Visit(TInfo->getTypeLoc()))
963 return true;
964 }
965 }
966
967 return false;
968}
969
Guy Benyei11169dd2012-12-18 14:30:41 +0000970bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000971 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 if (Visit(TSInfo->getTypeLoc()))
973 return true;
974
David Majnemer59f77922016-06-24 04:05:48 +0000975 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000976 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 return true;
978 }
979
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000980 return ND->isThisDeclarationADefinition() &&
981 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000982}
983
984template <typename DeclIt>
985static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
986 SourceManager &SM, SourceLocation EndLoc,
987 SmallVectorImpl<Decl *> &Decls) {
988 DeclIt next = *DI_current;
989 while (++next != DE_current) {
990 Decl *D_next = *next;
991 if (!D_next)
992 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000993 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 if (!L.isValid())
995 break;
996 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
997 *DI_current = next;
998 Decls.push_back(D_next);
999 continue;
1000 }
1001 break;
1002 }
1003}
1004
Guy Benyei11169dd2012-12-18 14:30:41 +00001005bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1006 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1007 // an @implementation can lexically contain Decls that are not properly
1008 // nested in the AST. When we identify such cases, we need to retrofit
1009 // this nesting here.
1010 if (!DI_current && !FileDI_current)
1011 return VisitDeclContext(D);
1012
1013 // Scan the Decls that immediately come after the container
1014 // in the current DeclContext. If any fall within the
1015 // container's lexical region, stash them into a vector
1016 // for later processing.
1017 SmallVector<Decl *, 24> DeclsInContainer;
1018 SourceLocation EndLoc = D->getSourceRange().getEnd();
1019 SourceManager &SM = AU->getSourceManager();
1020 if (EndLoc.isValid()) {
1021 if (DI_current) {
1022 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1023 DeclsInContainer);
1024 } else {
1025 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1026 DeclsInContainer);
1027 }
1028 }
1029
1030 // The common case.
1031 if (DeclsInContainer.empty())
1032 return VisitDeclContext(D);
1033
1034 // Get all the Decls in the DeclContext, and sort them with the
1035 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001036 for (auto *SubDecl : D->decls()) {
1037 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001038 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001040 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 }
1042
1043 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001044 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001045 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001046 SourceLocation L_A = A->getBeginLoc();
1047 SourceLocation L_B = B->getBeginLoc();
1048 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001049 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1050 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001051 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001052
1053 // Now visit the decls.
1054 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1055 E = DeclsInContainer.end(); I != E; ++I) {
1056 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001057 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001058 if (!V.hasValue())
1059 continue;
1060 if (!V.getValue())
1061 return false;
1062 if (Visit(Cursor, true))
1063 return true;
1064 }
1065 return false;
1066}
1067
1068bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1069 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1070 TU)))
1071 return true;
1072
Douglas Gregore9d95f12015-07-07 03:57:35 +00001073 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1074 return true;
1075
Guy Benyei11169dd2012-12-18 14:30:41 +00001076 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1077 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1078 E = ND->protocol_end(); I != E; ++I, ++PL)
1079 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1080 return true;
1081
1082 return VisitObjCContainerDecl(ND);
1083}
1084
1085bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1086 if (!PID->isThisDeclarationADefinition())
1087 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1088
1089 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1090 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1091 E = PID->protocol_end(); I != E; ++I, ++PL)
1092 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1093 return true;
1094
1095 return VisitObjCContainerDecl(PID);
1096}
1097
1098bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1099 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1100 return true;
1101
1102 // FIXME: This implements a workaround with @property declarations also being
1103 // installed in the DeclContext for the @interface. Eventually this code
1104 // should be removed.
1105 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1106 if (!CDecl || !CDecl->IsClassExtension())
1107 return false;
1108
1109 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1110 if (!ID)
1111 return false;
1112
1113 IdentifierInfo *PropertyId = PD->getIdentifier();
1114 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001115 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1116 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001117
1118 if (!prevDecl)
1119 return false;
1120
1121 // Visit synthesized methods since they will be skipped when visiting
1122 // the @interface.
1123 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1124 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1125 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1126 return true;
1127
1128 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1129 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1130 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1131 return true;
1132
1133 return false;
1134}
1135
Douglas Gregore9d95f12015-07-07 03:57:35 +00001136bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1137 if (!typeParamList)
1138 return false;
1139
1140 for (auto *typeParam : *typeParamList) {
1141 // Visit the type parameter.
1142 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1143 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001144 }
1145
1146 return false;
1147}
1148
Guy Benyei11169dd2012-12-18 14:30:41 +00001149bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1150 if (!D->isThisDeclarationADefinition()) {
1151 // Forward declaration is treated like a reference.
1152 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1153 }
1154
Douglas Gregore9d95f12015-07-07 03:57:35 +00001155 // Objective-C type parameters.
1156 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1157 return true;
1158
Guy Benyei11169dd2012-12-18 14:30:41 +00001159 // Issue callbacks for super class.
1160 if (D->getSuperClass() &&
1161 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1162 D->getSuperClassLoc(),
1163 TU)))
1164 return true;
1165
Douglas Gregore9d95f12015-07-07 03:57:35 +00001166 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1167 if (Visit(SuperClassTInfo->getTypeLoc()))
1168 return true;
1169
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1171 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1172 E = D->protocol_end(); I != E; ++I, ++PL)
1173 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1174 return true;
1175
1176 return VisitObjCContainerDecl(D);
1177}
1178
1179bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1180 return VisitObjCContainerDecl(D);
1181}
1182
1183bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1184 // 'ID' could be null when dealing with invalid code.
1185 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1186 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1187 return true;
1188
1189 return VisitObjCImplDecl(D);
1190}
1191
1192bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1193#if 0
1194 // Issue callbacks for super class.
1195 // FIXME: No source location information!
1196 if (D->getSuperClass() &&
1197 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1198 D->getSuperClassLoc(),
1199 TU)))
1200 return true;
1201#endif
1202
1203 return VisitObjCImplDecl(D);
1204}
1205
1206bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1207 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1208 if (PD->isIvarNameSpecified())
1209 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1210
1211 return false;
1212}
1213
1214bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1215 return VisitDeclContext(D);
1216}
1217
1218bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1219 // Visit nested-name-specifier.
1220 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1221 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1222 return true;
1223
1224 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1225 D->getTargetNameLoc(), TU));
1226}
1227
1228bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1229 // Visit nested-name-specifier.
1230 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1231 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1232 return true;
1233 }
1234
1235 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1236 return true;
1237
1238 return VisitDeclarationNameInfo(D->getNameInfo());
1239}
1240
1241bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1242 // Visit nested-name-specifier.
1243 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1244 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1245 return true;
1246
1247 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1248 D->getIdentLocation(), TU));
1249}
1250
1251bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1252 // Visit nested-name-specifier.
1253 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1254 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1255 return true;
1256 }
1257
1258 return VisitDeclarationNameInfo(D->getNameInfo());
1259}
1260
1261bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1262 UnresolvedUsingTypenameDecl *D) {
1263 // Visit nested-name-specifier.
1264 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1265 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1266 return true;
1267
1268 return false;
1269}
1270
Olivier Goffart81978012016-06-09 16:15:55 +00001271bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1272 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1273 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001274 if (StringLiteral *Message = D->getMessage())
1275 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1276 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001277 return false;
1278}
1279
Olivier Goffartd211c642016-11-04 06:29:27 +00001280bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1281 if (NamedDecl *FriendD = D->getFriendDecl()) {
1282 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1283 return true;
1284 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1285 if (Visit(TI->getTypeLoc()))
1286 return true;
1287 }
1288 return false;
1289}
1290
Guy Benyei11169dd2012-12-18 14:30:41 +00001291bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1292 switch (Name.getName().getNameKind()) {
1293 case clang::DeclarationName::Identifier:
1294 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001295 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001296 case clang::DeclarationName::CXXOperatorName:
1297 case clang::DeclarationName::CXXUsingDirective:
1298 return false;
Richard Smith35845152017-02-07 01:37:30 +00001299
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 case clang::DeclarationName::CXXConstructorName:
1301 case clang::DeclarationName::CXXDestructorName:
1302 case clang::DeclarationName::CXXConversionFunctionName:
1303 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1304 return Visit(TSInfo->getTypeLoc());
1305 return false;
1306
1307 case clang::DeclarationName::ObjCZeroArgSelector:
1308 case clang::DeclarationName::ObjCOneArgSelector:
1309 case clang::DeclarationName::ObjCMultiArgSelector:
1310 // FIXME: Per-identifier location info?
1311 return false;
1312 }
1313
1314 llvm_unreachable("Invalid DeclarationName::Kind!");
1315}
1316
1317bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1318 SourceRange Range) {
1319 // FIXME: This whole routine is a hack to work around the lack of proper
1320 // source information in nested-name-specifiers (PR5791). Since we do have
1321 // a beginning source location, we can visit the first component of the
1322 // nested-name-specifier, if it's a single-token component.
1323 if (!NNS)
1324 return false;
1325
1326 // Get the first component in the nested-name-specifier.
1327 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1328 NNS = Prefix;
1329
1330 switch (NNS->getKind()) {
1331 case NestedNameSpecifier::Namespace:
1332 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1333 TU));
1334
1335 case NestedNameSpecifier::NamespaceAlias:
1336 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1337 Range.getBegin(), TU));
1338
1339 case NestedNameSpecifier::TypeSpec: {
1340 // If the type has a form where we know that the beginning of the source
1341 // range matches up with a reference cursor. Visit the appropriate reference
1342 // cursor.
1343 const Type *T = NNS->getAsType();
1344 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1345 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1346 if (const TagType *Tag = dyn_cast<TagType>(T))
1347 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1348 if (const TemplateSpecializationType *TST
1349 = dyn_cast<TemplateSpecializationType>(T))
1350 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1351 break;
1352 }
1353
1354 case NestedNameSpecifier::TypeSpecWithTemplate:
1355 case NestedNameSpecifier::Global:
1356 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001357 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 break;
1359 }
1360
1361 return false;
1362}
1363
1364bool
1365CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1366 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1367 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1368 Qualifiers.push_back(Qualifier);
1369
1370 while (!Qualifiers.empty()) {
1371 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1372 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1373 switch (NNS->getKind()) {
1374 case NestedNameSpecifier::Namespace:
1375 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1376 Q.getLocalBeginLoc(),
1377 TU)))
1378 return true;
1379
1380 break;
1381
1382 case NestedNameSpecifier::NamespaceAlias:
1383 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1384 Q.getLocalBeginLoc(),
1385 TU)))
1386 return true;
1387
1388 break;
1389
1390 case NestedNameSpecifier::TypeSpec:
1391 case NestedNameSpecifier::TypeSpecWithTemplate:
1392 if (Visit(Q.getTypeLoc()))
1393 return true;
1394
1395 break;
1396
1397 case NestedNameSpecifier::Global:
1398 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001399 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 break;
1401 }
1402 }
1403
1404 return false;
1405}
1406
1407bool CursorVisitor::VisitTemplateParameters(
1408 const TemplateParameterList *Params) {
1409 if (!Params)
1410 return false;
1411
1412 for (TemplateParameterList::const_iterator P = Params->begin(),
1413 PEnd = Params->end();
1414 P != PEnd; ++P) {
1415 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1416 return true;
1417 }
1418
1419 return false;
1420}
1421
1422bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1423 switch (Name.getKind()) {
1424 case TemplateName::Template:
1425 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1426
1427 case TemplateName::OverloadedTemplate:
1428 // Visit the overloaded template set.
1429 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1430 return true;
1431
1432 return false;
1433
Richard Smithb23c5e82019-05-09 03:31:27 +00001434 case TemplateName::AssumedTemplate:
1435 // FIXME: Visit DeclarationName?
1436 return false;
1437
Guy Benyei11169dd2012-12-18 14:30:41 +00001438 case TemplateName::DependentTemplate:
1439 // FIXME: Visit nested-name-specifier.
1440 return false;
1441
1442 case TemplateName::QualifiedTemplate:
1443 // FIXME: Visit nested-name-specifier.
1444 return Visit(MakeCursorTemplateRef(
1445 Name.getAsQualifiedTemplateName()->getDecl(),
1446 Loc, TU));
1447
1448 case TemplateName::SubstTemplateTemplateParm:
1449 return Visit(MakeCursorTemplateRef(
1450 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1451 Loc, TU));
1452
1453 case TemplateName::SubstTemplateTemplateParmPack:
1454 return Visit(MakeCursorTemplateRef(
1455 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1456 Loc, TU));
1457 }
1458
1459 llvm_unreachable("Invalid TemplateName::Kind!");
1460}
1461
1462bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1463 switch (TAL.getArgument().getKind()) {
1464 case TemplateArgument::Null:
1465 case TemplateArgument::Integral:
1466 case TemplateArgument::Pack:
1467 return false;
1468
1469 case TemplateArgument::Type:
1470 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1471 return Visit(TSInfo->getTypeLoc());
1472 return false;
1473
1474 case TemplateArgument::Declaration:
1475 if (Expr *E = TAL.getSourceDeclExpression())
1476 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1477 return false;
1478
1479 case TemplateArgument::NullPtr:
1480 if (Expr *E = TAL.getSourceNullPtrExpression())
1481 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1482 return false;
1483
1484 case TemplateArgument::Expression:
1485 if (Expr *E = TAL.getSourceExpression())
1486 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1487 return false;
1488
1489 case TemplateArgument::Template:
1490 case TemplateArgument::TemplateExpansion:
1491 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1492 return true;
1493
1494 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1495 TAL.getTemplateNameLoc());
1496 }
1497
1498 llvm_unreachable("Invalid TemplateArgument::Kind!");
1499}
1500
1501bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1502 return VisitDeclContext(D);
1503}
1504
1505bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1506 return Visit(TL.getUnqualifiedLoc());
1507}
1508
1509bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1510 ASTContext &Context = AU->getASTContext();
1511
1512 // Some builtin types (such as Objective-C's "id", "sel", and
1513 // "Class") have associated declarations. Create cursors for those.
1514 QualType VisitType;
1515 switch (TL.getTypePtr()->getKind()) {
1516
1517 case BuiltinType::Void:
1518 case BuiltinType::NullPtr:
1519 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001520#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1521 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001522#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001523#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1524 case BuiltinType::Id:
1525#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001526 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001527 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001528 case BuiltinType::OCLClkEvent:
1529 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001530 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001531#define SVE_TYPE(Name, Id, SingletonId) \
1532 case BuiltinType::Id:
1533#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00001534#define BUILTIN_TYPE(Id, SingletonId)
1535#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1536#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1537#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1538#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1539#include "clang/AST/BuiltinTypes.def"
1540 break;
1541
1542 case BuiltinType::ObjCId:
1543 VisitType = Context.getObjCIdType();
1544 break;
1545
1546 case BuiltinType::ObjCClass:
1547 VisitType = Context.getObjCClassType();
1548 break;
1549
1550 case BuiltinType::ObjCSel:
1551 VisitType = Context.getObjCSelType();
1552 break;
1553 }
1554
1555 if (!VisitType.isNull()) {
1556 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1557 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1558 TU));
1559 }
1560
1561 return false;
1562}
1563
1564bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1565 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1566}
1567
1568bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1569 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1570}
1571
1572bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1573 if (TL.isDefinition())
1574 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1575
1576 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1577}
1578
1579bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1580 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1581}
1582
1583bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001584 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001585}
1586
Manman Rene6be26c2016-09-13 17:25:08 +00001587bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001588 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001589 return true;
1590 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1591 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1592 TU)))
1593 return true;
1594 }
1595
1596 return false;
1597}
1598
Guy Benyei11169dd2012-12-18 14:30:41 +00001599bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1600 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1601 return true;
1602
Douglas Gregore9d95f12015-07-07 03:57:35 +00001603 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1604 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1605 return true;
1606 }
1607
Guy Benyei11169dd2012-12-18 14:30:41 +00001608 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1609 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1610 TU)))
1611 return true;
1612 }
1613
1614 return false;
1615}
1616
1617bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1618 return Visit(TL.getPointeeLoc());
1619}
1620
1621bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1622 return Visit(TL.getInnerLoc());
1623}
1624
Leonard Chanc72aaf62019-05-07 03:20:17 +00001625bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1626 return Visit(TL.getInnerLoc());
1627}
1628
Guy Benyei11169dd2012-12-18 14:30:41 +00001629bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1630 return Visit(TL.getPointeeLoc());
1631}
1632
1633bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1634 return Visit(TL.getPointeeLoc());
1635}
1636
1637bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1638 return Visit(TL.getPointeeLoc());
1639}
1640
1641bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1642 return Visit(TL.getPointeeLoc());
1643}
1644
1645bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1646 return Visit(TL.getPointeeLoc());
1647}
1648
1649bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1650 return Visit(TL.getModifiedLoc());
1651}
1652
1653bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1654 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001655 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 return true;
1657
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001658 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1659 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001660 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1661 return true;
1662
1663 return false;
1664}
1665
1666bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1667 if (Visit(TL.getElementLoc()))
1668 return true;
1669
1670 if (Expr *Size = TL.getSizeExpr())
1671 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1672
1673 return false;
1674}
1675
Reid Kleckner8a365022013-06-24 17:51:48 +00001676bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1677 return Visit(TL.getOriginalLoc());
1678}
1679
Reid Kleckner0503a872013-12-05 01:23:43 +00001680bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1681 return Visit(TL.getOriginalLoc());
1682}
1683
Richard Smith600b5262017-01-26 20:40:47 +00001684bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1685 DeducedTemplateSpecializationTypeLoc TL) {
1686 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1687 TL.getTemplateNameLoc()))
1688 return true;
1689
1690 return false;
1691}
1692
Guy Benyei11169dd2012-12-18 14:30:41 +00001693bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1694 TemplateSpecializationTypeLoc TL) {
1695 // Visit the template name.
1696 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1697 TL.getTemplateNameLoc()))
1698 return true;
1699
1700 // Visit the template arguments.
1701 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1702 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1703 return true;
1704
1705 return false;
1706}
1707
1708bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1709 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1710}
1711
1712bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1713 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1714 return Visit(TSInfo->getTypeLoc());
1715
1716 return false;
1717}
1718
1719bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1720 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1721 return Visit(TSInfo->getTypeLoc());
1722
1723 return false;
1724}
1725
1726bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001727 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001728}
1729
1730bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1731 DependentTemplateSpecializationTypeLoc TL) {
1732 // Visit the nested-name-specifier, if there is one.
1733 if (TL.getQualifierLoc() &&
1734 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1735 return true;
1736
1737 // Visit the template arguments.
1738 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1739 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1740 return true;
1741
1742 return false;
1743}
1744
1745bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1746 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1747 return true;
1748
1749 return Visit(TL.getNamedTypeLoc());
1750}
1751
1752bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1753 return Visit(TL.getPatternLoc());
1754}
1755
1756bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1757 if (Expr *E = TL.getUnderlyingExpr())
1758 return Visit(MakeCXCursor(E, StmtParent, TU));
1759
1760 return false;
1761}
1762
1763bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1764 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1765}
1766
1767bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1768 return Visit(TL.getValueLoc());
1769}
1770
Xiuli Pan9c14e282016-01-09 12:53:17 +00001771bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1772 return Visit(TL.getValueLoc());
1773}
1774
Guy Benyei11169dd2012-12-18 14:30:41 +00001775#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1776bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1777 return Visit##PARENT##Loc(TL); \
1778}
1779
1780DEFAULT_TYPELOC_IMPL(Complex, Type)
1781DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1782DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1783DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1784DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001785DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001786DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001787DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1788DEFAULT_TYPELOC_IMPL(Vector, Type)
1789DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1790DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1791DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1792DEFAULT_TYPELOC_IMPL(Record, TagType)
1793DEFAULT_TYPELOC_IMPL(Enum, TagType)
1794DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1795DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1796DEFAULT_TYPELOC_IMPL(Auto, Type)
1797
1798bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1799 // Visit the nested-name-specifier, if present.
1800 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1801 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1802 return true;
1803
1804 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001805 for (const auto &I : D->bases()) {
1806 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 return true;
1808 }
1809 }
1810
1811 return VisitTagDecl(D);
1812}
1813
1814bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001815 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001816 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1817 !I->isImplicit()) &&
1818 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001819 return true;
1820
1821 return false;
1822}
1823
1824//===----------------------------------------------------------------------===//
1825// Data-recursive visitor methods.
1826//===----------------------------------------------------------------------===//
1827
1828namespace {
1829#define DEF_JOB(NAME, DATA, KIND)\
1830class NAME : public VisitorJob {\
1831public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001832 NAME(const DATA *d, CXCursor parent) : \
1833 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001834 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001835 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001836};
1837
1838DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1839DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1840DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1841DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001842DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1843DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1844DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1845#undef DEF_JOB
1846
James Y Knight04ec5bf2015-12-24 02:59:37 +00001847class ExplicitTemplateArgsVisit : public VisitorJob {
1848public:
1849 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1850 const TemplateArgumentLoc *End, CXCursor parent)
1851 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1852 End) {}
1853 static bool classof(const VisitorJob *VJ) {
1854 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1855 }
1856 const TemplateArgumentLoc *begin() const {
1857 return static_cast<const TemplateArgumentLoc *>(data[0]);
1858 }
1859 const TemplateArgumentLoc *end() {
1860 return static_cast<const TemplateArgumentLoc *>(data[1]);
1861 }
1862};
Guy Benyei11169dd2012-12-18 14:30:41 +00001863class DeclVisit : public VisitorJob {
1864public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001865 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001866 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001867 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001868 static bool classof(const VisitorJob *VJ) {
1869 return VJ->getKind() == DeclVisitKind;
1870 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001871 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001872 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001873};
1874class TypeLocVisit : public VisitorJob {
1875public:
1876 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1877 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1878 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1879
1880 static bool classof(const VisitorJob *VJ) {
1881 return VJ->getKind() == TypeLocVisitKind;
1882 }
1883
1884 TypeLoc get() const {
1885 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001886 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 }
1888};
1889
1890class LabelRefVisit : public VisitorJob {
1891public:
1892 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1893 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1894 labelLoc.getPtrEncoding()) {}
1895
1896 static bool classof(const VisitorJob *VJ) {
1897 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1898 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001899 const LabelDecl *get() const {
1900 return static_cast<const LabelDecl *>(data[0]);
1901 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 SourceLocation getLoc() const {
1903 return SourceLocation::getFromPtrEncoding(data[1]); }
1904};
1905
1906class NestedNameSpecifierLocVisit : public VisitorJob {
1907public:
1908 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1909 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1910 Qualifier.getNestedNameSpecifier(),
1911 Qualifier.getOpaqueData()) { }
1912
1913 static bool classof(const VisitorJob *VJ) {
1914 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1915 }
1916
1917 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001918 return NestedNameSpecifierLoc(
1919 const_cast<NestedNameSpecifier *>(
1920 static_cast<const NestedNameSpecifier *>(data[0])),
1921 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001922 }
1923};
1924
1925class DeclarationNameInfoVisit : public VisitorJob {
1926public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001927 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001928 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001929 static bool classof(const VisitorJob *VJ) {
1930 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1931 }
1932 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001933 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 switch (S->getStmtClass()) {
1935 default:
1936 llvm_unreachable("Unhandled Stmt");
1937 case clang::Stmt::MSDependentExistsStmtClass:
1938 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1939 case Stmt::CXXDependentScopeMemberExprClass:
1940 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1941 case Stmt::DependentScopeDeclRefExprClass:
1942 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001943 case Stmt::OMPCriticalDirectiveClass:
1944 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001945 }
1946 }
1947};
1948class MemberRefVisit : public VisitorJob {
1949public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001950 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1952 L.getPtrEncoding()) {}
1953 static bool classof(const VisitorJob *VJ) {
1954 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1955 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001956 const FieldDecl *get() const {
1957 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001958 }
1959 SourceLocation getLoc() const {
1960 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1961 }
1962};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001963class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001964 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001965 VisitorWorkList &WL;
1966 CXCursor Parent;
1967public:
1968 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1969 : WL(wl), Parent(parent) {}
1970
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001971 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1972 void VisitBlockExpr(const BlockExpr *B);
1973 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1974 void VisitCompoundStmt(const CompoundStmt *S);
1975 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1976 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1977 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1978 void VisitCXXNewExpr(const CXXNewExpr *E);
1979 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1980 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1981 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1982 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1983 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1984 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1985 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1986 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001987 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001988 void VisitDeclRefExpr(const DeclRefExpr *D);
1989 void VisitDeclStmt(const DeclStmt *S);
1990 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1991 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1992 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1993 void VisitForStmt(const ForStmt *FS);
1994 void VisitGotoStmt(const GotoStmt *GS);
1995 void VisitIfStmt(const IfStmt *If);
1996 void VisitInitListExpr(const InitListExpr *IE);
1997 void VisitMemberExpr(const MemberExpr *M);
1998 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1999 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2000 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
2001 void VisitOverloadExpr(const OverloadExpr *E);
2002 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2003 void VisitStmt(const Stmt *S);
2004 void VisitSwitchStmt(const SwitchStmt *S);
2005 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002006 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2007 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2008 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2009 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2010 void VisitVAArgExpr(const VAArgExpr *E);
2011 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2012 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2013 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2014 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002015 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002016 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002017 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002018 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002019 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002020 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002021 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002022 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002023 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002024 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002025 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002026 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002027 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002028 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002029 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002030 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002031 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002032 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002033 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002034 void
2035 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002036 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002037 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002038 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002039 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002040 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002041 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002042 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002043 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002044 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002045 void
2046 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002047 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002048 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002049 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Alexey Bataev60e51c42019-10-10 20:13:02 +00002050 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002051 void
2052 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002053 void VisitOMPParallelMasterTaskLoopDirective(
2054 const OMPParallelMasterTaskLoopDirective *D);
Alexey Bataev14a388f2019-10-25 10:27:13 -04002055 void VisitOMPParallelMasterTaskLoopSimdDirective(
2056 const OMPParallelMasterTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002057 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002058 void VisitOMPDistributeParallelForDirective(
2059 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002060 void VisitOMPDistributeParallelForSimdDirective(
2061 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002062 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002063 void VisitOMPTargetParallelForSimdDirective(
2064 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002065 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002066 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002067 void VisitOMPTeamsDistributeSimdDirective(
2068 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002069 void VisitOMPTeamsDistributeParallelForSimdDirective(
2070 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002071 void VisitOMPTeamsDistributeParallelForDirective(
2072 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002073 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002074 void VisitOMPTargetTeamsDistributeDirective(
2075 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002076 void VisitOMPTargetTeamsDistributeParallelForDirective(
2077 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002078 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2079 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002080 void VisitOMPTargetTeamsDistributeSimdDirective(
2081 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002082
Guy Benyei11169dd2012-12-18 14:30:41 +00002083private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002084 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002085 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002086 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2087 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002088 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2089 void AddStmt(const Stmt *S);
2090 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002091 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002092 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002093 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002094};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002095} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002096
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002097void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 // 'S' should always be non-null, since it comes from the
2099 // statement we are visiting.
2100 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2101}
2102
2103void
2104EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2105 if (Qualifier)
2106 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2107}
2108
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002109void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002110 if (S)
2111 WL.push_back(StmtVisit(S, Parent));
2112}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002113void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 if (D)
2115 WL.push_back(DeclVisit(D, Parent, isFirst));
2116}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002117void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2118 unsigned NumTemplateArgs) {
2119 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002120}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002121void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002122 if (D)
2123 WL.push_back(MemberRefVisit(D, L, Parent));
2124}
2125void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2126 if (TI)
2127 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2128 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002129void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002130 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002131 for (const Stmt *SubStmt : S->children()) {
2132 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002133 }
2134 if (size == WL.size())
2135 return;
2136 // Now reverse the entries we just added. This will match the DFS
2137 // ordering performed by the worklist.
2138 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2139 std::reverse(I, E);
2140}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002141namespace {
2142class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2143 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002144 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002145 template <typename T>
2146 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002147public:
2148 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2149#define OPENMP_CLAUSE(Name, Class) \
2150 void Visit##Class(const Class *C);
2151#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002152 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002153 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002154};
2155
Alexey Bataev3392d762016-02-16 11:18:12 +00002156void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2157 const OMPClauseWithPreInit *C) {
2158 Visitor->AddStmt(C->getPreInitStmt());
2159}
2160
Alexey Bataev005248a2016-02-25 05:25:57 +00002161void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2162 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002163 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002164 Visitor->AddStmt(C->getPostUpdateExpr());
2165}
2166
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002167void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002168 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002169 Visitor->AddStmt(C->getCondition());
2170}
2171
Alexey Bataev3778b602014-07-17 07:32:53 +00002172void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2173 Visitor->AddStmt(C->getCondition());
2174}
2175
Alexey Bataev568a8332014-03-06 06:15:19 +00002176void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002177 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002178 Visitor->AddStmt(C->getNumThreads());
2179}
2180
Alexey Bataev62c87d22014-03-21 04:51:18 +00002181void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2182 Visitor->AddStmt(C->getSafelen());
2183}
2184
Alexey Bataev66b15b52015-08-21 11:14:16 +00002185void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2186 Visitor->AddStmt(C->getSimdlen());
2187}
2188
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002189void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2190 Visitor->AddStmt(C->getAllocator());
2191}
2192
Alexander Musman8bd31e62014-05-27 15:12:19 +00002193void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2194 Visitor->AddStmt(C->getNumForLoops());
2195}
2196
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002197void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002198
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002199void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2200
Alexey Bataev56dafe82014-06-20 07:16:17 +00002201void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002202 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002203 Visitor->AddStmt(C->getChunkSize());
2204}
2205
Alexey Bataev10e775f2015-07-30 11:36:16 +00002206void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2207 Visitor->AddStmt(C->getNumForLoops());
2208}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002209
Alexey Bataev236070f2014-06-20 11:19:47 +00002210void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2211
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002212void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2213
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002214void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2215
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002216void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2217
Alexey Bataevdea47612014-07-23 07:46:59 +00002218void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2219
Alexey Bataev67a4f222014-07-23 10:25:33 +00002220void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2221
Alexey Bataev459dec02014-07-24 06:46:57 +00002222void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2223
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002224void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2225
Alexey Bataev346265e2015-09-25 10:37:12 +00002226void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2227
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002228void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2229
Alexey Bataevb825de12015-12-07 10:51:44 +00002230void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2231
Kelvin Li1408f912018-09-26 04:28:39 +00002232void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2233 const OMPUnifiedAddressClause *) {}
2234
Patrick Lyster4a370b92018-10-01 13:47:43 +00002235void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2236 const OMPUnifiedSharedMemoryClause *) {}
2237
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002238void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2239 const OMPReverseOffloadClause *) {}
2240
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002241void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2242 const OMPDynamicAllocatorsClause *) {}
2243
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002244void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2245 const OMPAtomicDefaultMemOrderClause *) {}
2246
Michael Wonge710d542015-08-07 16:16:36 +00002247void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2248 Visitor->AddStmt(C->getDevice());
2249}
2250
Kelvin Li099bb8c2015-11-24 20:50:12 +00002251void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002252 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002253 Visitor->AddStmt(C->getNumTeams());
2254}
2255
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002256void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002257 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002258 Visitor->AddStmt(C->getThreadLimit());
2259}
2260
Alexey Bataeva0569352015-12-01 10:17:31 +00002261void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2262 Visitor->AddStmt(C->getPriority());
2263}
2264
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002265void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2266 Visitor->AddStmt(C->getGrainsize());
2267}
2268
Alexey Bataev382967a2015-12-08 12:06:20 +00002269void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2270 Visitor->AddStmt(C->getNumTasks());
2271}
2272
Alexey Bataev28c75412015-12-15 08:19:24 +00002273void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2274 Visitor->AddStmt(C->getHint());
2275}
2276
Alexey Bataev756c1962013-09-24 03:17:45 +00002277template<typename T>
2278void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002279 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002280 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002281 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002282}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002283
Alexey Bataeve04483e2019-03-27 14:14:31 +00002284void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2285 VisitOMPClauseList(C);
2286 Visitor->AddStmt(C->getAllocator());
2287}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002288void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002289 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002290 for (const auto *E : C->private_copies()) {
2291 Visitor->AddStmt(E);
2292 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002293}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002294void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2295 const OMPFirstprivateClause *C) {
2296 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002297 VisitOMPClauseWithPreInit(C);
2298 for (const auto *E : C->private_copies()) {
2299 Visitor->AddStmt(E);
2300 }
2301 for (const auto *E : C->inits()) {
2302 Visitor->AddStmt(E);
2303 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002304}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002305void OMPClauseEnqueue::VisitOMPLastprivateClause(
2306 const OMPLastprivateClause *C) {
2307 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002308 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002309 for (auto *E : C->private_copies()) {
2310 Visitor->AddStmt(E);
2311 }
2312 for (auto *E : C->source_exprs()) {
2313 Visitor->AddStmt(E);
2314 }
2315 for (auto *E : C->destination_exprs()) {
2316 Visitor->AddStmt(E);
2317 }
2318 for (auto *E : C->assignment_ops()) {
2319 Visitor->AddStmt(E);
2320 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002321}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002322void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002323 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002324}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002325void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2326 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002327 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002328 for (auto *E : C->privates()) {
2329 Visitor->AddStmt(E);
2330 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002331 for (auto *E : C->lhs_exprs()) {
2332 Visitor->AddStmt(E);
2333 }
2334 for (auto *E : C->rhs_exprs()) {
2335 Visitor->AddStmt(E);
2336 }
2337 for (auto *E : C->reduction_ops()) {
2338 Visitor->AddStmt(E);
2339 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002340}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002341void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2342 const OMPTaskReductionClause *C) {
2343 VisitOMPClauseList(C);
2344 VisitOMPClauseWithPostUpdate(C);
2345 for (auto *E : C->privates()) {
2346 Visitor->AddStmt(E);
2347 }
2348 for (auto *E : C->lhs_exprs()) {
2349 Visitor->AddStmt(E);
2350 }
2351 for (auto *E : C->rhs_exprs()) {
2352 Visitor->AddStmt(E);
2353 }
2354 for (auto *E : C->reduction_ops()) {
2355 Visitor->AddStmt(E);
2356 }
2357}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002358void OMPClauseEnqueue::VisitOMPInReductionClause(
2359 const OMPInReductionClause *C) {
2360 VisitOMPClauseList(C);
2361 VisitOMPClauseWithPostUpdate(C);
2362 for (auto *E : C->privates()) {
2363 Visitor->AddStmt(E);
2364 }
2365 for (auto *E : C->lhs_exprs()) {
2366 Visitor->AddStmt(E);
2367 }
2368 for (auto *E : C->rhs_exprs()) {
2369 Visitor->AddStmt(E);
2370 }
2371 for (auto *E : C->reduction_ops()) {
2372 Visitor->AddStmt(E);
2373 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002374 for (auto *E : C->taskgroup_descriptors())
2375 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002376}
Alexander Musman8dba6642014-04-22 13:09:42 +00002377void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2378 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002379 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002380 for (const auto *E : C->privates()) {
2381 Visitor->AddStmt(E);
2382 }
Alexander Musman3276a272015-03-21 10:12:56 +00002383 for (const auto *E : C->inits()) {
2384 Visitor->AddStmt(E);
2385 }
2386 for (const auto *E : C->updates()) {
2387 Visitor->AddStmt(E);
2388 }
2389 for (const auto *E : C->finals()) {
2390 Visitor->AddStmt(E);
2391 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002392 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002393 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002394}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002395void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2396 VisitOMPClauseList(C);
2397 Visitor->AddStmt(C->getAlignment());
2398}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002399void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2400 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002401 for (auto *E : C->source_exprs()) {
2402 Visitor->AddStmt(E);
2403 }
2404 for (auto *E : C->destination_exprs()) {
2405 Visitor->AddStmt(E);
2406 }
2407 for (auto *E : C->assignment_ops()) {
2408 Visitor->AddStmt(E);
2409 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002410}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002411void
2412OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2413 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002414 for (auto *E : C->source_exprs()) {
2415 Visitor->AddStmt(E);
2416 }
2417 for (auto *E : C->destination_exprs()) {
2418 Visitor->AddStmt(E);
2419 }
2420 for (auto *E : C->assignment_ops()) {
2421 Visitor->AddStmt(E);
2422 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002423}
Alexey Bataev6125da92014-07-21 11:26:11 +00002424void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2425 VisitOMPClauseList(C);
2426}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002427void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2428 VisitOMPClauseList(C);
2429}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002430void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2431 VisitOMPClauseList(C);
2432}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002433void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2434 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002435 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002436 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002437}
Alexey Bataev3392d762016-02-16 11:18:12 +00002438void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2439 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002440void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2441 VisitOMPClauseList(C);
2442}
Samuel Antaoec172c62016-05-26 17:49:04 +00002443void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2444 VisitOMPClauseList(C);
2445}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002446void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2447 VisitOMPClauseList(C);
2448}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002449void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2450 VisitOMPClauseList(C);
2451}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002452}
Alexey Bataev756c1962013-09-24 03:17:45 +00002453
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002454void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2455 unsigned size = WL.size();
2456 OMPClauseEnqueue Visitor(this);
2457 Visitor.Visit(S);
2458 if (size == WL.size())
2459 return;
2460 // Now reverse the entries we just added. This will match the DFS
2461 // ordering performed by the worklist.
2462 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2463 std::reverse(I, E);
2464}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002465void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2467}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002468void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 AddDecl(B->getBlockDecl());
2470}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002471void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 EnqueueChildren(E);
2473 AddTypeLoc(E->getTypeSourceInfo());
2474}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002475void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002476 for (auto &I : llvm::reverse(S->body()))
2477 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002478}
2479void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002480VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 AddStmt(S->getSubStmt());
2482 AddDeclarationNameInfo(S);
2483 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2484 AddNestedNameSpecifierLoc(QualifierLoc);
2485}
2486
2487void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002488VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002489 if (E->hasExplicitTemplateArgs())
2490 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 AddDeclarationNameInfo(E);
2492 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2493 AddNestedNameSpecifierLoc(QualifierLoc);
2494 if (!E->isImplicitAccess())
2495 AddStmt(E->getBase());
2496}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002497void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 // Enqueue the initializer , if any.
2499 AddStmt(E->getInitializer());
2500 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002501 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 // Enqueue the allocated type.
2503 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2504 // Enqueue the placement arguments.
2505 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2506 AddStmt(E->getPlacementArg(I-1));
2507}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002508void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2510 AddStmt(CE->getArg(I-1));
2511 AddStmt(CE->getCallee());
2512 AddStmt(CE->getArg(0));
2513}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002514void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2515 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 // Visit the name of the type being destroyed.
2517 AddTypeLoc(E->getDestroyedTypeInfo());
2518 // Visit the scope type that looks disturbingly like the nested-name-specifier
2519 // but isn't.
2520 AddTypeLoc(E->getScopeTypeInfo());
2521 // Visit the nested-name-specifier.
2522 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2523 AddNestedNameSpecifierLoc(QualifierLoc);
2524 // Visit base expression.
2525 AddStmt(E->getBase());
2526}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002527void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2528 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 AddTypeLoc(E->getTypeSourceInfo());
2530}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002531void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2532 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 EnqueueChildren(E);
2534 AddTypeLoc(E->getTypeSourceInfo());
2535}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002536void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 EnqueueChildren(E);
2538 if (E->isTypeOperand())
2539 AddTypeLoc(E->getTypeOperandSourceInfo());
2540}
2541
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002542void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2543 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 EnqueueChildren(E);
2545 AddTypeLoc(E->getTypeSourceInfo());
2546}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002547void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 EnqueueChildren(E);
2549 if (E->isTypeOperand())
2550 AddTypeLoc(E->getTypeOperandSourceInfo());
2551}
2552
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002553void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 EnqueueChildren(S);
2555 AddDecl(S->getExceptionDecl());
2556}
2557
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002558void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002559 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002560 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002561 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002562}
2563
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002564void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002565 if (DR->hasExplicitTemplateArgs())
2566 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 WL.push_back(DeclRefExprParts(DR, Parent));
2568}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002569void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2570 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002571 if (E->hasExplicitTemplateArgs())
2572 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 AddDeclarationNameInfo(E);
2574 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2575}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002576void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 unsigned size = WL.size();
2578 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002579 for (const auto *D : S->decls()) {
2580 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 isFirst = false;
2582 }
2583 if (size == WL.size())
2584 return;
2585 // Now reverse the entries we just added. This will match the DFS
2586 // ordering performed by the worklist.
2587 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2588 std::reverse(I, E);
2589}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002590void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002592 for (const DesignatedInitExpr::Designator &D :
2593 llvm::reverse(E->designators())) {
2594 if (D.isFieldDesignator()) {
2595 if (FieldDecl *Field = D.getField())
2596 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 continue;
2598 }
David Majnemerf7e36092016-06-23 00:15:04 +00002599 if (D.isArrayDesignator()) {
2600 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 continue;
2602 }
David Majnemerf7e36092016-06-23 00:15:04 +00002603 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2604 AddStmt(E->getArrayRangeEnd(D));
2605 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 }
2607}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002608void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 EnqueueChildren(E);
2610 AddTypeLoc(E->getTypeInfoAsWritten());
2611}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002612void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 AddStmt(FS->getBody());
2614 AddStmt(FS->getInc());
2615 AddStmt(FS->getCond());
2616 AddDecl(FS->getConditionVariable());
2617 AddStmt(FS->getInit());
2618}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002619void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2621}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002622void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 AddStmt(If->getElse());
2624 AddStmt(If->getThen());
2625 AddStmt(If->getCond());
2626 AddDecl(If->getConditionVariable());
2627}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002628void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 // We care about the syntactic form of the initializer list, only.
2630 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2631 IE = Syntactic;
2632 EnqueueChildren(IE);
2633}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002634void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 WL.push_back(MemberExprParts(M, Parent));
2636
2637 // If the base of the member access expression is an implicit 'this', don't
2638 // visit it.
2639 // FIXME: If we ever want to show these implicit accesses, this will be
2640 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002641 if (M->isImplicitAccess())
2642 return;
2643
2644 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002645 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002646 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2647 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2648 if (FD->isAnonymousStructOrUnion()) {
2649 AddStmt(SubME->getBase());
2650 return;
2651 }
2652 }
2653 }
2654
2655 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002656}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002657void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 AddTypeLoc(E->getEncodedTypeSourceInfo());
2659}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002660void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 EnqueueChildren(M);
2662 AddTypeLoc(M->getClassReceiverTypeInfo());
2663}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002664void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 // Visit the components of the offsetof expression.
2666 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 const OffsetOfNode &Node = E->getComponent(I-1);
2668 switch (Node.getKind()) {
2669 case OffsetOfNode::Array:
2670 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2671 break;
2672 case OffsetOfNode::Field:
2673 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2674 break;
2675 case OffsetOfNode::Identifier:
2676 case OffsetOfNode::Base:
2677 continue;
2678 }
2679 }
2680 // Visit the type into which we're computing the offset.
2681 AddTypeLoc(E->getTypeSourceInfo());
2682}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002683void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002684 if (E->hasExplicitTemplateArgs())
2685 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 WL.push_back(OverloadExprParts(E, Parent));
2687}
2688void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002689 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 EnqueueChildren(E);
2691 if (E->isArgumentType())
2692 AddTypeLoc(E->getArgumentTypeInfo());
2693}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002694void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 EnqueueChildren(S);
2696}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002697void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 AddStmt(S->getBody());
2699 AddStmt(S->getCond());
2700 AddDecl(S->getConditionVariable());
2701}
2702
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002703void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 AddStmt(W->getBody());
2705 AddStmt(W->getCond());
2706 AddDecl(W->getConditionVariable());
2707}
2708
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002709void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 for (unsigned I = E->getNumArgs(); I > 0; --I)
2711 AddTypeLoc(E->getArg(I-1));
2712}
2713
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002714void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 AddTypeLoc(E->getQueriedTypeSourceInfo());
2716}
2717
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002718void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 EnqueueChildren(E);
2720}
2721
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002722void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 VisitOverloadExpr(U);
2724 if (!U->isImplicitAccess())
2725 AddStmt(U->getBase());
2726}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002727void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 AddStmt(E->getSubExpr());
2729 AddTypeLoc(E->getWrittenTypeInfo());
2730}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002731void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 WL.push_back(SizeOfPackExprParts(E, Parent));
2733}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002734void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 // If the opaque value has a source expression, just transparently
2736 // visit that. This is useful for (e.g.) pseudo-object expressions.
2737 if (Expr *SourceExpr = E->getSourceExpr())
2738 return Visit(SourceExpr);
2739}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002740void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 AddStmt(E->getBody());
2742 WL.push_back(LambdaExprParts(E, Parent));
2743}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002744void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 // Treat the expression like its syntactic form.
2746 Visit(E->getSyntacticForm());
2747}
2748
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002749void EnqueueVisitor::VisitOMPExecutableDirective(
2750 const OMPExecutableDirective *D) {
2751 EnqueueChildren(D);
2752 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2753 E = D->clauses().end();
2754 I != E; ++I)
2755 EnqueueChildren(*I);
2756}
2757
Alexander Musman3aaab662014-08-19 11:27:13 +00002758void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2759 VisitOMPExecutableDirective(D);
2760}
2761
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002762void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2763 VisitOMPExecutableDirective(D);
2764}
2765
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002766void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002767 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002768}
2769
Alexey Bataevf29276e2014-06-18 04:14:57 +00002770void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002771 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002772}
2773
Alexander Musmanf82886e2014-09-18 05:12:34 +00002774void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2775 VisitOMPLoopDirective(D);
2776}
2777
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002778void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2779 VisitOMPExecutableDirective(D);
2780}
2781
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002782void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2783 VisitOMPExecutableDirective(D);
2784}
2785
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002786void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2787 VisitOMPExecutableDirective(D);
2788}
2789
Alexander Musman80c22892014-07-17 08:54:58 +00002790void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2791 VisitOMPExecutableDirective(D);
2792}
2793
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002794void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2795 VisitOMPExecutableDirective(D);
2796 AddDeclarationNameInfo(D);
2797}
2798
Alexey Bataev4acb8592014-07-07 13:01:15 +00002799void
2800EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002801 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002802}
2803
Alexander Musmane4e893b2014-09-23 09:33:00 +00002804void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2805 const OMPParallelForSimdDirective *D) {
2806 VisitOMPLoopDirective(D);
2807}
2808
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002809void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2810 const OMPParallelSectionsDirective *D) {
2811 VisitOMPExecutableDirective(D);
2812}
2813
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002814void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2815 VisitOMPExecutableDirective(D);
2816}
2817
Alexey Bataev68446b72014-07-18 07:47:19 +00002818void
2819EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2820 VisitOMPExecutableDirective(D);
2821}
2822
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002823void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2824 VisitOMPExecutableDirective(D);
2825}
2826
Alexey Bataev2df347a2014-07-18 10:17:07 +00002827void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2828 VisitOMPExecutableDirective(D);
2829}
2830
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002831void EnqueueVisitor::VisitOMPTaskgroupDirective(
2832 const OMPTaskgroupDirective *D) {
2833 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002834 if (const Expr *E = D->getReductionRef())
2835 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002836}
2837
Alexey Bataev6125da92014-07-21 11:26:11 +00002838void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2839 VisitOMPExecutableDirective(D);
2840}
2841
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002842void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2843 VisitOMPExecutableDirective(D);
2844}
2845
Alexey Bataev0162e452014-07-22 10:10:35 +00002846void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2847 VisitOMPExecutableDirective(D);
2848}
2849
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002850void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2851 VisitOMPExecutableDirective(D);
2852}
2853
Michael Wong65f367f2015-07-21 13:44:28 +00002854void EnqueueVisitor::VisitOMPTargetDataDirective(const
2855 OMPTargetDataDirective *D) {
2856 VisitOMPExecutableDirective(D);
2857}
2858
Samuel Antaodf67fc42016-01-19 19:15:56 +00002859void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2860 const OMPTargetEnterDataDirective *D) {
2861 VisitOMPExecutableDirective(D);
2862}
2863
Samuel Antao72590762016-01-19 20:04:50 +00002864void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2865 const OMPTargetExitDataDirective *D) {
2866 VisitOMPExecutableDirective(D);
2867}
2868
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002869void EnqueueVisitor::VisitOMPTargetParallelDirective(
2870 const OMPTargetParallelDirective *D) {
2871 VisitOMPExecutableDirective(D);
2872}
2873
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002874void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2875 const OMPTargetParallelForDirective *D) {
2876 VisitOMPLoopDirective(D);
2877}
2878
Alexey Bataev13314bf2014-10-09 04:18:56 +00002879void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2880 VisitOMPExecutableDirective(D);
2881}
2882
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002883void EnqueueVisitor::VisitOMPCancellationPointDirective(
2884 const OMPCancellationPointDirective *D) {
2885 VisitOMPExecutableDirective(D);
2886}
2887
Alexey Bataev80909872015-07-02 11:25:17 +00002888void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2889 VisitOMPExecutableDirective(D);
2890}
2891
Alexey Bataev49f6e782015-12-01 04:18:41 +00002892void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2893 VisitOMPLoopDirective(D);
2894}
2895
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002896void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2897 const OMPTaskLoopSimdDirective *D) {
2898 VisitOMPLoopDirective(D);
2899}
2900
Alexey Bataev60e51c42019-10-10 20:13:02 +00002901void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2902 const OMPMasterTaskLoopDirective *D) {
2903 VisitOMPLoopDirective(D);
2904}
2905
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002906void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2907 const OMPMasterTaskLoopSimdDirective *D) {
2908 VisitOMPLoopDirective(D);
2909}
2910
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002911void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2912 const OMPParallelMasterTaskLoopDirective *D) {
2913 VisitOMPLoopDirective(D);
2914}
2915
Alexey Bataev14a388f2019-10-25 10:27:13 -04002916void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
2917 const OMPParallelMasterTaskLoopSimdDirective *D) {
2918 VisitOMPLoopDirective(D);
2919}
2920
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002921void EnqueueVisitor::VisitOMPDistributeDirective(
2922 const OMPDistributeDirective *D) {
2923 VisitOMPLoopDirective(D);
2924}
2925
Carlo Bertolli9925f152016-06-27 14:55:37 +00002926void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2927 const OMPDistributeParallelForDirective *D) {
2928 VisitOMPLoopDirective(D);
2929}
2930
Kelvin Li4a39add2016-07-05 05:00:15 +00002931void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2932 const OMPDistributeParallelForSimdDirective *D) {
2933 VisitOMPLoopDirective(D);
2934}
2935
Kelvin Li787f3fc2016-07-06 04:45:38 +00002936void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2937 const OMPDistributeSimdDirective *D) {
2938 VisitOMPLoopDirective(D);
2939}
2940
Kelvin Lia579b912016-07-14 02:54:56 +00002941void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2942 const OMPTargetParallelForSimdDirective *D) {
2943 VisitOMPLoopDirective(D);
2944}
2945
Kelvin Li986330c2016-07-20 22:57:10 +00002946void EnqueueVisitor::VisitOMPTargetSimdDirective(
2947 const OMPTargetSimdDirective *D) {
2948 VisitOMPLoopDirective(D);
2949}
2950
Kelvin Li02532872016-08-05 14:37:37 +00002951void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2952 const OMPTeamsDistributeDirective *D) {
2953 VisitOMPLoopDirective(D);
2954}
2955
Kelvin Li4e325f72016-10-25 12:50:55 +00002956void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2957 const OMPTeamsDistributeSimdDirective *D) {
2958 VisitOMPLoopDirective(D);
2959}
2960
Kelvin Li579e41c2016-11-30 23:51:03 +00002961void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2962 const OMPTeamsDistributeParallelForSimdDirective *D) {
2963 VisitOMPLoopDirective(D);
2964}
2965
Kelvin Li7ade93f2016-12-09 03:24:30 +00002966void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2967 const OMPTeamsDistributeParallelForDirective *D) {
2968 VisitOMPLoopDirective(D);
2969}
2970
Kelvin Libf594a52016-12-17 05:48:59 +00002971void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2972 const OMPTargetTeamsDirective *D) {
2973 VisitOMPExecutableDirective(D);
2974}
2975
Kelvin Li83c451e2016-12-25 04:52:54 +00002976void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2977 const OMPTargetTeamsDistributeDirective *D) {
2978 VisitOMPLoopDirective(D);
2979}
2980
Kelvin Li80e8f562016-12-29 22:16:30 +00002981void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2982 const OMPTargetTeamsDistributeParallelForDirective *D) {
2983 VisitOMPLoopDirective(D);
2984}
2985
Kelvin Li1851df52017-01-03 05:23:48 +00002986void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2987 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2988 VisitOMPLoopDirective(D);
2989}
2990
Kelvin Lida681182017-01-10 18:08:18 +00002991void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2992 const OMPTargetTeamsDistributeSimdDirective *D) {
2993 VisitOMPLoopDirective(D);
2994}
2995
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002996void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002997 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2998}
2999
3000bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3001 if (RegionOfInterest.isValid()) {
3002 SourceRange Range = getRawCursorExtent(C);
3003 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3004 return false;
3005 }
3006 return true;
3007}
3008
3009bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3010 while (!WL.empty()) {
3011 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003012 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003013
3014 // Set the Parent field, then back to its old value once we're done.
3015 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3016
3017 switch (LI.getKind()) {
3018 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003019 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 if (!D)
3021 continue;
3022
3023 // For now, perform default visitation for Decls.
3024 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3025 cast<DeclVisit>(&LI)->isFirst())))
3026 return true;
3027
3028 continue;
3029 }
3030 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003031 for (const TemplateArgumentLoc &Arg :
3032 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3033 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 return true;
3035 }
3036 continue;
3037 }
3038 case VisitorJob::TypeLocVisitKind: {
3039 // Perform default visitation for TypeLocs.
3040 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3041 return true;
3042 continue;
3043 }
3044 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003045 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 if (LabelStmt *stmt = LS->getStmt()) {
3047 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3048 TU))) {
3049 return true;
3050 }
3051 }
3052 continue;
3053 }
3054
3055 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3056 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3057 if (VisitNestedNameSpecifierLoc(V->get()))
3058 return true;
3059 continue;
3060 }
3061
3062 case VisitorJob::DeclarationNameInfoVisitKind: {
3063 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3064 ->get()))
3065 return true;
3066 continue;
3067 }
3068 case VisitorJob::MemberRefVisitKind: {
3069 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3070 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3071 return true;
3072 continue;
3073 }
3074 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003075 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 if (!S)
3077 continue;
3078
3079 // Update the current cursor.
3080 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3081 if (!IsInRegionOfInterest(Cursor))
3082 continue;
3083 switch (Visitor(Cursor, Parent, ClientData)) {
3084 case CXChildVisit_Break: return true;
3085 case CXChildVisit_Continue: break;
3086 case CXChildVisit_Recurse:
3087 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003088 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 EnqueueWorkList(WL, S);
3090 break;
3091 }
3092 continue;
3093 }
3094 case VisitorJob::MemberExprPartsKind: {
3095 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003096 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003097
3098 // Visit the nested-name-specifier
3099 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3100 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3101 return true;
3102
3103 // Visit the declaration name.
3104 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3105 return true;
3106
3107 // Visit the explicitly-specified template arguments, if any.
3108 if (M->hasExplicitTemplateArgs()) {
3109 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3110 *ArgEnd = Arg + M->getNumTemplateArgs();
3111 Arg != ArgEnd; ++Arg) {
3112 if (VisitTemplateArgumentLoc(*Arg))
3113 return true;
3114 }
3115 }
3116 continue;
3117 }
3118 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003119 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 // Visit nested-name-specifier, if present.
3121 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3122 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3123 return true;
3124 // Visit declaration name.
3125 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3126 return true;
3127 continue;
3128 }
3129 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003130 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 // Visit the nested-name-specifier.
3132 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3133 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3134 return true;
3135 // Visit the declaration name.
3136 if (VisitDeclarationNameInfo(O->getNameInfo()))
3137 return true;
3138 // Visit the overloaded declaration reference.
3139 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3140 return true;
3141 continue;
3142 }
3143 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003144 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 NamedDecl *Pack = E->getPack();
3146 if (isa<TemplateTypeParmDecl>(Pack)) {
3147 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3148 E->getPackLoc(), TU)))
3149 return true;
3150
3151 continue;
3152 }
3153
3154 if (isa<TemplateTemplateParmDecl>(Pack)) {
3155 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3156 E->getPackLoc(), TU)))
3157 return true;
3158
3159 continue;
3160 }
3161
3162 // Non-type template parameter packs and function parameter packs are
3163 // treated like DeclRefExpr cursors.
3164 continue;
3165 }
3166
3167 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003168 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003169 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3171 CEnd = E->explicit_capture_end();
3172 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003173 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003174 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003175
Guy Benyei11169dd2012-12-18 14:30:41 +00003176 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3177 C->getLocation(),
3178 TU)))
3179 return true;
3180 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003181 // Visit init captures
3182 for (auto InitExpr : E->capture_inits()) {
3183 if (Visit(InitExpr))
3184 return true;
3185 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003186
Haojian Wuef87c262018-12-18 15:29:12 +00003187 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003188 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003189 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3190 if (E->hasExplicitParameters()) {
3191 // Visit parameters.
3192 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3193 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003195 }
3196 if (E->hasExplicitResultType()) {
3197 // Visit result type.
3198 if (Visit(Proto.getReturnLoc()))
3199 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003200 }
3201 }
3202 break;
3203 }
3204
3205 case VisitorJob::PostChildrenVisitKind:
3206 if (PostChildrenVisitor(Parent, ClientData))
3207 return true;
3208 break;
3209 }
3210 }
3211 return false;
3212}
3213
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003214bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003215 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003216 if (!WorkListFreeList.empty()) {
3217 WL = WorkListFreeList.back();
3218 WL->clear();
3219 WorkListFreeList.pop_back();
3220 }
3221 else {
3222 WL = new VisitorWorkList();
3223 WorkListCache.push_back(WL);
3224 }
3225 EnqueueWorkList(*WL, S);
3226 bool result = RunVisitorWorkList(*WL);
3227 WorkListFreeList.push_back(WL);
3228 return result;
3229}
3230
3231namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003232typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003233RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3234 const DeclarationNameInfo &NI, SourceRange QLoc,
3235 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003236 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3237 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3238 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3239
3240 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3241
3242 RefNamePieces Pieces;
3243
3244 if (WantQualifier && QLoc.isValid())
3245 Pieces.push_back(QLoc);
3246
3247 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3248 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003249
3250 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3251 Pieces.push_back(*TemplateArgsLoc);
3252
Guy Benyei11169dd2012-12-18 14:30:41 +00003253 if (Kind == DeclarationName::CXXOperatorName) {
3254 Pieces.push_back(SourceLocation::getFromRawEncoding(
3255 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3256 Pieces.push_back(SourceLocation::getFromRawEncoding(
3257 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3258 }
3259
3260 if (WantSinglePiece) {
3261 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3262 Pieces.clear();
3263 Pieces.push_back(R);
3264 }
3265
3266 return Pieces;
3267}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003268}
Guy Benyei11169dd2012-12-18 14:30:41 +00003269
3270//===----------------------------------------------------------------------===//
3271// Misc. API hooks.
3272//===----------------------------------------------------------------------===//
3273
Chandler Carruth66660742014-06-27 16:37:27 +00003274namespace {
3275struct RegisterFatalErrorHandler {
3276 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003277 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003278 }
3279};
3280}
3281
3282static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3283
Guy Benyei11169dd2012-12-18 14:30:41 +00003284CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3285 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003286 // We use crash recovery to make some of our APIs more reliable, implicitly
3287 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003288 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3289 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003290
Chandler Carruth66660742014-06-27 16:37:27 +00003291 // Look through the managed static to trigger construction of the managed
3292 // static which registers our fatal error handler. This ensures it is only
3293 // registered once.
3294 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003295
Adrian Prantlbc068582015-07-08 01:00:30 +00003296 // Initialize targets for clang module support.
3297 llvm::InitializeAllTargets();
3298 llvm::InitializeAllTargetMCs();
3299 llvm::InitializeAllAsmPrinters();
3300 llvm::InitializeAllAsmParsers();
3301
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003302 CIndexer *CIdxr = new CIndexer();
3303
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 if (excludeDeclarationsFromPCH)
3305 CIdxr->setOnlyLocalDecls();
3306 if (displayDiagnostics)
3307 CIdxr->setDisplayDiagnostics();
3308
3309 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3310 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3311 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3312 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3313 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3314 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3315
3316 return CIdxr;
3317}
3318
3319void clang_disposeIndex(CXIndex CIdx) {
3320 if (CIdx)
3321 delete static_cast<CIndexer *>(CIdx);
3322}
3323
3324void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3325 if (CIdx)
3326 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3327}
3328
3329unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3330 if (CIdx)
3331 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3332 return 0;
3333}
3334
Alex Lorenz08615792017-12-04 21:56:36 +00003335void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3336 const char *Path) {
3337 if (CIdx)
3338 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3339}
3340
Guy Benyei11169dd2012-12-18 14:30:41 +00003341void clang_toggleCrashRecovery(unsigned isEnabled) {
3342 if (isEnabled)
3343 llvm::CrashRecoveryContext::Enable();
3344 else
3345 llvm::CrashRecoveryContext::Disable();
3346}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003347
Guy Benyei11169dd2012-12-18 14:30:41 +00003348CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3349 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003350 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003351 enum CXErrorCode Result =
3352 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003353 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003354 assert((TU && Result == CXError_Success) ||
3355 (!TU && Result != CXError_Success));
3356 return TU;
3357}
3358
3359enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3360 const char *ast_filename,
3361 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003362 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003363 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003364
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003365 if (!CIdx || !ast_filename || !out_TU)
3366 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003367
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003368 LOG_FUNC_SECTION {
3369 *Log << ast_filename;
3370 }
3371
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3373 FileSystemOptions FileSystemOpts;
3374
Justin Bognerd512c1e2014-10-15 00:33:06 +00003375 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3376 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003377 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003378 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3379 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003380 FileSystemOpts, /*UseDebugInfo=*/false,
3381 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003382 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003383 /*AllowPCHWithCompilerErrors=*/true,
3384 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003385 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003386 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003387}
3388
3389unsigned clang_defaultEditingTranslationUnitOptions() {
3390 return CXTranslationUnit_PrecompiledPreamble |
3391 CXTranslationUnit_CacheCompletionResults;
3392}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003393
Guy Benyei11169dd2012-12-18 14:30:41 +00003394CXTranslationUnit
3395clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3396 const char *source_filename,
3397 int num_command_line_args,
3398 const char * const *command_line_args,
3399 unsigned num_unsaved_files,
3400 struct CXUnsavedFile *unsaved_files) {
3401 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3402 return clang_parseTranslationUnit(CIdx, source_filename,
3403 command_line_args, num_command_line_args,
3404 unsaved_files, num_unsaved_files,
3405 Options);
3406}
3407
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003408static CXErrorCode
3409clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3410 const char *const *command_line_args,
3411 int num_command_line_args,
3412 ArrayRef<CXUnsavedFile> unsaved_files,
3413 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003414 // Set up the initial return values.
3415 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003416 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003417
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003418 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003419 if (!CIdx || !out_TU)
3420 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003421
Guy Benyei11169dd2012-12-18 14:30:41 +00003422 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3423
3424 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3425 setThreadBackgroundPriority();
3426
3427 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003428 bool CreatePreambleOnFirstParse =
3429 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 // FIXME: Add a flag for modules.
3431 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003432 = (options & (CXTranslationUnit_Incomplete |
3433 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003434 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003435 = options & CXTranslationUnit_CacheCompletionResults;
3436 bool IncludeBriefCommentsInCodeCompletion
3437 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003438 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3439 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003440 bool RetainExcludedCB = options &
3441 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003442 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3443 if (options & CXTranslationUnit_SkipFunctionBodies) {
3444 SkipFunctionBodies =
3445 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3446 ? SkipFunctionBodiesScope::Preamble
3447 : SkipFunctionBodiesScope::PreambleAndMainFile;
3448 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003449
3450 // Configure the diagnostics.
3451 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003452 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003453
Manuel Klimek016c0242016-03-01 10:56:19 +00003454 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003455 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003456
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003457 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3458 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3459 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3460
Guy Benyei11169dd2012-12-18 14:30:41 +00003461 // Recover resources if we crash before exiting this function.
3462 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3463 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003464 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003465
Ahmed Charlesb8984322014-03-07 20:03:18 +00003466 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3467 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003468
3469 // Recover resources if we crash before exiting this function.
3470 llvm::CrashRecoveryContextCleanupRegistrar<
3471 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3472
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003473 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003474 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003475 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003476 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003477 }
3478
Ahmed Charlesb8984322014-03-07 20:03:18 +00003479 std::unique_ptr<std::vector<const char *>> Args(
3480 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003481
3482 // Recover resources if we crash before exiting this method.
3483 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3484 ArgsCleanup(Args.get());
3485
3486 // Since the Clang C library is primarily used by batch tools dealing with
3487 // (often very broken) source code, where spell-checking can have a
3488 // significant negative impact on performance (particularly when
3489 // precompiled headers are involved), we disable it by default.
3490 // Only do this if we haven't found a spell-checking-related argument.
3491 bool FoundSpellCheckingArgument = false;
3492 for (int I = 0; I != num_command_line_args; ++I) {
3493 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3494 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3495 FoundSpellCheckingArgument = true;
3496 break;
3497 }
3498 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003499 Args->insert(Args->end(), command_line_args,
3500 command_line_args + num_command_line_args);
3501
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003502 if (!FoundSpellCheckingArgument)
3503 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3504
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 // The 'source_filename' argument is optional. If the caller does not
3506 // specify it then it is assumed that the source file is specified
3507 // in the actual argument list.
3508 // Put the source file after command_line_args otherwise if '-x' flag is
3509 // present it will be unused.
3510 if (source_filename)
3511 Args->push_back(source_filename);
3512
3513 // Do we need the detailed preprocessing record?
3514 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3515 Args->push_back("-Xclang");
3516 Args->push_back("-detailed-preprocessing-record");
3517 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003518
3519 // Suppress any editor placeholder diagnostics.
3520 Args->push_back("-fallow-editor-placeholders");
3521
Guy Benyei11169dd2012-12-18 14:30:41 +00003522 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003523 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003524 // Unless the user specified that they want the preamble on the first parse
3525 // set it up to be created on the first reparse. This makes the first parse
3526 // faster, trading for a slower (first) reparse.
3527 unsigned PrecompilePreambleAfterNParses =
3528 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003529
Alex Lorenz08615792017-12-04 21:56:36 +00003530 LibclangInvocationReporter InvocationReporter(
3531 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003532 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3533 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003534 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003535 Args->data(), Args->data() + Args->size(),
3536 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003537 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003538 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003539 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3540 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003541 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003542 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003543 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3544 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003545
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003546 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003547 if (!Unit && !ErrUnit)
3548 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003549
Guy Benyei11169dd2012-12-18 14:30:41 +00003550 if (NumErrors != Diags->getClient()->getNumErrors()) {
3551 // Make sure to check that 'Unit' is non-NULL.
3552 if (CXXIdx->getDisplayDiagnostics())
3553 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3554 }
3555
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003556 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3557 return CXError_ASTReadError;
3558
David Blaikieea4395e2017-01-06 19:49:01 +00003559 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003560 if (CXTranslationUnitImpl *TU = *out_TU) {
3561 TU->ParsingOptions = options;
3562 TU->Arguments.reserve(Args->size());
3563 for (const char *Arg : *Args)
3564 TU->Arguments.push_back(Arg);
3565 return CXError_Success;
3566 }
3567 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003568}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003569
3570CXTranslationUnit
3571clang_parseTranslationUnit(CXIndex CIdx,
3572 const char *source_filename,
3573 const char *const *command_line_args,
3574 int num_command_line_args,
3575 struct CXUnsavedFile *unsaved_files,
3576 unsigned num_unsaved_files,
3577 unsigned options) {
3578 CXTranslationUnit TU;
3579 enum CXErrorCode Result = clang_parseTranslationUnit2(
3580 CIdx, source_filename, command_line_args, num_command_line_args,
3581 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003582 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003583 assert((TU && Result == CXError_Success) ||
3584 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003585 return TU;
3586}
3587
3588enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003589 CXIndex CIdx, const char *source_filename,
3590 const char *const *command_line_args, int num_command_line_args,
3591 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3592 unsigned options, CXTranslationUnit *out_TU) {
3593 SmallVector<const char *, 4> Args;
3594 Args.push_back("clang");
3595 Args.append(command_line_args, command_line_args + num_command_line_args);
3596 return clang_parseTranslationUnit2FullArgv(
3597 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3598 num_unsaved_files, options, out_TU);
3599}
3600
3601enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3602 CXIndex CIdx, const char *source_filename,
3603 const char *const *command_line_args, int num_command_line_args,
3604 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3605 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003606 LOG_FUNC_SECTION {
3607 *Log << source_filename << ": ";
3608 for (int i = 0; i != num_command_line_args; ++i)
3609 *Log << command_line_args[i] << " ";
3610 }
3611
Alp Toker9d85b182014-07-07 01:23:14 +00003612 if (num_unsaved_files && !unsaved_files)
3613 return CXError_InvalidArguments;
3614
Alp Toker5c532982014-07-07 22:42:03 +00003615 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003616 auto ParseTranslationUnitImpl = [=, &result] {
3617 result = clang_parseTranslationUnit_Impl(
3618 CIdx, source_filename, command_line_args, num_command_line_args,
3619 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3620 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003621
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 llvm::CrashRecoveryContext CRC;
3623
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003624 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003625 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3626 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3627 fprintf(stderr, " 'command_line_args' : [");
3628 for (int i = 0; i != num_command_line_args; ++i) {
3629 if (i)
3630 fprintf(stderr, ", ");
3631 fprintf(stderr, "'%s'", command_line_args[i]);
3632 }
3633 fprintf(stderr, "],\n");
3634 fprintf(stderr, " 'unsaved_files' : [");
3635 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3636 if (i)
3637 fprintf(stderr, ", ");
3638 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3639 unsaved_files[i].Length);
3640 }
3641 fprintf(stderr, "],\n");
3642 fprintf(stderr, " 'options' : %d,\n", options);
3643 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003644
3645 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003646 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003647 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003648 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 }
Alp Toker5c532982014-07-07 22:42:03 +00003650
3651 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003652}
3653
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003654CXString clang_Type_getObjCEncoding(CXType CT) {
3655 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3656 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3657 std::string encoding;
3658 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3659 encoding);
3660
3661 return cxstring::createDup(encoding);
3662}
3663
3664static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3665 if (C.kind == CXCursor_MacroDefinition) {
3666 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3667 return MDR->getName();
3668 } else if (C.kind == CXCursor_MacroExpansion) {
3669 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3670 return ME.getName();
3671 }
3672 return nullptr;
3673}
3674
3675unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3676 const IdentifierInfo *II = getMacroIdentifier(C);
3677 if (!II) {
3678 return false;
3679 }
3680 ASTUnit *ASTU = getCursorASTUnit(C);
3681 Preprocessor &PP = ASTU->getPreprocessor();
3682 if (const MacroInfo *MI = PP.getMacroInfo(II))
3683 return MI->isFunctionLike();
3684 return false;
3685}
3686
3687unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3688 const IdentifierInfo *II = getMacroIdentifier(C);
3689 if (!II) {
3690 return false;
3691 }
3692 ASTUnit *ASTU = getCursorASTUnit(C);
3693 Preprocessor &PP = ASTU->getPreprocessor();
3694 if (const MacroInfo *MI = PP.getMacroInfo(II))
3695 return MI->isBuiltinMacro();
3696 return false;
3697}
3698
3699unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3700 const Decl *D = getCursorDecl(C);
3701 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3702 if (!FD) {
3703 return false;
3704 }
3705 return FD->isInlined();
3706}
3707
3708static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3709 if (callExpr->getNumArgs() != 1) {
3710 return nullptr;
3711 }
3712
3713 StringLiteral *S = nullptr;
3714 auto *arg = callExpr->getArg(0);
3715 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3716 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3717 auto *subExpr = I->getSubExprAsWritten();
3718
3719 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3720 return nullptr;
3721 }
3722
3723 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3724 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3725 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3726 } else {
3727 return nullptr;
3728 }
3729 return S;
3730}
3731
David Blaikie59272572016-04-13 18:23:33 +00003732struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003733 CXEvalResultKind EvalType;
3734 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003735 unsigned long long unsignedVal;
3736 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003737 double floatVal;
3738 char *stringVal;
3739 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003740 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003741 ~ExprEvalResult() {
3742 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3743 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003744 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003745 }
3746 }
3747};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003748
3749void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003750 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003751}
3752
3753CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3754 if (!E) {
3755 return CXEval_UnExposed;
3756 }
3757 return ((ExprEvalResult *)E)->EvalType;
3758}
3759
3760int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003761 return clang_EvalResult_getAsLongLong(E);
3762}
3763
3764long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003765 if (!E) {
3766 return 0;
3767 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003768 ExprEvalResult *Result = (ExprEvalResult*)E;
3769 if (Result->IsUnsignedInt)
3770 return Result->EvalData.unsignedVal;
3771 return Result->EvalData.intVal;
3772}
3773
3774unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3775 return ((ExprEvalResult *)E)->IsUnsignedInt;
3776}
3777
3778unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3779 if (!E) {
3780 return 0;
3781 }
3782
3783 ExprEvalResult *Result = (ExprEvalResult*)E;
3784 if (Result->IsUnsignedInt)
3785 return Result->EvalData.unsignedVal;
3786 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003787}
3788
3789double clang_EvalResult_getAsDouble(CXEvalResult E) {
3790 if (!E) {
3791 return 0;
3792 }
3793 return ((ExprEvalResult *)E)->EvalData.floatVal;
3794}
3795
3796const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3797 if (!E) {
3798 return nullptr;
3799 }
3800 return ((ExprEvalResult *)E)->EvalData.stringVal;
3801}
3802
3803static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3804 Expr::EvalResult ER;
3805 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003806 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003807 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003808
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003809 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003810 if (expr->isValueDependent())
3811 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003812 if (!expr->EvaluateAsRValue(ER, ctx))
3813 return nullptr;
3814
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003815 QualType rettype;
3816 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003817 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003818 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003819 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003820
David Blaikiebbc00882016-04-13 18:36:19 +00003821 if (ER.Val.isInt()) {
3822 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003823
3824 auto& val = ER.Val.getInt();
3825 if (val.isUnsigned()) {
3826 result->IsUnsignedInt = true;
3827 result->EvalData.unsignedVal = val.getZExtValue();
3828 } else {
3829 result->EvalData.intVal = val.getExtValue();
3830 }
3831
David Blaikiebbc00882016-04-13 18:36:19 +00003832 return result.release();
3833 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003834
David Blaikiebbc00882016-04-13 18:36:19 +00003835 if (ER.Val.isFloat()) {
3836 llvm::SmallVector<char, 100> Buffer;
3837 ER.Val.getFloat().toString(Buffer);
3838 std::string floatStr(Buffer.data(), Buffer.size());
3839 result->EvalType = CXEval_Float;
3840 bool ignored;
3841 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003842 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003843 llvm::APFloat::rmNearestTiesToEven, &ignored);
3844 result->EvalData.floatVal = apFloat.convertToDouble();
3845 return result.release();
3846 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003847
David Blaikiebbc00882016-04-13 18:36:19 +00003848 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3849 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3850 auto *subExpr = I->getSubExprAsWritten();
3851 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3852 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003853 const StringLiteral *StrE = nullptr;
3854 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003855 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003856
3857 if (ObjCExpr) {
3858 StrE = ObjCExpr->getString();
3859 result->EvalType = CXEval_ObjCStrLiteral;
3860 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003861 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003862 result->EvalType = CXEval_StrLiteral;
3863 }
3864
3865 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003866 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003867 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3868 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003869 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003870 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003871 }
3872 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3873 expr->getStmtClass() == Stmt::StringLiteralClass) {
3874 const StringLiteral *StrE = nullptr;
3875 const ObjCStringLiteral *ObjCExpr;
3876 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003877
David Blaikiebbc00882016-04-13 18:36:19 +00003878 if (ObjCExpr) {
3879 StrE = ObjCExpr->getString();
3880 result->EvalType = CXEval_ObjCStrLiteral;
3881 } else {
3882 StrE = cast<StringLiteral>(expr);
3883 result->EvalType = CXEval_StrLiteral;
3884 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003885
David Blaikiebbc00882016-04-13 18:36:19 +00003886 std::string strRef(StrE->getString().str());
3887 result->EvalData.stringVal = new char[strRef.size() + 1];
3888 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3889 result->EvalData.stringVal[strRef.size()] = '\0';
3890 return result.release();
3891 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003892
David Blaikiebbc00882016-04-13 18:36:19 +00003893 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3894 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003895
David Blaikiebbc00882016-04-13 18:36:19 +00003896 rettype = CC->getType();
3897 if (rettype.getAsString() == "CFStringRef" &&
3898 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003899
David Blaikiebbc00882016-04-13 18:36:19 +00003900 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3901 StringLiteral *S = getCFSTR_value(callExpr);
3902 if (S) {
3903 std::string strLiteral(S->getString().str());
3904 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003905
David Blaikiebbc00882016-04-13 18:36:19 +00003906 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3907 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3908 strLiteral.size());
3909 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003910 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003911 }
3912 }
3913
David Blaikiebbc00882016-04-13 18:36:19 +00003914 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3915 callExpr = static_cast<CallExpr *>(expr);
3916 rettype = callExpr->getCallReturnType(ctx);
3917
3918 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3919 return nullptr;
3920
3921 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3922 if (callExpr->getNumArgs() == 1 &&
3923 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3924 return nullptr;
3925 } else if (rettype.getAsString() == "CFStringRef") {
3926
3927 StringLiteral *S = getCFSTR_value(callExpr);
3928 if (S) {
3929 std::string strLiteral(S->getString().str());
3930 result->EvalType = CXEval_CFStr;
3931 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3932 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3933 strLiteral.size());
3934 result->EvalData.stringVal[strLiteral.size()] = '\0';
3935 return result.release();
3936 }
3937 }
3938 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3939 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3940 ValueDecl *V = D->getDecl();
3941 if (V->getKind() == Decl::Function) {
3942 std::string strName = V->getNameAsString();
3943 result->EvalType = CXEval_Other;
3944 result->EvalData.stringVal = new char[strName.size() + 1];
3945 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3946 result->EvalData.stringVal[strName.size()] = '\0';
3947 return result.release();
3948 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003949 }
3950
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003951 return nullptr;
3952}
3953
Alex Lorenz65317e12019-01-08 22:32:51 +00003954static const Expr *evaluateDeclExpr(const Decl *D) {
3955 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003956 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003957 if (auto *Var = dyn_cast<VarDecl>(D))
3958 return Var->getInit();
3959 else if (auto *Field = dyn_cast<FieldDecl>(D))
3960 return Field->getInClassInitializer();
3961 return nullptr;
3962}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003963
Alex Lorenz65317e12019-01-08 22:32:51 +00003964static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3965 assert(CS && "invalid compound statement");
3966 for (auto *bodyIterator : CS->body()) {
3967 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3968 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003969 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003970 return nullptr;
3971}
3972
Alex Lorenz65317e12019-01-08 22:32:51 +00003973CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3974 if (const Expr *E =
3975 clang_getCursorKind(C) == CXCursor_CompoundStmt
3976 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3977 : evaluateDeclExpr(getCursorDecl(C)))
3978 return const_cast<CXEvalResult>(
3979 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3980 return nullptr;
3981}
3982
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003983unsigned clang_Cursor_hasAttrs(CXCursor C) {
3984 const Decl *D = getCursorDecl(C);
3985 if (!D) {
3986 return 0;
3987 }
3988
3989 if (D->hasAttrs()) {
3990 return 1;
3991 }
3992
3993 return 0;
3994}
Guy Benyei11169dd2012-12-18 14:30:41 +00003995unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3996 return CXSaveTranslationUnit_None;
3997}
3998
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003999static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4000 const char *FileName,
4001 unsigned options) {
4002 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4004 setThreadBackgroundPriority();
4005
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004006 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4007 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004008}
4009
4010int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4011 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004012 LOG_FUNC_SECTION {
4013 *Log << TU << ' ' << FileName;
4014 }
4015
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004016 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004017 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004019 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004020
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004021 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004022 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4023 if (!CXXUnit->hasSema())
4024 return CXSaveError_InvalidTU;
4025
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004026 CXSaveError result;
4027 auto SaveTranslationUnitImpl = [=, &result]() {
4028 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4029 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004030
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004031 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004032 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004033
4034 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4035 PrintLibclangResourceUsage(TU);
4036
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004037 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 }
4039
4040 // We have an AST that has invalid nodes due to compiler errors.
4041 // Use a crash recovery thread for protection.
4042
4043 llvm::CrashRecoveryContext CRC;
4044
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004045 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4047 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4048 fprintf(stderr, " 'options' : %d,\n", options);
4049 fprintf(stderr, "}\n");
4050
4051 return CXSaveError_Unknown;
4052
4053 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4054 PrintLibclangResourceUsage(TU);
4055 }
4056
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004057 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004058}
4059
4060void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4061 if (CTUnit) {
4062 // If the translation unit has been marked as unsafe to free, just discard
4063 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004064 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4065 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 return;
4067
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004068 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004069 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4071 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004072 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004073 delete CTUnit;
4074 }
4075}
4076
Erik Verbruggen346066b2017-05-30 14:25:54 +00004077unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4078 if (CTUnit) {
4079 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4080
4081 if (Unit && Unit->isUnsafeToFree())
4082 return false;
4083
4084 Unit->ResetForParse();
4085 return true;
4086 }
4087
4088 return false;
4089}
4090
Guy Benyei11169dd2012-12-18 14:30:41 +00004091unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4092 return CXReparse_None;
4093}
4094
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004095static CXErrorCode
4096clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4097 ArrayRef<CXUnsavedFile> unsaved_files,
4098 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004099 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004100 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004101 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004102 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004103 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004104
4105 // Reset the associated diagnostics.
4106 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004107 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004108
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004109 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4111 setThreadBackgroundPriority();
4112
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004113 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004115
4116 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4117 new std::vector<ASTUnit::RemappedFile>());
4118
Guy Benyei11169dd2012-12-18 14:30:41 +00004119 // Recover resources if we crash before exiting this function.
4120 llvm::CrashRecoveryContextCleanupRegistrar<
4121 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004122
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004123 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004124 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004125 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004126 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004128
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004129 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4130 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004131 return CXError_Success;
4132 if (isASTReadError(CXXUnit))
4133 return CXError_ASTReadError;
4134 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004135}
4136
4137int clang_reparseTranslationUnit(CXTranslationUnit TU,
4138 unsigned num_unsaved_files,
4139 struct CXUnsavedFile *unsaved_files,
4140 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004141 LOG_FUNC_SECTION {
4142 *Log << TU;
4143 }
4144
Alp Toker9d85b182014-07-07 01:23:14 +00004145 if (num_unsaved_files && !unsaved_files)
4146 return CXError_InvalidArguments;
4147
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004148 CXErrorCode result;
4149 auto ReparseTranslationUnitImpl = [=, &result]() {
4150 result = clang_reparseTranslationUnit_Impl(
4151 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4152 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004153
Guy Benyei11169dd2012-12-18 14:30:41 +00004154 llvm::CrashRecoveryContext CRC;
4155
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004156 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004158 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004159 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004160 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4161 PrintLibclangResourceUsage(TU);
4162
Alp Toker5c532982014-07-07 22:42:03 +00004163 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004164}
4165
4166
4167CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004168 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004169 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004170 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004171 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004172
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004173 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004174 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004175}
4176
4177CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004178 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004179 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004180 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004181 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004182
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004183 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4185}
4186
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004187CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4188 if (isNotUsableTU(CTUnit)) {
4189 LOG_BAD_TU(CTUnit);
4190 return nullptr;
4191 }
4192
4193 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4194 impl->TranslationUnit = CTUnit;
4195 return impl;
4196}
4197
4198CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4199 if (!TargetInfo)
4200 return cxstring::createEmpty();
4201
4202 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4203 assert(!isNotUsableTU(CTUnit) &&
4204 "Unexpected unusable translation unit in TargetInfo");
4205
4206 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4207 std::string Triple =
4208 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4209 return cxstring::createDup(Triple);
4210}
4211
4212int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4213 if (!TargetInfo)
4214 return -1;
4215
4216 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4217 assert(!isNotUsableTU(CTUnit) &&
4218 "Unexpected unusable translation unit in TargetInfo");
4219
4220 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4221 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4222}
4223
4224void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4225 if (!TargetInfo)
4226 return;
4227
4228 delete TargetInfo;
4229}
4230
Guy Benyei11169dd2012-12-18 14:30:41 +00004231//===----------------------------------------------------------------------===//
4232// CXFile Operations.
4233//===----------------------------------------------------------------------===//
4234
Guy Benyei11169dd2012-12-18 14:30:41 +00004235CXString clang_getFileName(CXFile SFile) {
4236 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004237 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004238
4239 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004240 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004241}
4242
4243time_t clang_getFileTime(CXFile SFile) {
4244 if (!SFile)
4245 return 0;
4246
4247 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4248 return FEnt->getModificationTime();
4249}
4250
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004251CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004252 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004253 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004254 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004255 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004256
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004257 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004258
4259 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004260 auto File = FMgr.getFile(file_name);
4261 if (!File)
4262 return nullptr;
4263 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004264}
4265
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004266const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4267 size_t *size) {
4268 if (isNotUsableTU(TU)) {
4269 LOG_BAD_TU(TU);
4270 return nullptr;
4271 }
4272
4273 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4274 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4275 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004276 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004277 if (Invalid) {
4278 if (size)
4279 *size = 0;
4280 return nullptr;
4281 }
4282 if (size)
4283 *size = buf->getBufferSize();
4284 return buf->getBufferStart();
4285}
4286
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004287unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4288 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004289 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004290 LOG_BAD_TU(TU);
4291 return 0;
4292 }
4293
4294 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 return 0;
4296
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004297 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 FileEntry *FEnt = static_cast<FileEntry *>(file);
4299 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4300 .isFileMultipleIncludeGuarded(FEnt);
4301}
4302
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004303int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4304 if (!file || !outID)
4305 return 1;
4306
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004307 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004308 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4309 outID->data[0] = ID.getDevice();
4310 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004311 outID->data[2] = FEnt->getModificationTime();
4312 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004313}
4314
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004315int clang_File_isEqual(CXFile file1, CXFile file2) {
4316 if (file1 == file2)
4317 return true;
4318
4319 if (!file1 || !file2)
4320 return false;
4321
4322 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4323 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4324 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4325}
4326
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004327CXString clang_File_tryGetRealPathName(CXFile SFile) {
4328 if (!SFile)
4329 return cxstring::createNull();
4330
4331 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4332 return cxstring::createRef(FEnt->tryGetRealPathName());
4333}
4334
Guy Benyei11169dd2012-12-18 14:30:41 +00004335//===----------------------------------------------------------------------===//
4336// CXCursor Operations.
4337//===----------------------------------------------------------------------===//
4338
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004339static const Decl *getDeclFromExpr(const Stmt *E) {
4340 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 return getDeclFromExpr(CE->getSubExpr());
4342
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004343 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004345 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004347 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004349 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004350 if (PRE->isExplicitProperty())
4351 return PRE->getExplicitProperty();
4352 // It could be messaging both getter and setter as in:
4353 // ++myobj.myprop;
4354 // in which case prefer to associate the setter since it is less obvious
4355 // from inspecting the source that the setter is going to get called.
4356 if (PRE->isMessagingSetter())
4357 return PRE->getImplicitPropertySetter();
4358 return PRE->getImplicitPropertyGetter();
4359 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004360 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004362 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 if (Expr *Src = OVE->getSourceExpr())
4364 return getDeclFromExpr(Src);
4365
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004366 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004368 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 if (!CE->isElidable())
4370 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004371 if (const CXXInheritedCtorInitExpr *CE =
4372 dyn_cast<CXXInheritedCtorInitExpr>(E))
4373 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004374 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 return OME->getMethodDecl();
4376
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004377 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004378 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004379 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4381 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004382 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4384 isa<ParmVarDecl>(SizeOfPack->getPack()))
4385 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004386
4387 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004388}
4389
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004390static SourceLocation getLocationFromExpr(const Expr *E) {
4391 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 return getLocationFromExpr(CE->getSubExpr());
4393
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004394 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004395 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004396 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004398 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004400 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004402 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004404 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004406
4407 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004408}
4409
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004410extern "C" {
4411
Guy Benyei11169dd2012-12-18 14:30:41 +00004412unsigned clang_visitChildren(CXCursor parent,
4413 CXCursorVisitor visitor,
4414 CXClientData client_data) {
4415 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4416 /*VisitPreprocessorLast=*/false);
4417 return CursorVis.VisitChildren(parent);
4418}
4419
4420#ifndef __has_feature
4421#define __has_feature(x) 0
4422#endif
4423#if __has_feature(blocks)
4424typedef enum CXChildVisitResult
4425 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4426
4427static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4428 CXClientData client_data) {
4429 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4430 return block(cursor, parent);
4431}
4432#else
4433// If we are compiled with a compiler that doesn't have native blocks support,
4434// define and call the block manually, so the
4435typedef struct _CXChildVisitResult
4436{
4437 void *isa;
4438 int flags;
4439 int reserved;
4440 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4441 CXCursor);
4442} *CXCursorVisitorBlock;
4443
4444static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4445 CXClientData client_data) {
4446 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4447 return block->invoke(block, cursor, parent);
4448}
4449#endif
4450
4451
4452unsigned clang_visitChildrenWithBlock(CXCursor parent,
4453 CXCursorVisitorBlock block) {
4454 return clang_visitChildren(parent, visitWithBlock, block);
4455}
4456
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004457static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004459 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004460
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004461 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004463 if (const ObjCPropertyImplDecl *PropImpl =
4464 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004466 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004467
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004468 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004470 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004471
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004472 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 }
4474
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004475 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004476 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004477
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004478 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4480 // and returns different names. NamedDecl returns the class name and
4481 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004482 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004483
4484 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004485 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004486
4487 SmallString<1024> S;
4488 llvm::raw_svector_ostream os(S);
4489 ND->printName(os);
4490
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004491 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004492}
4493
4494CXString clang_getCursorSpelling(CXCursor C) {
4495 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004496 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004497
4498 if (clang_isReference(C.kind)) {
4499 switch (C.kind) {
4500 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004501 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004502 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 }
4504 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004505 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004506 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 }
4508 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004509 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004511 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 }
4513 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004514 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004515 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 }
4517 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004518 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 assert(Type && "Missing type decl");
4520
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004521 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004522 getAsString());
4523 }
4524 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004525 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004526 assert(Template && "Missing template decl");
4527
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004528 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 }
4530
4531 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004532 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 assert(NS && "Missing namespace decl");
4534
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004535 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 }
4537
4538 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004539 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 assert(Field && "Missing member decl");
4541
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004542 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 }
4544
4545 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004546 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 assert(Label && "Missing label");
4548
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004549 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 }
4551
4552 case CXCursor_OverloadedDeclRef: {
4553 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004554 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4555 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004556 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004557 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004559 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004560 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 OverloadedTemplateStorage *Ovl
4562 = Storage.get<OverloadedTemplateStorage*>();
4563 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004564 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004565 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 }
4567
4568 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004569 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 assert(Var && "Missing variable decl");
4571
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004572 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 }
4574
4575 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004576 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 }
4578 }
4579
4580 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004581 const Expr *E = getCursorExpr(C);
4582
4583 if (C.kind == CXCursor_ObjCStringLiteral ||
4584 C.kind == CXCursor_StringLiteral) {
4585 const StringLiteral *SLit;
4586 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4587 SLit = OSL->getString();
4588 } else {
4589 SLit = cast<StringLiteral>(E);
4590 }
4591 SmallString<256> Buf;
4592 llvm::raw_svector_ostream OS(Buf);
4593 SLit->outputString(OS);
4594 return cxstring::createDup(OS.str());
4595 }
4596
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004597 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 if (D)
4599 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004600 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 }
4602
4603 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004604 const Stmt *S = getCursorStmt(C);
4605 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004606 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004607
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004608 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 }
4610
4611 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004612 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 ->getNameStart());
4614
4615 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004616 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 ->getNameStart());
4618
4619 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004620 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004621
4622 if (clang_isDeclaration(C.kind))
4623 return getDeclSpelling(getCursorDecl(C));
4624
4625 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004626 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004627 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 }
4629
4630 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004631 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004632 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 }
4634
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004635 if (C.kind == CXCursor_PackedAttr) {
4636 return cxstring::createRef("packed");
4637 }
4638
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004639 if (C.kind == CXCursor_VisibilityAttr) {
4640 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4641 switch (AA->getVisibility()) {
4642 case VisibilityAttr::VisibilityType::Default:
4643 return cxstring::createRef("default");
4644 case VisibilityAttr::VisibilityType::Hidden:
4645 return cxstring::createRef("hidden");
4646 case VisibilityAttr::VisibilityType::Protected:
4647 return cxstring::createRef("protected");
4648 }
4649 llvm_unreachable("unknown visibility type");
4650 }
4651
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004652 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004653}
4654
4655CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4656 unsigned pieceIndex,
4657 unsigned options) {
4658 if (clang_Cursor_isNull(C))
4659 return clang_getNullRange();
4660
4661 ASTContext &Ctx = getCursorContext(C);
4662
4663 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004664 const Stmt *S = getCursorStmt(C);
4665 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004666 if (pieceIndex > 0)
4667 return clang_getNullRange();
4668 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4669 }
4670
4671 return clang_getNullRange();
4672 }
4673
4674 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004675 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004676 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4677 if (pieceIndex >= ME->getNumSelectorLocs())
4678 return clang_getNullRange();
4679 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4680 }
4681 }
4682
4683 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4684 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004685 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4687 if (pieceIndex >= MD->getNumSelectorLocs())
4688 return clang_getNullRange();
4689 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4690 }
4691 }
4692
4693 if (C.kind == CXCursor_ObjCCategoryDecl ||
4694 C.kind == CXCursor_ObjCCategoryImplDecl) {
4695 if (pieceIndex > 0)
4696 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004697 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4699 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004700 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4702 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4703 }
4704
4705 if (C.kind == CXCursor_ModuleImportDecl) {
4706 if (pieceIndex > 0)
4707 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004708 if (const ImportDecl *ImportD =
4709 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4711 if (!Locs.empty())
4712 return cxloc::translateSourceRange(Ctx,
4713 SourceRange(Locs.front(), Locs.back()));
4714 }
4715 return clang_getNullRange();
4716 }
4717
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004718 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004719 C.kind == CXCursor_ConversionFunction ||
4720 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004721 if (pieceIndex > 0)
4722 return clang_getNullRange();
4723 if (const FunctionDecl *FD =
4724 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4725 DeclarationNameInfo FunctionName = FD->getNameInfo();
4726 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4727 }
4728 return clang_getNullRange();
4729 }
4730
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 // FIXME: A CXCursor_InclusionDirective should give the location of the
4732 // filename, but we don't keep track of this.
4733
4734 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4735 // but we don't keep track of this.
4736
4737 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4738 // but we don't keep track of this.
4739
4740 // Default handling, give the location of the cursor.
4741
4742 if (pieceIndex > 0)
4743 return clang_getNullRange();
4744
4745 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4746 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4747 return cxloc::translateSourceRange(Ctx, Loc);
4748}
4749
Eli Bendersky44a206f2014-07-31 18:04:56 +00004750CXString clang_Cursor_getMangling(CXCursor C) {
4751 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4752 return cxstring::createEmpty();
4753
Eli Bendersky44a206f2014-07-31 18:04:56 +00004754 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004755 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004756 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4757 return cxstring::createEmpty();
4758
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004759 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004760 ASTNameGenerator ASTNameGen(Ctx);
4761 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004762}
4763
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004764CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4765 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4766 return nullptr;
4767
4768 const Decl *D = getCursorDecl(C);
4769 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4770 return nullptr;
4771
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004772 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004773 ASTNameGenerator ASTNameGen(Ctx);
4774 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004775 return cxstring::createSet(Manglings);
4776}
4777
Dave Lee1a532c92017-09-22 16:58:57 +00004778CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4779 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4780 return nullptr;
4781
4782 const Decl *D = getCursorDecl(C);
4783 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4784 return nullptr;
4785
4786 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004787 ASTNameGenerator ASTNameGen(Ctx);
4788 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004789 return cxstring::createSet(Manglings);
4790}
4791
Jonathan Coe45ef5032018-01-16 10:19:56 +00004792CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4793 if (clang_Cursor_isNull(C))
4794 return 0;
4795 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4796}
4797
4798void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4799 if (Policy)
4800 delete static_cast<PrintingPolicy *>(Policy);
4801}
4802
4803unsigned
4804clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4805 enum CXPrintingPolicyProperty Property) {
4806 if (!Policy)
4807 return 0;
4808
4809 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4810 switch (Property) {
4811 case CXPrintingPolicy_Indentation:
4812 return P->Indentation;
4813 case CXPrintingPolicy_SuppressSpecifiers:
4814 return P->SuppressSpecifiers;
4815 case CXPrintingPolicy_SuppressTagKeyword:
4816 return P->SuppressTagKeyword;
4817 case CXPrintingPolicy_IncludeTagDefinition:
4818 return P->IncludeTagDefinition;
4819 case CXPrintingPolicy_SuppressScope:
4820 return P->SuppressScope;
4821 case CXPrintingPolicy_SuppressUnwrittenScope:
4822 return P->SuppressUnwrittenScope;
4823 case CXPrintingPolicy_SuppressInitializers:
4824 return P->SuppressInitializers;
4825 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4826 return P->ConstantArraySizeAsWritten;
4827 case CXPrintingPolicy_AnonymousTagLocations:
4828 return P->AnonymousTagLocations;
4829 case CXPrintingPolicy_SuppressStrongLifetime:
4830 return P->SuppressStrongLifetime;
4831 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4832 return P->SuppressLifetimeQualifiers;
4833 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4834 return P->SuppressTemplateArgsInCXXConstructors;
4835 case CXPrintingPolicy_Bool:
4836 return P->Bool;
4837 case CXPrintingPolicy_Restrict:
4838 return P->Restrict;
4839 case CXPrintingPolicy_Alignof:
4840 return P->Alignof;
4841 case CXPrintingPolicy_UnderscoreAlignof:
4842 return P->UnderscoreAlignof;
4843 case CXPrintingPolicy_UseVoidForZeroParams:
4844 return P->UseVoidForZeroParams;
4845 case CXPrintingPolicy_TerseOutput:
4846 return P->TerseOutput;
4847 case CXPrintingPolicy_PolishForDeclaration:
4848 return P->PolishForDeclaration;
4849 case CXPrintingPolicy_Half:
4850 return P->Half;
4851 case CXPrintingPolicy_MSWChar:
4852 return P->MSWChar;
4853 case CXPrintingPolicy_IncludeNewlines:
4854 return P->IncludeNewlines;
4855 case CXPrintingPolicy_MSVCFormatting:
4856 return P->MSVCFormatting;
4857 case CXPrintingPolicy_ConstantsAsWritten:
4858 return P->ConstantsAsWritten;
4859 case CXPrintingPolicy_SuppressImplicitBase:
4860 return P->SuppressImplicitBase;
4861 case CXPrintingPolicy_FullyQualifiedName:
4862 return P->FullyQualifiedName;
4863 }
4864
4865 assert(false && "Invalid CXPrintingPolicyProperty");
4866 return 0;
4867}
4868
4869void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4870 enum CXPrintingPolicyProperty Property,
4871 unsigned Value) {
4872 if (!Policy)
4873 return;
4874
4875 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4876 switch (Property) {
4877 case CXPrintingPolicy_Indentation:
4878 P->Indentation = Value;
4879 return;
4880 case CXPrintingPolicy_SuppressSpecifiers:
4881 P->SuppressSpecifiers = Value;
4882 return;
4883 case CXPrintingPolicy_SuppressTagKeyword:
4884 P->SuppressTagKeyword = Value;
4885 return;
4886 case CXPrintingPolicy_IncludeTagDefinition:
4887 P->IncludeTagDefinition = Value;
4888 return;
4889 case CXPrintingPolicy_SuppressScope:
4890 P->SuppressScope = Value;
4891 return;
4892 case CXPrintingPolicy_SuppressUnwrittenScope:
4893 P->SuppressUnwrittenScope = Value;
4894 return;
4895 case CXPrintingPolicy_SuppressInitializers:
4896 P->SuppressInitializers = Value;
4897 return;
4898 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4899 P->ConstantArraySizeAsWritten = Value;
4900 return;
4901 case CXPrintingPolicy_AnonymousTagLocations:
4902 P->AnonymousTagLocations = Value;
4903 return;
4904 case CXPrintingPolicy_SuppressStrongLifetime:
4905 P->SuppressStrongLifetime = Value;
4906 return;
4907 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4908 P->SuppressLifetimeQualifiers = Value;
4909 return;
4910 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4911 P->SuppressTemplateArgsInCXXConstructors = Value;
4912 return;
4913 case CXPrintingPolicy_Bool:
4914 P->Bool = Value;
4915 return;
4916 case CXPrintingPolicy_Restrict:
4917 P->Restrict = Value;
4918 return;
4919 case CXPrintingPolicy_Alignof:
4920 P->Alignof = Value;
4921 return;
4922 case CXPrintingPolicy_UnderscoreAlignof:
4923 P->UnderscoreAlignof = Value;
4924 return;
4925 case CXPrintingPolicy_UseVoidForZeroParams:
4926 P->UseVoidForZeroParams = Value;
4927 return;
4928 case CXPrintingPolicy_TerseOutput:
4929 P->TerseOutput = Value;
4930 return;
4931 case CXPrintingPolicy_PolishForDeclaration:
4932 P->PolishForDeclaration = Value;
4933 return;
4934 case CXPrintingPolicy_Half:
4935 P->Half = Value;
4936 return;
4937 case CXPrintingPolicy_MSWChar:
4938 P->MSWChar = Value;
4939 return;
4940 case CXPrintingPolicy_IncludeNewlines:
4941 P->IncludeNewlines = Value;
4942 return;
4943 case CXPrintingPolicy_MSVCFormatting:
4944 P->MSVCFormatting = Value;
4945 return;
4946 case CXPrintingPolicy_ConstantsAsWritten:
4947 P->ConstantsAsWritten = Value;
4948 return;
4949 case CXPrintingPolicy_SuppressImplicitBase:
4950 P->SuppressImplicitBase = Value;
4951 return;
4952 case CXPrintingPolicy_FullyQualifiedName:
4953 P->FullyQualifiedName = Value;
4954 return;
4955 }
4956
4957 assert(false && "Invalid CXPrintingPolicyProperty");
4958}
4959
4960CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4961 if (clang_Cursor_isNull(C))
4962 return cxstring::createEmpty();
4963
4964 if (clang_isDeclaration(C.kind)) {
4965 const Decl *D = getCursorDecl(C);
4966 if (!D)
4967 return cxstring::createEmpty();
4968
4969 SmallString<128> Str;
4970 llvm::raw_svector_ostream OS(Str);
4971 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4972 D->print(OS, UserPolicy ? *UserPolicy
4973 : getCursorContext(C).getPrintingPolicy());
4974
4975 return cxstring::createDup(OS.str());
4976 }
4977
4978 return cxstring::createEmpty();
4979}
4980
Guy Benyei11169dd2012-12-18 14:30:41 +00004981CXString clang_getCursorDisplayName(CXCursor C) {
4982 if (!clang_isDeclaration(C.kind))
4983 return clang_getCursorSpelling(C);
4984
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004985 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004987 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004988
4989 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004990 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 D = FunTmpl->getTemplatedDecl();
4992
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004993 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004994 SmallString<64> Str;
4995 llvm::raw_svector_ostream OS(Str);
4996 OS << *Function;
4997 if (Function->getPrimaryTemplate())
4998 OS << "<>";
4999 OS << "(";
5000 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5001 if (I)
5002 OS << ", ";
5003 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5004 }
5005
5006 if (Function->isVariadic()) {
5007 if (Function->getNumParams())
5008 OS << ", ";
5009 OS << "...";
5010 }
5011 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005012 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 }
5014
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005015 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 SmallString<64> Str;
5017 llvm::raw_svector_ostream OS(Str);
5018 OS << *ClassTemplate;
5019 OS << "<";
5020 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5021 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5022 if (I)
5023 OS << ", ";
5024
5025 NamedDecl *Param = Params->getParam(I);
5026 if (Param->getIdentifier()) {
5027 OS << Param->getIdentifier()->getName();
5028 continue;
5029 }
5030
5031 // There is no parameter name, which makes this tricky. Try to come up
5032 // with something useful that isn't too long.
5033 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5034 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
5035 else if (NonTypeTemplateParmDecl *NTTP
5036 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5037 OS << NTTP->getType().getAsString(Policy);
5038 else
5039 OS << "template<...> class";
5040 }
5041
5042 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005043 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 }
5045
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005046 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5048 // If the type was explicitly written, use that.
5049 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005050 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005051
Benjamin Kramer9170e912013-02-22 15:46:01 +00005052 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 llvm::raw_svector_ostream OS(Str);
5054 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005055 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5056 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005057 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 }
5059
5060 return clang_getCursorSpelling(C);
5061}
5062
5063CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5064 switch (Kind) {
5065 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005094 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005129 case CXCursor_FixedPointLiteral:
5130 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005145 case CXCursor_OMPArraySectionExpr:
5146 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005197 case CXCursor_ObjCAvailabilityCheckExpr:
5198 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005199 case CXCursor_ObjCSelfExpr:
5200 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005227 case CXCursor_BuiltinBitCastExpr:
5228 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005262 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005268 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005270 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005272 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005273 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005274 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005275 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005276 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005278 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005280 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005282 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005284 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005286 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005288 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005290 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005291 case CXCursor_SEHLeaveStmt:
5292 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005294 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005295 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005296 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005298 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005300 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005301 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005302 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005303 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005304 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005305 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005306 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005307 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005308 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005309 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005310 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005312 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005313 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005314 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005316 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005317 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005318 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005319 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005320 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005321 case CXCursor_PackedAttr:
5322 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005323 case CXCursor_PureAttr:
5324 return cxstring::createRef("attribute(pure)");
5325 case CXCursor_ConstAttr:
5326 return cxstring::createRef("attribute(const)");
5327 case CXCursor_NoDuplicateAttr:
5328 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005329 case CXCursor_CUDAConstantAttr:
5330 return cxstring::createRef("attribute(constant)");
5331 case CXCursor_CUDADeviceAttr:
5332 return cxstring::createRef("attribute(device)");
5333 case CXCursor_CUDAGlobalAttr:
5334 return cxstring::createRef("attribute(global)");
5335 case CXCursor_CUDAHostAttr:
5336 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005337 case CXCursor_CUDASharedAttr:
5338 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005339 case CXCursor_VisibilityAttr:
5340 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005341 case CXCursor_DLLExport:
5342 return cxstring::createRef("attribute(dllexport)");
5343 case CXCursor_DLLImport:
5344 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005345 case CXCursor_NSReturnsRetained:
5346 return cxstring::createRef("attribute(ns_returns_retained)");
5347 case CXCursor_NSReturnsNotRetained:
5348 return cxstring::createRef("attribute(ns_returns_not_retained)");
5349 case CXCursor_NSReturnsAutoreleased:
5350 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5351 case CXCursor_NSConsumesSelf:
5352 return cxstring::createRef("attribute(ns_consumes_self)");
5353 case CXCursor_NSConsumed:
5354 return cxstring::createRef("attribute(ns_consumed)");
5355 case CXCursor_ObjCException:
5356 return cxstring::createRef("attribute(objc_exception)");
5357 case CXCursor_ObjCNSObject:
5358 return cxstring::createRef("attribute(NSObject)");
5359 case CXCursor_ObjCIndependentClass:
5360 return cxstring::createRef("attribute(objc_independent_class)");
5361 case CXCursor_ObjCPreciseLifetime:
5362 return cxstring::createRef("attribute(objc_precise_lifetime)");
5363 case CXCursor_ObjCReturnsInnerPointer:
5364 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5365 case CXCursor_ObjCRequiresSuper:
5366 return cxstring::createRef("attribute(objc_requires_super)");
5367 case CXCursor_ObjCRootClass:
5368 return cxstring::createRef("attribute(objc_root_class)");
5369 case CXCursor_ObjCSubclassingRestricted:
5370 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5371 case CXCursor_ObjCExplicitProtocolImpl:
5372 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5373 case CXCursor_ObjCDesignatedInitializer:
5374 return cxstring::createRef("attribute(objc_designated_initializer)");
5375 case CXCursor_ObjCRuntimeVisible:
5376 return cxstring::createRef("attribute(objc_runtime_visible)");
5377 case CXCursor_ObjCBoxable:
5378 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005379 case CXCursor_FlagEnum:
5380 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005381 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005382 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005384 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005385 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005386 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005387 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005388 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005389 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005390 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005391 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005392 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005393 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005394 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005395 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005396 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005397 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005398 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005399 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005400 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005401 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005402 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005403 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005404 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005405 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005406 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005407 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005408 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005409 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005410 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005411 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005412 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005413 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005414 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005415 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005416 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005417 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005418 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005419 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005420 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005421 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005422 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005424 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005425 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005426 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005427 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005428 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005429 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005430 return cxstring::createRef("OMPParallelDirective");
5431 case CXCursor_OMPSimdDirective:
5432 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005433 case CXCursor_OMPForDirective:
5434 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005435 case CXCursor_OMPForSimdDirective:
5436 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005437 case CXCursor_OMPSectionsDirective:
5438 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005439 case CXCursor_OMPSectionDirective:
5440 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005441 case CXCursor_OMPSingleDirective:
5442 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005443 case CXCursor_OMPMasterDirective:
5444 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005445 case CXCursor_OMPCriticalDirective:
5446 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005447 case CXCursor_OMPParallelForDirective:
5448 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005449 case CXCursor_OMPParallelForSimdDirective:
5450 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005451 case CXCursor_OMPParallelSectionsDirective:
5452 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005453 case CXCursor_OMPTaskDirective:
5454 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005455 case CXCursor_OMPTaskyieldDirective:
5456 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005457 case CXCursor_OMPBarrierDirective:
5458 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005459 case CXCursor_OMPTaskwaitDirective:
5460 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005461 case CXCursor_OMPTaskgroupDirective:
5462 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005463 case CXCursor_OMPFlushDirective:
5464 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005465 case CXCursor_OMPOrderedDirective:
5466 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005467 case CXCursor_OMPAtomicDirective:
5468 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005469 case CXCursor_OMPTargetDirective:
5470 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005471 case CXCursor_OMPTargetDataDirective:
5472 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005473 case CXCursor_OMPTargetEnterDataDirective:
5474 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005475 case CXCursor_OMPTargetExitDataDirective:
5476 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005477 case CXCursor_OMPTargetParallelDirective:
5478 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005479 case CXCursor_OMPTargetParallelForDirective:
5480 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005481 case CXCursor_OMPTargetUpdateDirective:
5482 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005483 case CXCursor_OMPTeamsDirective:
5484 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005485 case CXCursor_OMPCancellationPointDirective:
5486 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005487 case CXCursor_OMPCancelDirective:
5488 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005489 case CXCursor_OMPTaskLoopDirective:
5490 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005491 case CXCursor_OMPTaskLoopSimdDirective:
5492 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005493 case CXCursor_OMPMasterTaskLoopDirective:
5494 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005495 case CXCursor_OMPMasterTaskLoopSimdDirective:
5496 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005497 case CXCursor_OMPParallelMasterTaskLoopDirective:
5498 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Alexey Bataev14a388f2019-10-25 10:27:13 -04005499 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5500 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005501 case CXCursor_OMPDistributeDirective:
5502 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005503 case CXCursor_OMPDistributeParallelForDirective:
5504 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005505 case CXCursor_OMPDistributeParallelForSimdDirective:
5506 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005507 case CXCursor_OMPDistributeSimdDirective:
5508 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005509 case CXCursor_OMPTargetParallelForSimdDirective:
5510 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005511 case CXCursor_OMPTargetSimdDirective:
5512 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005513 case CXCursor_OMPTeamsDistributeDirective:
5514 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005515 case CXCursor_OMPTeamsDistributeSimdDirective:
5516 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005517 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5518 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005519 case CXCursor_OMPTeamsDistributeParallelForDirective:
5520 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005521 case CXCursor_OMPTargetTeamsDirective:
5522 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005523 case CXCursor_OMPTargetTeamsDistributeDirective:
5524 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005525 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5526 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005527 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5528 return cxstring::createRef(
5529 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005530 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5531 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005532 case CXCursor_OverloadCandidate:
5533 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005534 case CXCursor_TypeAliasTemplateDecl:
5535 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005536 case CXCursor_StaticAssert:
5537 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005538 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005539 return cxstring::createRef("FriendDecl");
5540 case CXCursor_ConvergentAttr:
5541 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005542 case CXCursor_WarnUnusedAttr:
5543 return cxstring::createRef("attribute(warn_unused)");
5544 case CXCursor_WarnUnusedResultAttr:
5545 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005546 case CXCursor_AlignedAttr:
5547 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005548 }
5549
5550 llvm_unreachable("Unhandled CXCursorKind");
5551}
5552
5553struct GetCursorData {
5554 SourceLocation TokenBeginLoc;
5555 bool PointsAtMacroArgExpansion;
5556 bool VisitedObjCPropertyImplDecl;
5557 SourceLocation VisitedDeclaratorDeclStartLoc;
5558 CXCursor &BestCursor;
5559
5560 GetCursorData(SourceManager &SM,
5561 SourceLocation tokenBegin, CXCursor &outputCursor)
5562 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5563 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5564 VisitedObjCPropertyImplDecl = false;
5565 }
5566};
5567
5568static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5569 CXCursor parent,
5570 CXClientData client_data) {
5571 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5572 CXCursor *BestCursor = &Data->BestCursor;
5573
5574 // If we point inside a macro argument we should provide info of what the
5575 // token is so use the actual cursor, don't replace it with a macro expansion
5576 // cursor.
5577 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5578 return CXChildVisit_Recurse;
5579
5580 if (clang_isDeclaration(cursor.kind)) {
5581 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005582 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005583 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5584 if (MD->isImplicit())
5585 return CXChildVisit_Break;
5586
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005587 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005588 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5589 // Check that when we have multiple @class references in the same line,
5590 // that later ones do not override the previous ones.
5591 // If we have:
5592 // @class Foo, Bar;
5593 // source ranges for both start at '@', so 'Bar' will end up overriding
5594 // 'Foo' even though the cursor location was at 'Foo'.
5595 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5596 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005597 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005598 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5599 if (PrevID != ID &&
5600 !PrevID->isThisDeclarationADefinition() &&
5601 !ID->isThisDeclarationADefinition())
5602 return CXChildVisit_Break;
5603 }
5604
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005605 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005606 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5607 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5608 // Check that when we have multiple declarators in the same line,
5609 // that later ones do not override the previous ones.
5610 // If we have:
5611 // int Foo, Bar;
5612 // source ranges for both start at 'int', so 'Bar' will end up overriding
5613 // 'Foo' even though the cursor location was at 'Foo'.
5614 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5615 return CXChildVisit_Break;
5616 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5617
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005618 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005619 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5620 (void)PropImp;
5621 // Check that when we have multiple @synthesize in the same line,
5622 // that later ones do not override the previous ones.
5623 // If we have:
5624 // @synthesize Foo, Bar;
5625 // source ranges for both start at '@', so 'Bar' will end up overriding
5626 // 'Foo' even though the cursor location was at 'Foo'.
5627 if (Data->VisitedObjCPropertyImplDecl)
5628 return CXChildVisit_Break;
5629 Data->VisitedObjCPropertyImplDecl = true;
5630 }
5631 }
5632
5633 if (clang_isExpression(cursor.kind) &&
5634 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005635 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005636 // Avoid having the cursor of an expression replace the declaration cursor
5637 // when the expression source range overlaps the declaration range.
5638 // This can happen for C++ constructor expressions whose range generally
5639 // include the variable declaration, e.g.:
5640 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5641 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5642 D->getLocation() == Data->TokenBeginLoc)
5643 return CXChildVisit_Break;
5644 }
5645 }
5646
5647 // If our current best cursor is the construction of a temporary object,
5648 // don't replace that cursor with a type reference, because we want
5649 // clang_getCursor() to point at the constructor.
5650 if (clang_isExpression(BestCursor->kind) &&
5651 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5652 cursor.kind == CXCursor_TypeRef) {
5653 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5654 // as having the actual point on the type reference.
5655 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5656 return CXChildVisit_Recurse;
5657 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005658
5659 // If we already have an Objective-C superclass reference, don't
5660 // update it further.
5661 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5662 return CXChildVisit_Break;
5663
Guy Benyei11169dd2012-12-18 14:30:41 +00005664 *BestCursor = cursor;
5665 return CXChildVisit_Recurse;
5666}
5667
5668CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005669 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005670 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005671 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005672 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005673
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005674 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005675 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5676
5677 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5678 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5679
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005680 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005681 CXFile SearchFile;
5682 unsigned SearchLine, SearchColumn;
5683 CXFile ResultFile;
5684 unsigned ResultLine, ResultColumn;
5685 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5686 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5687 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005688
5689 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5690 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005691 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005692 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005693 SearchFileName = clang_getFileName(SearchFile);
5694 ResultFileName = clang_getFileName(ResultFile);
5695 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5696 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005697 *Log << llvm::format("(%s:%d:%d) = %s",
5698 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5699 clang_getCString(KindSpelling))
5700 << llvm::format("(%s:%d:%d):%s%s",
5701 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5702 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005703 clang_disposeString(SearchFileName);
5704 clang_disposeString(ResultFileName);
5705 clang_disposeString(KindSpelling);
5706 clang_disposeString(USR);
5707
5708 CXCursor Definition = clang_getCursorDefinition(Result);
5709 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5710 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5711 CXString DefinitionKindSpelling
5712 = clang_getCursorKindSpelling(Definition.kind);
5713 CXFile DefinitionFile;
5714 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005715 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005716 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005717 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005718 *Log << llvm::format(" -> %s(%s:%d:%d)",
5719 clang_getCString(DefinitionKindSpelling),
5720 clang_getCString(DefinitionFileName),
5721 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005722 clang_disposeString(DefinitionFileName);
5723 clang_disposeString(DefinitionKindSpelling);
5724 }
5725 }
5726
5727 return Result;
5728}
5729
5730CXCursor clang_getNullCursor(void) {
5731 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5732}
5733
5734unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005735 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5736 // can't set consistently. For example, when visiting a DeclStmt we will set
5737 // it but we don't set it on the result of clang_getCursorDefinition for
5738 // a reference of the same declaration.
5739 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5740 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5741 // to provide that kind of info.
5742 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005743 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005744 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005745 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005746
Guy Benyei11169dd2012-12-18 14:30:41 +00005747 return X == Y;
5748}
5749
5750unsigned clang_hashCursor(CXCursor C) {
5751 unsigned Index = 0;
5752 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5753 Index = 1;
5754
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005755 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005756 std::make_pair(C.kind, C.data[Index]));
5757}
5758
5759unsigned clang_isInvalid(enum CXCursorKind K) {
5760 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5761}
5762
5763unsigned clang_isDeclaration(enum CXCursorKind K) {
5764 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005765 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5766}
5767
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005768unsigned clang_isInvalidDeclaration(CXCursor C) {
5769 if (clang_isDeclaration(C.kind)) {
5770 if (const Decl *D = getCursorDecl(C))
5771 return D->isInvalidDecl();
5772 }
5773
5774 return 0;
5775}
5776
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005777unsigned clang_isReference(enum CXCursorKind K) {
5778 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5779}
Guy Benyei11169dd2012-12-18 14:30:41 +00005780
5781unsigned clang_isExpression(enum CXCursorKind K) {
5782 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5783}
5784
5785unsigned clang_isStatement(enum CXCursorKind K) {
5786 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5787}
5788
5789unsigned clang_isAttribute(enum CXCursorKind K) {
5790 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5791}
5792
5793unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5794 return K == CXCursor_TranslationUnit;
5795}
5796
5797unsigned clang_isPreprocessing(enum CXCursorKind K) {
5798 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5799}
5800
5801unsigned clang_isUnexposed(enum CXCursorKind K) {
5802 switch (K) {
5803 case CXCursor_UnexposedDecl:
5804 case CXCursor_UnexposedExpr:
5805 case CXCursor_UnexposedStmt:
5806 case CXCursor_UnexposedAttr:
5807 return true;
5808 default:
5809 return false;
5810 }
5811}
5812
5813CXCursorKind clang_getCursorKind(CXCursor C) {
5814 return C.kind;
5815}
5816
5817CXSourceLocation clang_getCursorLocation(CXCursor C) {
5818 if (clang_isReference(C.kind)) {
5819 switch (C.kind) {
5820 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005821 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005822 = getCursorObjCSuperClassRef(C);
5823 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5824 }
5825
5826 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005827 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005828 = getCursorObjCProtocolRef(C);
5829 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5830 }
5831
5832 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005833 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005834 = getCursorObjCClassRef(C);
5835 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5836 }
5837
5838 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005839 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005840 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5841 }
5842
5843 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005844 std::pair<const TemplateDecl *, SourceLocation> P =
5845 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005846 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5847 }
5848
5849 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005850 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005851 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5852 }
5853
5854 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005855 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005856 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5857 }
5858
5859 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005860 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005861 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5862 }
5863
5864 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005865 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005866 if (!BaseSpec)
5867 return clang_getNullLocation();
5868
5869 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5870 return cxloc::translateSourceLocation(getCursorContext(C),
5871 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005872
Guy Benyei11169dd2012-12-18 14:30:41 +00005873 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005874 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005875 }
5876
5877 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005878 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005879 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5880 }
5881
5882 case CXCursor_OverloadedDeclRef:
5883 return cxloc::translateSourceLocation(getCursorContext(C),
5884 getCursorOverloadedDeclRef(C).second);
5885
5886 default:
5887 // FIXME: Need a way to enumerate all non-reference cases.
5888 llvm_unreachable("Missed a reference kind");
5889 }
5890 }
5891
5892 if (clang_isExpression(C.kind))
5893 return cxloc::translateSourceLocation(getCursorContext(C),
5894 getLocationFromExpr(getCursorExpr(C)));
5895
5896 if (clang_isStatement(C.kind))
5897 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005898 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005899
5900 if (C.kind == CXCursor_PreprocessingDirective) {
5901 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5902 return cxloc::translateSourceLocation(getCursorContext(C), L);
5903 }
5904
5905 if (C.kind == CXCursor_MacroExpansion) {
5906 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005907 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005908 return cxloc::translateSourceLocation(getCursorContext(C), L);
5909 }
5910
5911 if (C.kind == CXCursor_MacroDefinition) {
5912 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5913 return cxloc::translateSourceLocation(getCursorContext(C), L);
5914 }
5915
5916 if (C.kind == CXCursor_InclusionDirective) {
5917 SourceLocation L
5918 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5919 return cxloc::translateSourceLocation(getCursorContext(C), L);
5920 }
5921
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005922 if (clang_isAttribute(C.kind)) {
5923 SourceLocation L
5924 = cxcursor::getCursorAttr(C)->getLocation();
5925 return cxloc::translateSourceLocation(getCursorContext(C), L);
5926 }
5927
Guy Benyei11169dd2012-12-18 14:30:41 +00005928 if (!clang_isDeclaration(C.kind))
5929 return clang_getNullLocation();
5930
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005931 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005932 if (!D)
5933 return clang_getNullLocation();
5934
5935 SourceLocation Loc = D->getLocation();
5936 // FIXME: Multiple variables declared in a single declaration
5937 // currently lack the information needed to correctly determine their
5938 // ranges when accounting for the type-specifier. We use context
5939 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5940 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005941 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005942 if (!cxcursor::isFirstInDeclGroup(C))
5943 Loc = VD->getLocation();
5944 }
5945
5946 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005947 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005948 Loc = MD->getSelectorStartLoc();
5949
5950 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5951}
5952
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005953} // end extern "C"
5954
Guy Benyei11169dd2012-12-18 14:30:41 +00005955CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5956 assert(TU);
5957
5958 // Guard against an invalid SourceLocation, or we may assert in one
5959 // of the following calls.
5960 if (SLoc.isInvalid())
5961 return clang_getNullCursor();
5962
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005963 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005964
5965 // Translate the given source location to make it point at the beginning of
5966 // the token under the cursor.
5967 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5968 CXXUnit->getASTContext().getLangOpts());
5969
5970 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5971 if (SLoc.isValid()) {
5972 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5973 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5974 /*VisitPreprocessorLast=*/true,
5975 /*VisitIncludedEntities=*/false,
5976 SourceLocation(SLoc));
5977 CursorVis.visitFileRegion();
5978 }
5979
5980 return Result;
5981}
5982
5983static SourceRange getRawCursorExtent(CXCursor C) {
5984 if (clang_isReference(C.kind)) {
5985 switch (C.kind) {
5986 case CXCursor_ObjCSuperClassRef:
5987 return getCursorObjCSuperClassRef(C).second;
5988
5989 case CXCursor_ObjCProtocolRef:
5990 return getCursorObjCProtocolRef(C).second;
5991
5992 case CXCursor_ObjCClassRef:
5993 return getCursorObjCClassRef(C).second;
5994
5995 case CXCursor_TypeRef:
5996 return getCursorTypeRef(C).second;
5997
5998 case CXCursor_TemplateRef:
5999 return getCursorTemplateRef(C).second;
6000
6001 case CXCursor_NamespaceRef:
6002 return getCursorNamespaceRef(C).second;
6003
6004 case CXCursor_MemberRef:
6005 return getCursorMemberRef(C).second;
6006
6007 case CXCursor_CXXBaseSpecifier:
6008 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6009
6010 case CXCursor_LabelRef:
6011 return getCursorLabelRef(C).second;
6012
6013 case CXCursor_OverloadedDeclRef:
6014 return getCursorOverloadedDeclRef(C).second;
6015
6016 case CXCursor_VariableRef:
6017 return getCursorVariableRef(C).second;
6018
6019 default:
6020 // FIXME: Need a way to enumerate all non-reference cases.
6021 llvm_unreachable("Missed a reference kind");
6022 }
6023 }
6024
6025 if (clang_isExpression(C.kind))
6026 return getCursorExpr(C)->getSourceRange();
6027
6028 if (clang_isStatement(C.kind))
6029 return getCursorStmt(C)->getSourceRange();
6030
6031 if (clang_isAttribute(C.kind))
6032 return getCursorAttr(C)->getRange();
6033
6034 if (C.kind == CXCursor_PreprocessingDirective)
6035 return cxcursor::getCursorPreprocessingDirective(C);
6036
6037 if (C.kind == CXCursor_MacroExpansion) {
6038 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006039 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006040 return TU->mapRangeFromPreamble(Range);
6041 }
6042
6043 if (C.kind == CXCursor_MacroDefinition) {
6044 ASTUnit *TU = getCursorASTUnit(C);
6045 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6046 return TU->mapRangeFromPreamble(Range);
6047 }
6048
6049 if (C.kind == CXCursor_InclusionDirective) {
6050 ASTUnit *TU = getCursorASTUnit(C);
6051 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6052 return TU->mapRangeFromPreamble(Range);
6053 }
6054
6055 if (C.kind == CXCursor_TranslationUnit) {
6056 ASTUnit *TU = getCursorASTUnit(C);
6057 FileID MainID = TU->getSourceManager().getMainFileID();
6058 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6059 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6060 return SourceRange(Start, End);
6061 }
6062
6063 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006064 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006065 if (!D)
6066 return SourceRange();
6067
6068 SourceRange R = D->getSourceRange();
6069 // FIXME: Multiple variables declared in a single declaration
6070 // currently lack the information needed to correctly determine their
6071 // ranges when accounting for the type-specifier. We use context
6072 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6073 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006074 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 if (!cxcursor::isFirstInDeclGroup(C))
6076 R.setBegin(VD->getLocation());
6077 }
6078 return R;
6079 }
6080 return SourceRange();
6081}
6082
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006083/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006084/// the decl-specifier-seq for declarations.
6085static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6086 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006087 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006088 if (!D)
6089 return SourceRange();
6090
6091 SourceRange R = D->getSourceRange();
6092
6093 // Adjust the start of the location for declarations preceded by
6094 // declaration specifiers.
6095 SourceLocation StartLoc;
6096 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6097 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006098 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006099 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006100 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006101 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006102 }
6103
6104 if (StartLoc.isValid() && R.getBegin().isValid() &&
6105 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6106 R.setBegin(StartLoc);
6107
6108 // FIXME: Multiple variables declared in a single declaration
6109 // currently lack the information needed to correctly determine their
6110 // ranges when accounting for the type-specifier. We use context
6111 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6112 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006113 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 if (!cxcursor::isFirstInDeclGroup(C))
6115 R.setBegin(VD->getLocation());
6116 }
6117
6118 return R;
6119 }
6120
6121 return getRawCursorExtent(C);
6122}
6123
Guy Benyei11169dd2012-12-18 14:30:41 +00006124CXSourceRange clang_getCursorExtent(CXCursor C) {
6125 SourceRange R = getRawCursorExtent(C);
6126 if (R.isInvalid())
6127 return clang_getNullRange();
6128
6129 return cxloc::translateSourceRange(getCursorContext(C), R);
6130}
6131
6132CXCursor clang_getCursorReferenced(CXCursor C) {
6133 if (clang_isInvalid(C.kind))
6134 return clang_getNullCursor();
6135
6136 CXTranslationUnit tu = getCursorTU(C);
6137 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006138 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006139 if (!D)
6140 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006141 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006142 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006143 if (const ObjCPropertyImplDecl *PropImpl =
6144 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6146 return MakeCXCursor(Property, tu);
6147
6148 return C;
6149 }
6150
6151 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006152 const Expr *E = getCursorExpr(C);
6153 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006154 if (D) {
6155 CXCursor declCursor = MakeCXCursor(D, tu);
6156 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6157 declCursor);
6158 return declCursor;
6159 }
6160
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006161 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006162 return MakeCursorOverloadedDeclRef(Ovl, tu);
6163
6164 return clang_getNullCursor();
6165 }
6166
6167 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006168 const Stmt *S = getCursorStmt(C);
6169 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006170 if (LabelDecl *label = Goto->getLabel())
6171 if (LabelStmt *labelS = label->getStmt())
6172 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6173
6174 return clang_getNullCursor();
6175 }
Richard Smith66a81862015-05-04 02:25:31 +00006176
Guy Benyei11169dd2012-12-18 14:30:41 +00006177 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006178 if (const MacroDefinitionRecord *Def =
6179 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006180 return MakeMacroDefinitionCursor(Def, tu);
6181 }
6182
6183 if (!clang_isReference(C.kind))
6184 return clang_getNullCursor();
6185
6186 switch (C.kind) {
6187 case CXCursor_ObjCSuperClassRef:
6188 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6189
6190 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006191 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6192 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006193 return MakeCXCursor(Def, tu);
6194
6195 return MakeCXCursor(Prot, tu);
6196 }
6197
6198 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006199 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6200 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006201 return MakeCXCursor(Def, tu);
6202
6203 return MakeCXCursor(Class, tu);
6204 }
6205
6206 case CXCursor_TypeRef:
6207 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6208
6209 case CXCursor_TemplateRef:
6210 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6211
6212 case CXCursor_NamespaceRef:
6213 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6214
6215 case CXCursor_MemberRef:
6216 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6217
6218 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006219 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006220 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6221 tu ));
6222 }
6223
6224 case CXCursor_LabelRef:
6225 // FIXME: We end up faking the "parent" declaration here because we
6226 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006227 return MakeCXCursor(getCursorLabelRef(C).first,
6228 cxtu::getASTUnit(tu)->getASTContext()
6229 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006230 tu);
6231
6232 case CXCursor_OverloadedDeclRef:
6233 return C;
6234
6235 case CXCursor_VariableRef:
6236 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6237
6238 default:
6239 // We would prefer to enumerate all non-reference cursor kinds here.
6240 llvm_unreachable("Unhandled reference cursor kind");
6241 }
6242}
6243
6244CXCursor clang_getCursorDefinition(CXCursor C) {
6245 if (clang_isInvalid(C.kind))
6246 return clang_getNullCursor();
6247
6248 CXTranslationUnit TU = getCursorTU(C);
6249
6250 bool WasReference = false;
6251 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6252 C = clang_getCursorReferenced(C);
6253 WasReference = true;
6254 }
6255
6256 if (C.kind == CXCursor_MacroExpansion)
6257 return clang_getCursorReferenced(C);
6258
6259 if (!clang_isDeclaration(C.kind))
6260 return clang_getNullCursor();
6261
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006262 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006263 if (!D)
6264 return clang_getNullCursor();
6265
6266 switch (D->getKind()) {
6267 // Declaration kinds that don't really separate the notions of
6268 // declaration and definition.
6269 case Decl::Namespace:
6270 case Decl::Typedef:
6271 case Decl::TypeAlias:
6272 case Decl::TypeAliasTemplate:
6273 case Decl::TemplateTypeParm:
6274 case Decl::EnumConstant:
6275 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006276 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006277 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006278 case Decl::IndirectField:
6279 case Decl::ObjCIvar:
6280 case Decl::ObjCAtDefsField:
6281 case Decl::ImplicitParam:
6282 case Decl::ParmVar:
6283 case Decl::NonTypeTemplateParm:
6284 case Decl::TemplateTemplateParm:
6285 case Decl::ObjCCategoryImpl:
6286 case Decl::ObjCImplementation:
6287 case Decl::AccessSpec:
6288 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006289 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 case Decl::ObjCPropertyImpl:
6291 case Decl::FileScopeAsm:
6292 case Decl::StaticAssert:
6293 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006294 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006295 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006296 case Decl::Label: // FIXME: Is this right??
6297 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006298 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006299 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006300 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006301 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006302 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006303 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006304 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006305 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006306 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006307 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006308 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006309 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006310 case Decl::Concept:
Guy Benyei11169dd2012-12-18 14:30:41 +00006311 return C;
6312
6313 // Declaration kinds that don't make any sense here, but are
6314 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006315 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006316 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006317 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006318 break;
6319
6320 // Declaration kinds for which the definition is not resolvable.
6321 case Decl::UnresolvedUsingTypename:
6322 case Decl::UnresolvedUsingValue:
6323 break;
6324
6325 case Decl::UsingDirective:
6326 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6327 TU);
6328
6329 case Decl::NamespaceAlias:
6330 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6331
6332 case Decl::Enum:
6333 case Decl::Record:
6334 case Decl::CXXRecord:
6335 case Decl::ClassTemplateSpecialization:
6336 case Decl::ClassTemplatePartialSpecialization:
6337 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6338 return MakeCXCursor(Def, TU);
6339 return clang_getNullCursor();
6340
6341 case Decl::Function:
6342 case Decl::CXXMethod:
6343 case Decl::CXXConstructor:
6344 case Decl::CXXDestructor:
6345 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006346 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006348 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 return clang_getNullCursor();
6350 }
6351
Larisse Voufo39a1e502013-08-06 01:03:05 +00006352 case Decl::Var:
6353 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006354 case Decl::VarTemplatePartialSpecialization:
6355 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006357 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006358 return MakeCXCursor(Def, TU);
6359 return clang_getNullCursor();
6360 }
6361
6362 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006363 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006364 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6365 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6366 return clang_getNullCursor();
6367 }
6368
6369 case Decl::ClassTemplate: {
6370 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6371 ->getDefinition())
6372 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6373 TU);
6374 return clang_getNullCursor();
6375 }
6376
Larisse Voufo39a1e502013-08-06 01:03:05 +00006377 case Decl::VarTemplate: {
6378 if (VarDecl *Def =
6379 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6380 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6381 return clang_getNullCursor();
6382 }
6383
Guy Benyei11169dd2012-12-18 14:30:41 +00006384 case Decl::Using:
6385 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6386 D->getLocation(), TU);
6387
6388 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006389 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 return clang_getCursorDefinition(
6391 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6392 TU));
6393
6394 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006395 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006396 if (Method->isThisDeclarationADefinition())
6397 return C;
6398
6399 // Dig out the method definition in the associated
6400 // @implementation, if we have it.
6401 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006402 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6404 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6405 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6406 Method->isInstanceMethod()))
6407 if (Def->isThisDeclarationADefinition())
6408 return MakeCXCursor(Def, TU);
6409
6410 return clang_getNullCursor();
6411 }
6412
6413 case Decl::ObjCCategory:
6414 if (ObjCCategoryImplDecl *Impl
6415 = cast<ObjCCategoryDecl>(D)->getImplementation())
6416 return MakeCXCursor(Impl, TU);
6417 return clang_getNullCursor();
6418
6419 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006420 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006421 return MakeCXCursor(Def, TU);
6422 return clang_getNullCursor();
6423
6424 case Decl::ObjCInterface: {
6425 // There are two notions of a "definition" for an Objective-C
6426 // class: the interface and its implementation. When we resolved a
6427 // reference to an Objective-C class, produce the @interface as
6428 // the definition; when we were provided with the interface,
6429 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006430 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006431 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006432 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006433 return MakeCXCursor(Def, TU);
6434 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6435 return MakeCXCursor(Impl, TU);
6436 return clang_getNullCursor();
6437 }
6438
6439 case Decl::ObjCProperty:
6440 // FIXME: We don't really know where to find the
6441 // ObjCPropertyImplDecls that implement this property.
6442 return clang_getNullCursor();
6443
6444 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006445 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006446 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006447 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006448 return MakeCXCursor(Def, TU);
6449
6450 return clang_getNullCursor();
6451
6452 case Decl::Friend:
6453 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6454 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6455 return clang_getNullCursor();
6456
6457 case Decl::FriendTemplate:
6458 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6459 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6460 return clang_getNullCursor();
6461 }
6462
6463 return clang_getNullCursor();
6464}
6465
6466unsigned clang_isCursorDefinition(CXCursor C) {
6467 if (!clang_isDeclaration(C.kind))
6468 return 0;
6469
6470 return clang_getCursorDefinition(C) == C;
6471}
6472
6473CXCursor clang_getCanonicalCursor(CXCursor C) {
6474 if (!clang_isDeclaration(C.kind))
6475 return C;
6476
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006477 if (const Decl *D = getCursorDecl(C)) {
6478 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006479 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6480 return MakeCXCursor(CatD, getCursorTU(C));
6481
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006482 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6483 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 return MakeCXCursor(IFD, getCursorTU(C));
6485
6486 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6487 }
6488
6489 return C;
6490}
6491
6492int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6493 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6494}
6495
6496unsigned clang_getNumOverloadedDecls(CXCursor C) {
6497 if (C.kind != CXCursor_OverloadedDeclRef)
6498 return 0;
6499
6500 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006501 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 return E->getNumDecls();
6503
6504 if (OverloadedTemplateStorage *S
6505 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6506 return S->size();
6507
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006508 const Decl *D = Storage.get<const Decl *>();
6509 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006510 return Using->shadow_size();
6511
6512 return 0;
6513}
6514
6515CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6516 if (cursor.kind != CXCursor_OverloadedDeclRef)
6517 return clang_getNullCursor();
6518
6519 if (index >= clang_getNumOverloadedDecls(cursor))
6520 return clang_getNullCursor();
6521
6522 CXTranslationUnit TU = getCursorTU(cursor);
6523 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006524 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006525 return MakeCXCursor(E->decls_begin()[index], TU);
6526
6527 if (OverloadedTemplateStorage *S
6528 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6529 return MakeCXCursor(S->begin()[index], TU);
6530
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006531 const Decl *D = Storage.get<const Decl *>();
6532 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006533 // FIXME: This is, unfortunately, linear time.
6534 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6535 std::advance(Pos, index);
6536 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6537 }
6538
6539 return clang_getNullCursor();
6540}
6541
6542void clang_getDefinitionSpellingAndExtent(CXCursor C,
6543 const char **startBuf,
6544 const char **endBuf,
6545 unsigned *startLine,
6546 unsigned *startColumn,
6547 unsigned *endLine,
6548 unsigned *endColumn) {
6549 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006550 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006551 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6552
6553 SourceManager &SM = FD->getASTContext().getSourceManager();
6554 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6555 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6556 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6557 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6558 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6559 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6560}
6561
6562
6563CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6564 unsigned PieceIndex) {
6565 RefNamePieces Pieces;
6566
6567 switch (C.kind) {
6568 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006569 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006570 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6571 E->getQualifierLoc().getSourceRange());
6572 break;
6573
6574 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006575 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6576 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6577 Pieces =
6578 buildPieces(NameFlags, false, E->getNameInfo(),
6579 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6580 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006581 break;
6582
6583 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006584 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006585 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006586 const Expr *Callee = OCE->getCallee();
6587 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006588 Callee = ICE->getSubExpr();
6589
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006590 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006591 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6592 DRE->getQualifierLoc().getSourceRange());
6593 }
6594 break;
6595
6596 default:
6597 break;
6598 }
6599
6600 if (Pieces.empty()) {
6601 if (PieceIndex == 0)
6602 return clang_getCursorExtent(C);
6603 } else if (PieceIndex < Pieces.size()) {
6604 SourceRange R = Pieces[PieceIndex];
6605 if (R.isValid())
6606 return cxloc::translateSourceRange(getCursorContext(C), R);
6607 }
6608
6609 return clang_getNullRange();
6610}
6611
6612void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006613 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6614 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006615}
6616
6617void clang_executeOnThread(void (*fn)(void*), void *user_data,
6618 unsigned stack_size) {
Sam McCalla9c3c172019-10-23 15:34:48 +02006619 llvm::llvm_execute_on_thread(
6620 fn, user_data,
6621 stack_size == 0 ? llvm::None : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006622}
6623
Guy Benyei11169dd2012-12-18 14:30:41 +00006624//===----------------------------------------------------------------------===//
6625// Token-based Operations.
6626//===----------------------------------------------------------------------===//
6627
6628/* CXToken layout:
6629 * int_data[0]: a CXTokenKind
6630 * int_data[1]: starting token location
6631 * int_data[2]: token length
6632 * int_data[3]: reserved
6633 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6634 * otherwise unused.
6635 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006636CXTokenKind clang_getTokenKind(CXToken CXTok) {
6637 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6638}
6639
6640CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6641 switch (clang_getTokenKind(CXTok)) {
6642 case CXToken_Identifier:
6643 case CXToken_Keyword:
6644 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006645 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006646 ->getNameStart());
6647
6648 case CXToken_Literal: {
6649 // We have stashed the starting pointer in the ptr_data field. Use it.
6650 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006651 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006652 }
6653
6654 case CXToken_Punctuation:
6655 case CXToken_Comment:
6656 break;
6657 }
6658
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006659 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006660 LOG_BAD_TU(TU);
6661 return cxstring::createEmpty();
6662 }
6663
Guy Benyei11169dd2012-12-18 14:30:41 +00006664 // We have to find the starting buffer pointer the hard way, by
6665 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006666 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006667 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006668 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006669
6670 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6671 std::pair<FileID, unsigned> LocInfo
6672 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6673 bool Invalid = false;
6674 StringRef Buffer
6675 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6676 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006677 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006678
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006679 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006680}
6681
6682CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006683 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006684 LOG_BAD_TU(TU);
6685 return clang_getNullLocation();
6686 }
6687
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006688 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006689 if (!CXXUnit)
6690 return clang_getNullLocation();
6691
6692 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6693 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6694}
6695
6696CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006697 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006698 LOG_BAD_TU(TU);
6699 return clang_getNullRange();
6700 }
6701
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006702 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 if (!CXXUnit)
6704 return clang_getNullRange();
6705
6706 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6707 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6708}
6709
6710static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6711 SmallVectorImpl<CXToken> &CXTokens) {
6712 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6713 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006714 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006715 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006716 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006717
6718 // Cannot tokenize across files.
6719 if (BeginLocInfo.first != EndLocInfo.first)
6720 return;
6721
6722 // Create a lexer
6723 bool Invalid = false;
6724 StringRef Buffer
6725 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6726 if (Invalid)
6727 return;
6728
6729 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6730 CXXUnit->getASTContext().getLangOpts(),
6731 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6732 Lex.SetCommentRetentionState(true);
6733
6734 // Lex tokens until we hit the end of the range.
6735 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6736 Token Tok;
6737 bool previousWasAt = false;
6738 do {
6739 // Lex the next token
6740 Lex.LexFromRawLexer(Tok);
6741 if (Tok.is(tok::eof))
6742 break;
6743
6744 // Initialize the CXToken.
6745 CXToken CXTok;
6746
6747 // - Common fields
6748 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6749 CXTok.int_data[2] = Tok.getLength();
6750 CXTok.int_data[3] = 0;
6751
6752 // - Kind-specific fields
6753 if (Tok.isLiteral()) {
6754 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006755 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006756 } else if (Tok.is(tok::raw_identifier)) {
6757 // Lookup the identifier to determine whether we have a keyword.
6758 IdentifierInfo *II
6759 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6760
6761 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6762 CXTok.int_data[0] = CXToken_Keyword;
6763 }
6764 else {
6765 CXTok.int_data[0] = Tok.is(tok::identifier)
6766 ? CXToken_Identifier
6767 : CXToken_Keyword;
6768 }
6769 CXTok.ptr_data = II;
6770 } else if (Tok.is(tok::comment)) {
6771 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006772 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 } else {
6774 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006775 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006776 }
6777 CXTokens.push_back(CXTok);
6778 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006779 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006780}
6781
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006782CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6783 LOG_FUNC_SECTION {
6784 *Log << TU << ' ' << Location;
6785 }
6786
6787 if (isNotUsableTU(TU)) {
6788 LOG_BAD_TU(TU);
6789 return NULL;
6790 }
6791
6792 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6793 if (!CXXUnit)
6794 return NULL;
6795
6796 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6797 if (Begin.isInvalid())
6798 return NULL;
6799 SourceManager &SM = CXXUnit->getSourceManager();
6800 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6801 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6802
6803 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6804
6805 SmallVector<CXToken, 32> CXTokens;
6806 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6807
6808 if (CXTokens.empty())
6809 return NULL;
6810
6811 CXTokens.resize(1);
6812 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6813
6814 memmove(Token, CXTokens.data(), sizeof(CXToken));
6815 return Token;
6816}
6817
Guy Benyei11169dd2012-12-18 14:30:41 +00006818void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6819 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006820 LOG_FUNC_SECTION {
6821 *Log << TU << ' ' << Range;
6822 }
6823
Guy Benyei11169dd2012-12-18 14:30:41 +00006824 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006825 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006826 if (NumTokens)
6827 *NumTokens = 0;
6828
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006829 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006830 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006831 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006832 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006833
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006834 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006835 if (!CXXUnit || !Tokens || !NumTokens)
6836 return;
6837
6838 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6839
6840 SourceRange R = cxloc::translateCXSourceRange(Range);
6841 if (R.isInvalid())
6842 return;
6843
6844 SmallVector<CXToken, 32> CXTokens;
6845 getTokens(CXXUnit, R, CXTokens);
6846
6847 if (CXTokens.empty())
6848 return;
6849
Serge Pavlov52525732018-02-21 02:02:39 +00006850 *Tokens = static_cast<CXToken *>(
6851 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006852 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6853 *NumTokens = CXTokens.size();
6854}
6855
6856void clang_disposeTokens(CXTranslationUnit TU,
6857 CXToken *Tokens, unsigned NumTokens) {
6858 free(Tokens);
6859}
6860
Guy Benyei11169dd2012-12-18 14:30:41 +00006861//===----------------------------------------------------------------------===//
6862// Token annotation APIs.
6863//===----------------------------------------------------------------------===//
6864
Guy Benyei11169dd2012-12-18 14:30:41 +00006865static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6866 CXCursor parent,
6867 CXClientData client_data);
6868static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6869 CXClientData client_data);
6870
6871namespace {
6872class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006873 CXToken *Tokens;
6874 CXCursor *Cursors;
6875 unsigned NumTokens;
6876 unsigned TokIdx;
6877 unsigned PreprocessingTokIdx;
6878 CursorVisitor AnnotateVis;
6879 SourceManager &SrcMgr;
6880 bool HasContextSensitiveKeywords;
6881
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006882 struct PostChildrenAction {
6883 CXCursor cursor;
6884 enum Action { Invalid, Ignore, Postpone } action;
6885 };
6886 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6887
Guy Benyei11169dd2012-12-18 14:30:41 +00006888 struct PostChildrenInfo {
6889 CXCursor Cursor;
6890 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006891 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006892 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006893 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006894 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006895 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006896
6897 CXToken &getTok(unsigned Idx) {
6898 assert(Idx < NumTokens);
6899 return Tokens[Idx];
6900 }
6901 const CXToken &getTok(unsigned Idx) const {
6902 assert(Idx < NumTokens);
6903 return Tokens[Idx];
6904 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006905 bool MoreTokens() const { return TokIdx < NumTokens; }
6906 unsigned NextToken() const { return TokIdx; }
6907 void AdvanceToken() { ++TokIdx; }
6908 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006909 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 }
6911 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006912 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006913 }
6914 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006915 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 }
6917
6918 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006919 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006920 SourceRange);
6921
6922public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006923 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006924 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006925 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006927 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006928 AnnotateTokensVisitor, this,
6929 /*VisitPreprocessorLast=*/true,
6930 /*VisitIncludedEntities=*/false,
6931 RegionOfInterest,
6932 /*VisitDeclsOnly=*/false,
6933 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006934 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006935 HasContextSensitiveKeywords(false) { }
6936
6937 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6938 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006939 bool IsIgnoredChildCursor(CXCursor cursor) const;
6940 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6941
Guy Benyei11169dd2012-12-18 14:30:41 +00006942 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006943 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6944 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6945
Guy Benyei11169dd2012-12-18 14:30:41 +00006946 void AnnotateTokens();
6947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006948 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 /// context-sensitive keywords.
6950 bool hasContextSensitiveKeywords() const {
6951 return HasContextSensitiveKeywords;
6952 }
6953
6954 ~AnnotateTokensWorker() {
6955 assert(PostChildrenInfos.empty());
6956 }
6957};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006958}
Guy Benyei11169dd2012-12-18 14:30:41 +00006959
6960void AnnotateTokensWorker::AnnotateTokens() {
6961 // Walk the AST within the region of interest, annotating tokens
6962 // along the way.
6963 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006964}
Guy Benyei11169dd2012-12-18 14:30:41 +00006965
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006966bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6967 if (PostChildrenInfos.empty())
6968 return false;
6969
6970 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6971 if (ChildAction.cursor == cursor &&
6972 ChildAction.action == PostChildrenAction::Ignore) {
6973 return true;
6974 }
6975 }
6976
6977 return false;
6978}
6979
6980const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6981 if (!clang_isExpression(Cursor.kind))
6982 return nullptr;
6983
6984 const Expr *E = getCursorExpr(Cursor);
6985 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6986 const OverloadedOperatorKind Kind = OCE->getOperator();
6987 if (Kind == OO_Call || Kind == OO_Subscript)
6988 return OCE;
6989 }
6990
6991 return nullptr;
6992}
6993
6994AnnotateTokensWorker::PostChildrenActions
6995AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6996 PostChildrenActions actions;
6997
6998 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6999 // visited before the arguments to the operator call. For the Call and
7000 // Subscript operator the range of this DeclRefExpr includes the whole call
7001 // expression, so that all tokens in that range would be mapped to the
7002 // operator function, including the tokens of the arguments. To avoid that,
7003 // ensure to visit this DeclRefExpr as last node.
7004 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7005 const Expr *Callee = OCE->getCallee();
7006 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7007 const Expr *SubExpr = ICE->getSubExpr();
7008 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007009 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007010 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7011
7012 // Visit the DeclRefExpr as last.
7013 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7014 actions.push_back({cxChild, PostChildrenAction::Postpone});
7015
7016 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7017 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7018 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7019 actions.push_back({cxChild, PostChildrenAction::Ignore});
7020 }
7021 }
7022 }
7023
7024 return actions;
7025}
7026
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007027static inline void updateCursorAnnotation(CXCursor &Cursor,
7028 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007029 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007031 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007032}
7033
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007034/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007035//// between the cursor location and the source range is the same as
7036/// \arg compResult.
7037///
7038/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7039/// Pass RangeOverlap to annotate tokens inside a range.
7040void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7041 RangeComparisonResult compResult,
7042 SourceRange range) {
7043 while (MoreTokens()) {
7044 const unsigned I = NextToken();
7045 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007046 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7047 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007048
7049 SourceLocation TokLoc = GetTokenLoc(I);
7050 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007051 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007052 AdvanceToken();
7053 continue;
7054 }
7055 break;
7056 }
7057}
7058
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007059/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007060/// \returns true if it advanced beyond all macro tokens, false otherwise.
7061bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007062 CXCursor updateC,
7063 RangeComparisonResult compResult,
7064 SourceRange range) {
7065 assert(MoreTokens());
7066 assert(isFunctionMacroToken(NextToken()) &&
7067 "Should be called only for macro arg tokens");
7068
7069 // This works differently than annotateAndAdvanceTokens; because expanded
7070 // macro arguments can have arbitrary translation-unit source order, we do not
7071 // advance the token index one by one until a token fails the range test.
7072 // We only advance once past all of the macro arg tokens if all of them
7073 // pass the range test. If one of them fails we keep the token index pointing
7074 // at the start of the macro arg tokens so that the failing token will be
7075 // annotated by a subsequent annotation try.
7076
7077 bool atLeastOneCompFail = false;
7078
7079 unsigned I = NextToken();
7080 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7081 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7082 if (TokLoc.isFileID())
7083 continue; // not macro arg token, it's parens or comma.
7084 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7085 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7086 Cursors[I] = updateC;
7087 } else
7088 atLeastOneCompFail = true;
7089 }
7090
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007091 if (atLeastOneCompFail)
7092 return false;
7093
7094 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7095 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007096}
7097
7098enum CXChildVisitResult
7099AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007100 SourceRange cursorRange = getRawCursorExtent(cursor);
7101 if (cursorRange.isInvalid())
7102 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007103
7104 if (IsIgnoredChildCursor(cursor))
7105 return CXChildVisit_Continue;
7106
Guy Benyei11169dd2012-12-18 14:30:41 +00007107 if (!HasContextSensitiveKeywords) {
7108 // Objective-C properties can have context-sensitive keywords.
7109 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007110 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007111 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7112 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7113 }
7114 // Objective-C methods can have context-sensitive keywords.
7115 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7116 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007117 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007118 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7119 if (Method->getObjCDeclQualifier())
7120 HasContextSensitiveKeywords = true;
7121 else {
David Majnemer59f77922016-06-24 04:05:48 +00007122 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007123 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007124 HasContextSensitiveKeywords = true;
7125 break;
7126 }
7127 }
7128 }
7129 }
7130 }
7131 // C++ methods can have context-sensitive keywords.
7132 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007133 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007134 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7135 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7136 HasContextSensitiveKeywords = true;
7137 }
7138 }
7139 // C++ classes can have context-sensitive keywords.
7140 else if (cursor.kind == CXCursor_StructDecl ||
7141 cursor.kind == CXCursor_ClassDecl ||
7142 cursor.kind == CXCursor_ClassTemplate ||
7143 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007144 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007145 if (D->hasAttr<FinalAttr>())
7146 HasContextSensitiveKeywords = true;
7147 }
7148 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007149
7150 // Don't override a property annotation with its getter/setter method.
7151 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7152 parent.kind == CXCursor_ObjCPropertyDecl)
7153 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007154
7155 if (clang_isPreprocessing(cursor.kind)) {
7156 // Items in the preprocessing record are kept separate from items in
7157 // declarations, so we keep a separate token index.
7158 unsigned SavedTokIdx = TokIdx;
7159 TokIdx = PreprocessingTokIdx;
7160
7161 // Skip tokens up until we catch up to the beginning of the preprocessing
7162 // entry.
7163 while (MoreTokens()) {
7164 const unsigned I = NextToken();
7165 SourceLocation TokLoc = GetTokenLoc(I);
7166 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7167 case RangeBefore:
7168 AdvanceToken();
7169 continue;
7170 case RangeAfter:
7171 case RangeOverlap:
7172 break;
7173 }
7174 break;
7175 }
7176
7177 // Look at all of the tokens within this range.
7178 while (MoreTokens()) {
7179 const unsigned I = NextToken();
7180 SourceLocation TokLoc = GetTokenLoc(I);
7181 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7182 case RangeBefore:
7183 llvm_unreachable("Infeasible");
7184 case RangeAfter:
7185 break;
7186 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007187 // For macro expansions, just note where the beginning of the macro
7188 // expansion occurs.
7189 if (cursor.kind == CXCursor_MacroExpansion) {
7190 if (TokLoc == cursorRange.getBegin())
7191 Cursors[I] = cursor;
7192 AdvanceToken();
7193 break;
7194 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007195 // We may have already annotated macro names inside macro definitions.
7196 if (Cursors[I].kind != CXCursor_MacroExpansion)
7197 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007198 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007199 continue;
7200 }
7201 break;
7202 }
7203
7204 // Save the preprocessing token index; restore the non-preprocessing
7205 // token index.
7206 PreprocessingTokIdx = TokIdx;
7207 TokIdx = SavedTokIdx;
7208 return CXChildVisit_Recurse;
7209 }
7210
7211 if (cursorRange.isInvalid())
7212 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007213
7214 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007215 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007216 const enum CXCursorKind K = clang_getCursorKind(parent);
7217 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007218 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7219 // Attributes are annotated out-of-order, skip tokens until we reach it.
7220 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007221 ? clang_getNullCursor() : parent;
7222
7223 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7224
7225 // Avoid having the cursor of an expression "overwrite" the annotation of the
7226 // variable declaration that it belongs to.
7227 // This can happen for C++ constructor expressions whose range generally
7228 // include the variable declaration, e.g.:
7229 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007230 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007231 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007232 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007234 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7235 E->getBeginLoc() == D->getLocation() &&
7236 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007237 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007238 AdvanceToken();
7239 }
7240 }
7241 }
7242
7243 // Before recursing into the children keep some state that we are going
7244 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7245 // extra work after the child nodes are visited.
7246 // Note that we don't call VisitChildren here to avoid traversing statements
7247 // code-recursively which can blow the stack.
7248
7249 PostChildrenInfo Info;
7250 Info.Cursor = cursor;
7251 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007252 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007253 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007254 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 PostChildrenInfos.push_back(Info);
7256
7257 return CXChildVisit_Recurse;
7258}
7259
7260bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7261 if (PostChildrenInfos.empty())
7262 return false;
7263 const PostChildrenInfo &Info = PostChildrenInfos.back();
7264 if (!clang_equalCursors(Info.Cursor, cursor))
7265 return false;
7266
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007267 HandlePostPonedChildCursors(Info);
7268
Guy Benyei11169dd2012-12-18 14:30:41 +00007269 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7270 const unsigned AfterChildren = NextToken();
7271 SourceRange cursorRange = Info.CursorRange;
7272
7273 // Scan the tokens that are at the end of the cursor, but are not captured
7274 // but the child cursors.
7275 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7276
7277 // Scan the tokens that are at the beginning of the cursor, but are not
7278 // capture by the child cursors.
7279 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7280 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7281 break;
7282
7283 Cursors[I] = cursor;
7284 }
7285
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007286 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7287 // encountered the attribute cursor.
7288 if (clang_isAttribute(cursor.kind))
7289 TokIdx = Info.BeforeReachingCursorIdx;
7290
Guy Benyei11169dd2012-12-18 14:30:41 +00007291 PostChildrenInfos.pop_back();
7292 return false;
7293}
7294
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007295void AnnotateTokensWorker::HandlePostPonedChildCursors(
7296 const PostChildrenInfo &Info) {
7297 for (const auto &ChildAction : Info.ChildActions) {
7298 if (ChildAction.action == PostChildrenAction::Postpone) {
7299 HandlePostPonedChildCursor(ChildAction.cursor,
7300 Info.BeforeChildrenTokenIdx);
7301 }
7302 }
7303}
7304
7305void AnnotateTokensWorker::HandlePostPonedChildCursor(
7306 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007307 unsigned I = StartTokenIndex;
7308
7309 // The bracket tokens of a Call or Subscript operator are mapped to
7310 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7311 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7312 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007313 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7314 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007315 if (clang_Range_isNull(CXRefNameRange))
7316 break; // All ranges handled.
7317
7318 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7319 while (I < NumTokens) {
7320 const SourceLocation TokenLocation = GetTokenLoc(I);
7321 if (!TokenLocation.isValid())
7322 break;
7323
7324 // Adapt the end range, because LocationCompare() reports
7325 // RangeOverlap even for the not-inclusive end location.
7326 const SourceLocation fixedEnd =
7327 RefNameRange.getEnd().getLocWithOffset(-1);
7328 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7329
7330 const RangeComparisonResult ComparisonResult =
7331 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7332
7333 if (ComparisonResult == RangeOverlap) {
7334 Cursors[I++] = Cursor;
7335 } else if (ComparisonResult == RangeBefore) {
7336 ++I; // Not relevant token, check next one.
7337 } else if (ComparisonResult == RangeAfter) {
7338 break; // All tokens updated for current range, check next.
7339 }
7340 }
7341 }
7342}
7343
Guy Benyei11169dd2012-12-18 14:30:41 +00007344static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7345 CXCursor parent,
7346 CXClientData client_data) {
7347 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7348}
7349
7350static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7351 CXClientData client_data) {
7352 return static_cast<AnnotateTokensWorker*>(client_data)->
7353 postVisitChildren(cursor);
7354}
7355
7356namespace {
7357
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007358/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007359/// and mark tokens that are macro arguments. This info is used by the
7360/// AnnotateTokensWorker.
7361class MarkMacroArgTokensVisitor {
7362 SourceManager &SM;
7363 CXToken *Tokens;
7364 unsigned NumTokens;
7365 unsigned CurIdx;
7366
7367public:
7368 MarkMacroArgTokensVisitor(SourceManager &SM,
7369 CXToken *tokens, unsigned numTokens)
7370 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7371
7372 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7373 if (cursor.kind != CXCursor_MacroExpansion)
7374 return CXChildVisit_Continue;
7375
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007376 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007377 if (macroRange.getBegin() == macroRange.getEnd())
7378 return CXChildVisit_Continue; // it's not a function macro.
7379
7380 for (; CurIdx < NumTokens; ++CurIdx) {
7381 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7382 macroRange.getBegin()))
7383 break;
7384 }
7385
7386 if (CurIdx == NumTokens)
7387 return CXChildVisit_Break;
7388
7389 for (; CurIdx < NumTokens; ++CurIdx) {
7390 SourceLocation tokLoc = getTokenLoc(CurIdx);
7391 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7392 break;
7393
7394 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7395 }
7396
7397 if (CurIdx == NumTokens)
7398 return CXChildVisit_Break;
7399
7400 return CXChildVisit_Continue;
7401 }
7402
7403private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007404 CXToken &getTok(unsigned Idx) {
7405 assert(Idx < NumTokens);
7406 return Tokens[Idx];
7407 }
7408 const CXToken &getTok(unsigned Idx) const {
7409 assert(Idx < NumTokens);
7410 return Tokens[Idx];
7411 }
7412
Guy Benyei11169dd2012-12-18 14:30:41 +00007413 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007414 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007415 }
7416
7417 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7418 // The third field is reserved and currently not used. Use it here
7419 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007420 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007421 }
7422};
7423
7424} // end anonymous namespace
7425
7426static CXChildVisitResult
7427MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7428 CXClientData client_data) {
7429 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7430 parent);
7431}
7432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007433/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007434/// \returns true if lexing was finished, false otherwise.
7435static bool lexNext(Lexer &Lex, Token &Tok,
7436 unsigned &NextIdx, unsigned NumTokens) {
7437 if (NextIdx >= NumTokens)
7438 return true;
7439
7440 ++NextIdx;
7441 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007442 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007443}
7444
Guy Benyei11169dd2012-12-18 14:30:41 +00007445static void annotatePreprocessorTokens(CXTranslationUnit TU,
7446 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007447 CXCursor *Cursors,
7448 CXToken *Tokens,
7449 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007450 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007451
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007452 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007453 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7454 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007455 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007456 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007457 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007458
7459 if (BeginLocInfo.first != EndLocInfo.first)
7460 return;
7461
7462 StringRef Buffer;
7463 bool Invalid = false;
7464 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7465 if (Buffer.empty() || Invalid)
7466 return;
7467
7468 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7469 CXXUnit->getASTContext().getLangOpts(),
7470 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7471 Buffer.end());
7472 Lex.SetCommentRetentionState(true);
7473
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007474 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 // Lex tokens in raw mode until we hit the end of the range, to avoid
7476 // entering #includes or expanding macros.
7477 while (true) {
7478 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007479 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7480 break;
7481 unsigned TokIdx = NextIdx-1;
7482 assert(Tok.getLocation() ==
7483 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007484
7485 reprocess:
7486 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007487 // We have found a preprocessing directive. Annotate the tokens
7488 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007489 //
7490 // FIXME: Some simple tests here could identify macro definitions and
7491 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007492
7493 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007494 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7495 break;
7496
Craig Topper69186e72014-06-08 08:38:04 +00007497 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007498 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007499 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7500 break;
7501
7502 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007503 IdentifierInfo &II =
7504 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007505 SourceLocation MappedTokLoc =
7506 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7507 MI = getMacroInfo(II, MappedTokLoc, TU);
7508 }
7509 }
7510
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007511 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007512 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007513 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7514 finished = true;
7515 break;
7516 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007517 // If we are in a macro definition, check if the token was ever a
7518 // macro name and annotate it if that's the case.
7519 if (MI) {
7520 SourceLocation SaveLoc = Tok.getLocation();
7521 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007522 MacroDefinitionRecord *MacroDef =
7523 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007524 Tok.setLocation(SaveLoc);
7525 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007526 Cursors[NextIdx - 1] =
7527 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007528 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007529 } while (!Tok.isAtStartOfLine());
7530
7531 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7532 assert(TokIdx <= LastIdx);
7533 SourceLocation EndLoc =
7534 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7535 CXCursor Cursor =
7536 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7537
7538 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007539 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007540
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007541 if (finished)
7542 break;
7543 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007544 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007545 }
7546}
7547
7548// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007549static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7550 CXToken *Tokens, unsigned NumTokens,
7551 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007552 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007553 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7554 setThreadBackgroundPriority();
7555
7556 // Determine the region of interest, which contains all of the tokens.
7557 SourceRange RegionOfInterest;
7558 RegionOfInterest.setBegin(
7559 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7560 RegionOfInterest.setEnd(
7561 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7562 Tokens[NumTokens-1])));
7563
Guy Benyei11169dd2012-12-18 14:30:41 +00007564 // Relex the tokens within the source range to look for preprocessing
7565 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007566 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007567
7568 // If begin location points inside a macro argument, set it to the expansion
7569 // location so we can have the full context when annotating semantically.
7570 {
7571 SourceManager &SM = CXXUnit->getSourceManager();
7572 SourceLocation Loc =
7573 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7574 if (Loc.isMacroID())
7575 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7576 }
7577
Guy Benyei11169dd2012-12-18 14:30:41 +00007578 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7579 // Search and mark tokens that are macro argument expansions.
7580 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7581 Tokens, NumTokens);
7582 CursorVisitor MacroArgMarker(TU,
7583 MarkMacroArgTokensVisitorDelegate, &Visitor,
7584 /*VisitPreprocessorLast=*/true,
7585 /*VisitIncludedEntities=*/false,
7586 RegionOfInterest);
7587 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7588 }
7589
7590 // Annotate all of the source locations in the region of interest that map to
7591 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007592 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007593
7594 // FIXME: We use a ridiculous stack size here because the data-recursion
7595 // algorithm uses a large stack frame than the non-data recursive version,
7596 // and AnnotationTokensWorker currently transforms the data-recursion
7597 // algorithm back into a traditional recursion by explicitly calling
7598 // VisitChildren(). We will need to remove this explicit recursive call.
7599 W.AnnotateTokens();
7600
7601 // If we ran into any entities that involve context-sensitive keywords,
7602 // take another pass through the tokens to mark them as such.
7603 if (W.hasContextSensitiveKeywords()) {
7604 for (unsigned I = 0; I != NumTokens; ++I) {
7605 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7606 continue;
7607
7608 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7609 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007610 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007611 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7612 if (Property->getPropertyAttributesAsWritten() != 0 &&
7613 llvm::StringSwitch<bool>(II->getName())
7614 .Case("readonly", true)
7615 .Case("assign", true)
7616 .Case("unsafe_unretained", true)
7617 .Case("readwrite", true)
7618 .Case("retain", true)
7619 .Case("copy", true)
7620 .Case("nonatomic", true)
7621 .Case("atomic", true)
7622 .Case("getter", true)
7623 .Case("setter", true)
7624 .Case("strong", true)
7625 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007626 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007627 .Default(false))
7628 Tokens[I].int_data[0] = CXToken_Keyword;
7629 }
7630 continue;
7631 }
7632
7633 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7634 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7635 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7636 if (llvm::StringSwitch<bool>(II->getName())
7637 .Case("in", true)
7638 .Case("out", true)
7639 .Case("inout", true)
7640 .Case("oneway", true)
7641 .Case("bycopy", true)
7642 .Case("byref", true)
7643 .Default(false))
7644 Tokens[I].int_data[0] = CXToken_Keyword;
7645 continue;
7646 }
7647
7648 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7649 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7650 Tokens[I].int_data[0] = CXToken_Keyword;
7651 continue;
7652 }
7653 }
7654 }
7655}
7656
Guy Benyei11169dd2012-12-18 14:30:41 +00007657void clang_annotateTokens(CXTranslationUnit TU,
7658 CXToken *Tokens, unsigned NumTokens,
7659 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007660 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007661 LOG_BAD_TU(TU);
7662 return;
7663 }
7664 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007665 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007667 }
7668
7669 LOG_FUNC_SECTION {
7670 *Log << TU << ' ';
7671 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7672 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7673 *Log << clang_getRange(bloc, eloc);
7674 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007675
7676 // Any token we don't specifically annotate will have a NULL cursor.
7677 CXCursor C = clang_getNullCursor();
7678 for (unsigned I = 0; I != NumTokens; ++I)
7679 Cursors[I] = C;
7680
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007681 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007682 if (!CXXUnit)
7683 return;
7684
7685 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007686
7687 auto AnnotateTokensImpl = [=]() {
7688 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7689 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007690 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007691 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007692 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7693 }
7694}
7695
Guy Benyei11169dd2012-12-18 14:30:41 +00007696//===----------------------------------------------------------------------===//
7697// Operations for querying linkage of a cursor.
7698//===----------------------------------------------------------------------===//
7699
Guy Benyei11169dd2012-12-18 14:30:41 +00007700CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7701 if (!clang_isDeclaration(cursor.kind))
7702 return CXLinkage_Invalid;
7703
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007704 const Decl *D = cxcursor::getCursorDecl(cursor);
7705 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007706 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007707 case NoLinkage:
7708 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007709 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007710 case InternalLinkage: return CXLinkage_Internal;
7711 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007712 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007713 case ExternalLinkage: return CXLinkage_External;
7714 };
7715
7716 return CXLinkage_Invalid;
7717}
Guy Benyei11169dd2012-12-18 14:30:41 +00007718
7719//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007720// Operations for querying visibility of a cursor.
7721//===----------------------------------------------------------------------===//
7722
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007723CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7724 if (!clang_isDeclaration(cursor.kind))
7725 return CXVisibility_Invalid;
7726
7727 const Decl *D = cxcursor::getCursorDecl(cursor);
7728 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7729 switch (ND->getVisibility()) {
7730 case HiddenVisibility: return CXVisibility_Hidden;
7731 case ProtectedVisibility: return CXVisibility_Protected;
7732 case DefaultVisibility: return CXVisibility_Default;
7733 };
7734
7735 return CXVisibility_Invalid;
7736}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007737
7738//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007739// Operations for querying language of a cursor.
7740//===----------------------------------------------------------------------===//
7741
7742static CXLanguageKind getDeclLanguage(const Decl *D) {
7743 if (!D)
7744 return CXLanguage_C;
7745
7746 switch (D->getKind()) {
7747 default:
7748 break;
7749 case Decl::ImplicitParam:
7750 case Decl::ObjCAtDefsField:
7751 case Decl::ObjCCategory:
7752 case Decl::ObjCCategoryImpl:
7753 case Decl::ObjCCompatibleAlias:
7754 case Decl::ObjCImplementation:
7755 case Decl::ObjCInterface:
7756 case Decl::ObjCIvar:
7757 case Decl::ObjCMethod:
7758 case Decl::ObjCProperty:
7759 case Decl::ObjCPropertyImpl:
7760 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007761 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007762 return CXLanguage_ObjC;
7763 case Decl::CXXConstructor:
7764 case Decl::CXXConversion:
7765 case Decl::CXXDestructor:
7766 case Decl::CXXMethod:
7767 case Decl::CXXRecord:
7768 case Decl::ClassTemplate:
7769 case Decl::ClassTemplatePartialSpecialization:
7770 case Decl::ClassTemplateSpecialization:
7771 case Decl::Friend:
7772 case Decl::FriendTemplate:
7773 case Decl::FunctionTemplate:
7774 case Decl::LinkageSpec:
7775 case Decl::Namespace:
7776 case Decl::NamespaceAlias:
7777 case Decl::NonTypeTemplateParm:
7778 case Decl::StaticAssert:
7779 case Decl::TemplateTemplateParm:
7780 case Decl::TemplateTypeParm:
7781 case Decl::UnresolvedUsingTypename:
7782 case Decl::UnresolvedUsingValue:
7783 case Decl::Using:
7784 case Decl::UsingDirective:
7785 case Decl::UsingShadow:
7786 return CXLanguage_CPlusPlus;
7787 }
7788
7789 return CXLanguage_C;
7790}
7791
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007792static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7793 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007794 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007795
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007796 switch (D->getAvailability()) {
7797 case AR_Available:
7798 case AR_NotYetIntroduced:
7799 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007800 return getCursorAvailabilityForDecl(
7801 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007802 return CXAvailability_Available;
7803
7804 case AR_Deprecated:
7805 return CXAvailability_Deprecated;
7806
7807 case AR_Unavailable:
7808 return CXAvailability_NotAvailable;
7809 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007810
7811 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007812}
7813
Guy Benyei11169dd2012-12-18 14:30:41 +00007814enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7815 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007816 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7817 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007818
7819 return CXAvailability_Available;
7820}
7821
7822static CXVersion convertVersion(VersionTuple In) {
7823 CXVersion Out = { -1, -1, -1 };
7824 if (In.empty())
7825 return Out;
7826
7827 Out.Major = In.getMajor();
7828
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007829 Optional<unsigned> Minor = In.getMinor();
7830 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007831 Out.Minor = *Minor;
7832 else
7833 return Out;
7834
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007835 Optional<unsigned> Subminor = In.getSubminor();
7836 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007837 Out.Subminor = *Subminor;
7838
7839 return Out;
7840}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007841
Alex Lorenz1345ea22017-06-12 19:06:30 +00007842static void getCursorPlatformAvailabilityForDecl(
7843 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7844 int *always_unavailable, CXString *unavailable_message,
7845 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007846 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007847 for (auto A : D->attrs()) {
7848 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007849 HadAvailAttr = true;
7850 if (always_deprecated)
7851 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007852 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007853 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007854 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007855 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007856 continue;
7857 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007858
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007859 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007860 HadAvailAttr = true;
7861 if (always_unavailable)
7862 *always_unavailable = 1;
7863 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007864 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007865 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7866 }
7867 continue;
7868 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007869
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007870 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007871 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007872 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007873 }
7874 }
7875
7876 if (!HadAvailAttr)
7877 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7878 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007879 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7880 deprecated_message, always_unavailable, unavailable_message,
7881 AvailabilityAttrs);
7882
7883 if (AvailabilityAttrs.empty())
7884 return;
7885
Fangrui Song55fab262018-09-26 22:16:28 +00007886 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007887 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7888 return LHS->getPlatform()->getName() <
7889 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007890 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007891 ASTContext &Ctx = D->getASTContext();
7892 auto It = std::unique(
7893 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7894 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7895 if (LHS->getPlatform() != RHS->getPlatform())
7896 return false;
7897
7898 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7899 LHS->getDeprecated() == RHS->getDeprecated() &&
7900 LHS->getObsoleted() == RHS->getObsoleted() &&
7901 LHS->getMessage() == RHS->getMessage() &&
7902 LHS->getReplacement() == RHS->getReplacement())
7903 return true;
7904
7905 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7906 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7907 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7908 return false;
7909
7910 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7911 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7912
7913 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7914 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7915 if (LHS->getMessage().empty())
7916 LHS->setMessage(Ctx, RHS->getMessage());
7917 if (LHS->getReplacement().empty())
7918 LHS->setReplacement(Ctx, RHS->getReplacement());
7919 }
7920
7921 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7922 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7923 if (LHS->getMessage().empty())
7924 LHS->setMessage(Ctx, RHS->getMessage());
7925 if (LHS->getReplacement().empty())
7926 LHS->setReplacement(Ctx, RHS->getReplacement());
7927 }
7928
7929 return true;
7930 });
7931 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007932}
7933
Alex Lorenz1345ea22017-06-12 19:06:30 +00007934int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007935 CXString *deprecated_message,
7936 int *always_unavailable,
7937 CXString *unavailable_message,
7938 CXPlatformAvailability *availability,
7939 int availability_size) {
7940 if (always_deprecated)
7941 *always_deprecated = 0;
7942 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007943 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007944 if (always_unavailable)
7945 *always_unavailable = 0;
7946 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007947 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007948
Guy Benyei11169dd2012-12-18 14:30:41 +00007949 if (!clang_isDeclaration(cursor.kind))
7950 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007951
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007952 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007953 if (!D)
7954 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007955
Alex Lorenz1345ea22017-06-12 19:06:30 +00007956 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7957 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7958 always_unavailable, unavailable_message,
7959 AvailabilityAttrs);
7960 for (const auto &Avail :
7961 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7962 .take_front(availability_size))) {
7963 availability[Avail.index()].Platform =
7964 cxstring::createDup(Avail.value()->getPlatform()->getName());
7965 availability[Avail.index()].Introduced =
7966 convertVersion(Avail.value()->getIntroduced());
7967 availability[Avail.index()].Deprecated =
7968 convertVersion(Avail.value()->getDeprecated());
7969 availability[Avail.index()].Obsoleted =
7970 convertVersion(Avail.value()->getObsoleted());
7971 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7972 availability[Avail.index()].Message =
7973 cxstring::createDup(Avail.value()->getMessage());
7974 }
7975
7976 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007977}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007978
Guy Benyei11169dd2012-12-18 14:30:41 +00007979void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7980 clang_disposeString(availability->Platform);
7981 clang_disposeString(availability->Message);
7982}
7983
7984CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7985 if (clang_isDeclaration(cursor.kind))
7986 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7987
7988 return CXLanguage_Invalid;
7989}
7990
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007991CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7992 const Decl *D = cxcursor::getCursorDecl(cursor);
7993 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7994 switch (VD->getTLSKind()) {
7995 case VarDecl::TLS_None:
7996 return CXTLS_None;
7997 case VarDecl::TLS_Dynamic:
7998 return CXTLS_Dynamic;
7999 case VarDecl::TLS_Static:
8000 return CXTLS_Static;
8001 }
8002 }
8003
8004 return CXTLS_None;
8005}
8006
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008007 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008008 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008009 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008010static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008011 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008012 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008013
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008014 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008015 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8016 return FunTmpl;
8017
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008018 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008019 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8020 return ClassTmpl;
8021
8022 return D;
8023}
8024
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008025
8026enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8027 StorageClass sc = SC_None;
8028 const Decl *D = getCursorDecl(C);
8029 if (D) {
8030 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8031 sc = FD->getStorageClass();
8032 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8033 sc = VD->getStorageClass();
8034 } else {
8035 return CX_SC_Invalid;
8036 }
8037 } else {
8038 return CX_SC_Invalid;
8039 }
8040 switch (sc) {
8041 case SC_None:
8042 return CX_SC_None;
8043 case SC_Extern:
8044 return CX_SC_Extern;
8045 case SC_Static:
8046 return CX_SC_Static;
8047 case SC_PrivateExtern:
8048 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008049 case SC_Auto:
8050 return CX_SC_Auto;
8051 case SC_Register:
8052 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008053 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008054 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008055}
8056
Guy Benyei11169dd2012-12-18 14:30:41 +00008057CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8058 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008059 if (const Decl *D = getCursorDecl(cursor)) {
8060 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 if (!DC)
8062 return clang_getNullCursor();
8063
8064 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8065 getCursorTU(cursor));
8066 }
8067 }
8068
8069 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008070 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 return MakeCXCursor(D, getCursorTU(cursor));
8072 }
8073
8074 return clang_getNullCursor();
8075}
8076
8077CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8078 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008079 if (const Decl *D = getCursorDecl(cursor)) {
8080 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008081 if (!DC)
8082 return clang_getNullCursor();
8083
8084 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8085 getCursorTU(cursor));
8086 }
8087 }
8088
8089 // FIXME: Note that we can't easily compute the lexical context of a
8090 // statement or expression, so we return nothing.
8091 return clang_getNullCursor();
8092}
8093
8094CXFile clang_getIncludedFile(CXCursor cursor) {
8095 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008096 return nullptr;
8097
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008098 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008099 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008100}
8101
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008102unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8103 if (C.kind != CXCursor_ObjCPropertyDecl)
8104 return CXObjCPropertyAttr_noattr;
8105
8106 unsigned Result = CXObjCPropertyAttr_noattr;
8107 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8108 ObjCPropertyDecl::PropertyAttributeKind Attr =
8109 PD->getPropertyAttributesAsWritten();
8110
8111#define SET_CXOBJCPROP_ATTR(A) \
8112 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8113 Result |= CXObjCPropertyAttr_##A
8114 SET_CXOBJCPROP_ATTR(readonly);
8115 SET_CXOBJCPROP_ATTR(getter);
8116 SET_CXOBJCPROP_ATTR(assign);
8117 SET_CXOBJCPROP_ATTR(readwrite);
8118 SET_CXOBJCPROP_ATTR(retain);
8119 SET_CXOBJCPROP_ATTR(copy);
8120 SET_CXOBJCPROP_ATTR(nonatomic);
8121 SET_CXOBJCPROP_ATTR(setter);
8122 SET_CXOBJCPROP_ATTR(atomic);
8123 SET_CXOBJCPROP_ATTR(weak);
8124 SET_CXOBJCPROP_ATTR(strong);
8125 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008126 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008127#undef SET_CXOBJCPROP_ATTR
8128
8129 return Result;
8130}
8131
Michael Wu6e88f532018-08-03 05:38:29 +00008132CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8133 if (C.kind != CXCursor_ObjCPropertyDecl)
8134 return cxstring::createNull();
8135
8136 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8137 Selector sel = PD->getGetterName();
8138 if (sel.isNull())
8139 return cxstring::createNull();
8140
8141 return cxstring::createDup(sel.getAsString());
8142}
8143
8144CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8145 if (C.kind != CXCursor_ObjCPropertyDecl)
8146 return cxstring::createNull();
8147
8148 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8149 Selector sel = PD->getSetterName();
8150 if (sel.isNull())
8151 return cxstring::createNull();
8152
8153 return cxstring::createDup(sel.getAsString());
8154}
8155
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008156unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8157 if (!clang_isDeclaration(C.kind))
8158 return CXObjCDeclQualifier_None;
8159
8160 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8161 const Decl *D = getCursorDecl(C);
8162 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8163 QT = MD->getObjCDeclQualifier();
8164 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8165 QT = PD->getObjCDeclQualifier();
8166 if (QT == Decl::OBJC_TQ_None)
8167 return CXObjCDeclQualifier_None;
8168
8169 unsigned Result = CXObjCDeclQualifier_None;
8170 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8171 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8172 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8173 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8174 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8175 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8176
8177 return Result;
8178}
8179
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008180unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8181 if (!clang_isDeclaration(C.kind))
8182 return 0;
8183
8184 const Decl *D = getCursorDecl(C);
8185 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8186 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8187 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8188 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8189
8190 return 0;
8191}
8192
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008193unsigned clang_Cursor_isVariadic(CXCursor C) {
8194 if (!clang_isDeclaration(C.kind))
8195 return 0;
8196
8197 const Decl *D = getCursorDecl(C);
8198 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8199 return FD->isVariadic();
8200 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8201 return MD->isVariadic();
8202
8203 return 0;
8204}
8205
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008206unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8207 CXString *language, CXString *definedIn,
8208 unsigned *isGenerated) {
8209 if (!clang_isDeclaration(C.kind))
8210 return 0;
8211
8212 const Decl *D = getCursorDecl(C);
8213
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008214 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008215 if (language)
8216 *language = cxstring::createDup(attr->getLanguage());
8217 if (definedIn)
8218 *definedIn = cxstring::createDup(attr->getDefinedIn());
8219 if (isGenerated)
8220 *isGenerated = attr->getGeneratedDeclaration();
8221 return 1;
8222 }
8223 return 0;
8224}
8225
Guy Benyei11169dd2012-12-18 14:30:41 +00008226CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8227 if (!clang_isDeclaration(C.kind))
8228 return clang_getNullRange();
8229
8230 const Decl *D = getCursorDecl(C);
8231 ASTContext &Context = getCursorContext(C);
8232 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8233 if (!RC)
8234 return clang_getNullRange();
8235
8236 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8237}
8238
8239CXString clang_Cursor_getRawCommentText(CXCursor C) {
8240 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008241 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008242
8243 const Decl *D = getCursorDecl(C);
8244 ASTContext &Context = getCursorContext(C);
8245 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8246 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8247 StringRef();
8248
8249 // Don't duplicate the string because RawText points directly into source
8250 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008251 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008252}
8253
8254CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8255 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008256 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008257
8258 const Decl *D = getCursorDecl(C);
8259 const ASTContext &Context = getCursorContext(C);
8260 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8261
8262 if (RC) {
8263 StringRef BriefText = RC->getBriefText(Context);
8264
8265 // Don't duplicate the string because RawComment ensures that this memory
8266 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008267 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008268 }
8269
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008270 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008271}
8272
Guy Benyei11169dd2012-12-18 14:30:41 +00008273CXModule clang_Cursor_getModule(CXCursor C) {
8274 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008275 if (const ImportDecl *ImportD =
8276 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008277 return ImportD->getImportedModule();
8278 }
8279
Craig Topper69186e72014-06-08 08:38:04 +00008280 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008281}
8282
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008283CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8284 if (isNotUsableTU(TU)) {
8285 LOG_BAD_TU(TU);
8286 return nullptr;
8287 }
8288 if (!File)
8289 return nullptr;
8290 FileEntry *FE = static_cast<FileEntry *>(File);
8291
8292 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8293 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8294 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8295
Richard Smithfeb54b62014-10-23 02:01:19 +00008296 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008297}
8298
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008299CXFile clang_Module_getASTFile(CXModule CXMod) {
8300 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008301 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008302 Module *Mod = static_cast<Module*>(CXMod);
8303 return const_cast<FileEntry *>(Mod->getASTFile());
8304}
8305
Guy Benyei11169dd2012-12-18 14:30:41 +00008306CXModule clang_Module_getParent(CXModule CXMod) {
8307 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008308 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008309 Module *Mod = static_cast<Module*>(CXMod);
8310 return Mod->Parent;
8311}
8312
8313CXString clang_Module_getName(CXModule CXMod) {
8314 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008315 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008316 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008317 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008318}
8319
8320CXString clang_Module_getFullName(CXModule CXMod) {
8321 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008322 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008323 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008324 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008325}
8326
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008327int clang_Module_isSystem(CXModule CXMod) {
8328 if (!CXMod)
8329 return 0;
8330 Module *Mod = static_cast<Module*>(CXMod);
8331 return Mod->IsSystem;
8332}
8333
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008334unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8335 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008336 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008337 LOG_BAD_TU(TU);
8338 return 0;
8339 }
8340 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008341 return 0;
8342 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008343 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8344 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8345 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008346}
8347
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008348CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8349 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008350 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008351 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008352 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008353 }
8354 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008355 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008357 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008358
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008359 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8360 if (Index < TopHeaders.size())
8361 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008362
Craig Topper69186e72014-06-08 08:38:04 +00008363 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008364}
8365
Guy Benyei11169dd2012-12-18 14:30:41 +00008366//===----------------------------------------------------------------------===//
8367// C++ AST instrospection.
8368//===----------------------------------------------------------------------===//
8369
Jonathan Coe29565352016-04-27 12:48:25 +00008370unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8371 if (!clang_isDeclaration(C.kind))
8372 return 0;
8373
8374 const Decl *D = cxcursor::getCursorDecl(C);
8375 const CXXConstructorDecl *Constructor =
8376 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8377 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8378}
8379
8380unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8381 if (!clang_isDeclaration(C.kind))
8382 return 0;
8383
8384 const Decl *D = cxcursor::getCursorDecl(C);
8385 const CXXConstructorDecl *Constructor =
8386 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8387 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8388}
8389
8390unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8391 if (!clang_isDeclaration(C.kind))
8392 return 0;
8393
8394 const Decl *D = cxcursor::getCursorDecl(C);
8395 const CXXConstructorDecl *Constructor =
8396 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8397 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8398}
8399
8400unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8401 if (!clang_isDeclaration(C.kind))
8402 return 0;
8403
8404 const Decl *D = cxcursor::getCursorDecl(C);
8405 const CXXConstructorDecl *Constructor =
8406 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8407 // Passing 'false' excludes constructors marked 'explicit'.
8408 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8409}
8410
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008411unsigned clang_CXXField_isMutable(CXCursor C) {
8412 if (!clang_isDeclaration(C.kind))
8413 return 0;
8414
8415 if (const auto D = cxcursor::getCursorDecl(C))
8416 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8417 return FD->isMutable() ? 1 : 0;
8418 return 0;
8419}
8420
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008421unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8422 if (!clang_isDeclaration(C.kind))
8423 return 0;
8424
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008425 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008426 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008427 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008428 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8429}
8430
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008431unsigned clang_CXXMethod_isConst(CXCursor C) {
8432 if (!clang_isDeclaration(C.kind))
8433 return 0;
8434
8435 const Decl *D = cxcursor::getCursorDecl(C);
8436 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008437 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008438 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008439}
8440
Jonathan Coe29565352016-04-27 12:48:25 +00008441unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8442 if (!clang_isDeclaration(C.kind))
8443 return 0;
8444
8445 const Decl *D = cxcursor::getCursorDecl(C);
8446 const CXXMethodDecl *Method =
8447 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8448 return (Method && Method->isDefaulted()) ? 1 : 0;
8449}
8450
Guy Benyei11169dd2012-12-18 14:30:41 +00008451unsigned clang_CXXMethod_isStatic(CXCursor C) {
8452 if (!clang_isDeclaration(C.kind))
8453 return 0;
8454
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008455 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008456 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008457 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008458 return (Method && Method->isStatic()) ? 1 : 0;
8459}
8460
8461unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8462 if (!clang_isDeclaration(C.kind))
8463 return 0;
8464
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008465 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008466 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008467 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008468 return (Method && Method->isVirtual()) ? 1 : 0;
8469}
Guy Benyei11169dd2012-12-18 14:30:41 +00008470
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008471unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8472 if (!clang_isDeclaration(C.kind))
8473 return 0;
8474
8475 const auto *D = cxcursor::getCursorDecl(C);
8476 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8477 if (RD)
8478 RD = RD->getDefinition();
8479 return (RD && RD->isAbstract()) ? 1 : 0;
8480}
8481
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008482unsigned clang_EnumDecl_isScoped(CXCursor C) {
8483 if (!clang_isDeclaration(C.kind))
8484 return 0;
8485
8486 const Decl *D = cxcursor::getCursorDecl(C);
8487 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8488 return (Enum && Enum->isScoped()) ? 1 : 0;
8489}
8490
Guy Benyei11169dd2012-12-18 14:30:41 +00008491//===----------------------------------------------------------------------===//
8492// Attribute introspection.
8493//===----------------------------------------------------------------------===//
8494
Guy Benyei11169dd2012-12-18 14:30:41 +00008495CXType clang_getIBOutletCollectionType(CXCursor C) {
8496 if (C.kind != CXCursor_IBOutletCollectionAttr)
8497 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8498
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008499 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008500 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8501
8502 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8503}
Guy Benyei11169dd2012-12-18 14:30:41 +00008504
8505//===----------------------------------------------------------------------===//
8506// Inspecting memory usage.
8507//===----------------------------------------------------------------------===//
8508
8509typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8510
8511static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8512 enum CXTUResourceUsageKind k,
8513 unsigned long amount) {
8514 CXTUResourceUsageEntry entry = { k, amount };
8515 entries.push_back(entry);
8516}
8517
Guy Benyei11169dd2012-12-18 14:30:41 +00008518const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8519 const char *str = "";
8520 switch (kind) {
8521 case CXTUResourceUsage_AST:
8522 str = "ASTContext: expressions, declarations, and types";
8523 break;
8524 case CXTUResourceUsage_Identifiers:
8525 str = "ASTContext: identifiers";
8526 break;
8527 case CXTUResourceUsage_Selectors:
8528 str = "ASTContext: selectors";
8529 break;
8530 case CXTUResourceUsage_GlobalCompletionResults:
8531 str = "Code completion: cached global results";
8532 break;
8533 case CXTUResourceUsage_SourceManagerContentCache:
8534 str = "SourceManager: content cache allocator";
8535 break;
8536 case CXTUResourceUsage_AST_SideTables:
8537 str = "ASTContext: side tables";
8538 break;
8539 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8540 str = "SourceManager: malloc'ed memory buffers";
8541 break;
8542 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8543 str = "SourceManager: mmap'ed memory buffers";
8544 break;
8545 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8546 str = "ExternalASTSource: malloc'ed memory buffers";
8547 break;
8548 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8549 str = "ExternalASTSource: mmap'ed memory buffers";
8550 break;
8551 case CXTUResourceUsage_Preprocessor:
8552 str = "Preprocessor: malloc'ed memory";
8553 break;
8554 case CXTUResourceUsage_PreprocessingRecord:
8555 str = "Preprocessor: PreprocessingRecord";
8556 break;
8557 case CXTUResourceUsage_SourceManager_DataStructures:
8558 str = "SourceManager: data structures and tables";
8559 break;
8560 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8561 str = "Preprocessor: header search tables";
8562 break;
8563 }
8564 return str;
8565}
8566
8567CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008568 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008569 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008570 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008571 return usage;
8572 }
8573
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008574 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008575 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008576 ASTContext &astContext = astUnit->getASTContext();
8577
8578 // How much memory is used by AST nodes and types?
8579 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8580 (unsigned long) astContext.getASTAllocatedMemory());
8581
8582 // How much memory is used by identifiers?
8583 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8584 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8585
8586 // How much memory is used for selectors?
8587 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8588 (unsigned long) astContext.Selectors.getTotalMemory());
8589
8590 // How much memory is used by ASTContext's side tables?
8591 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8592 (unsigned long) astContext.getSideTableAllocatedMemory());
8593
8594 // How much memory is used for caching global code completion results?
8595 unsigned long completionBytes = 0;
8596 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008597 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008598 completionBytes = completionAllocator->getTotalMemory();
8599 }
8600 createCXTUResourceUsageEntry(*entries,
8601 CXTUResourceUsage_GlobalCompletionResults,
8602 completionBytes);
8603
8604 // How much memory is being used by SourceManager's content cache?
8605 createCXTUResourceUsageEntry(*entries,
8606 CXTUResourceUsage_SourceManagerContentCache,
8607 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8608
8609 // How much memory is being used by the MemoryBuffer's in SourceManager?
8610 const SourceManager::MemoryBufferSizes &srcBufs =
8611 astUnit->getSourceManager().getMemoryBufferSizes();
8612
8613 createCXTUResourceUsageEntry(*entries,
8614 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8615 (unsigned long) srcBufs.malloc_bytes);
8616 createCXTUResourceUsageEntry(*entries,
8617 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8618 (unsigned long) srcBufs.mmap_bytes);
8619 createCXTUResourceUsageEntry(*entries,
8620 CXTUResourceUsage_SourceManager_DataStructures,
8621 (unsigned long) astContext.getSourceManager()
8622 .getDataStructureSizes());
8623
8624 // How much memory is being used by the ExternalASTSource?
8625 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8626 const ExternalASTSource::MemoryBufferSizes &sizes =
8627 esrc->getMemoryBufferSizes();
8628
8629 createCXTUResourceUsageEntry(*entries,
8630 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8631 (unsigned long) sizes.malloc_bytes);
8632 createCXTUResourceUsageEntry(*entries,
8633 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8634 (unsigned long) sizes.mmap_bytes);
8635 }
8636
8637 // How much memory is being used by the Preprocessor?
8638 Preprocessor &pp = astUnit->getPreprocessor();
8639 createCXTUResourceUsageEntry(*entries,
8640 CXTUResourceUsage_Preprocessor,
8641 pp.getTotalMemory());
8642
8643 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8644 createCXTUResourceUsageEntry(*entries,
8645 CXTUResourceUsage_PreprocessingRecord,
8646 pRec->getTotalMemory());
8647 }
8648
8649 createCXTUResourceUsageEntry(*entries,
8650 CXTUResourceUsage_Preprocessor_HeaderSearch,
8651 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008652
Guy Benyei11169dd2012-12-18 14:30:41 +00008653 CXTUResourceUsage usage = { (void*) entries.get(),
8654 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008655 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008656 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008657 return usage;
8658}
8659
8660void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8661 if (usage.data)
8662 delete (MemUsageEntries*) usage.data;
8663}
8664
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008665CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8666 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008667 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008668 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008669
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008670 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008671 LOG_BAD_TU(TU);
8672 return skipped;
8673 }
8674
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008675 if (!file)
8676 return skipped;
8677
8678 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8679 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8680 if (!ppRec)
8681 return skipped;
8682
8683 ASTContext &Ctx = astUnit->getASTContext();
8684 SourceManager &sm = Ctx.getSourceManager();
8685 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8686 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008687 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008688
8689 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8690 std::vector<SourceRange> wantedRanges;
8691 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8692 i != ei; ++i) {
8693 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8694 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008695 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8696 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008697 }
8698
8699 skipped->count = wantedRanges.size();
8700 skipped->ranges = new CXSourceRange[skipped->count];
8701 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8702 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8703
8704 return skipped;
8705}
8706
Cameron Desrochersd8091282016-08-18 15:43:55 +00008707CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8708 CXSourceRangeList *skipped = new CXSourceRangeList;
8709 skipped->count = 0;
8710 skipped->ranges = nullptr;
8711
8712 if (isNotUsableTU(TU)) {
8713 LOG_BAD_TU(TU);
8714 return skipped;
8715 }
8716
8717 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8718 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8719 if (!ppRec)
8720 return skipped;
8721
8722 ASTContext &Ctx = astUnit->getASTContext();
8723
8724 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8725
8726 skipped->count = SkippedRanges.size();
8727 skipped->ranges = new CXSourceRange[skipped->count];
8728 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8729 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8730
8731 return skipped;
8732}
8733
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008734void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8735 if (ranges) {
8736 delete[] ranges->ranges;
8737 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008738 }
8739}
8740
Guy Benyei11169dd2012-12-18 14:30:41 +00008741void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8742 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8743 for (unsigned I = 0; I != Usage.numEntries; ++I)
8744 fprintf(stderr, " %s: %lu\n",
8745 clang_getTUResourceUsageName(Usage.entries[I].kind),
8746 Usage.entries[I].amount);
8747
8748 clang_disposeCXTUResourceUsage(Usage);
8749}
8750
8751//===----------------------------------------------------------------------===//
8752// Misc. utility functions.
8753//===----------------------------------------------------------------------===//
8754
Richard Smith0a7b2972018-07-03 21:34:13 +00008755/// Default to using our desired 8 MB stack size on "safety" threads.
8756static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008757
8758namespace clang {
8759
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008760bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008761 unsigned Size) {
8762 if (!Size)
8763 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008764 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008765 return CRC.RunSafelyOnThread(Fn, Size);
8766 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008767}
8768
8769unsigned GetSafetyThreadStackSize() {
8770 return SafetyStackThreadSize;
8771}
8772
8773void SetSafetyThreadStackSize(unsigned Value) {
8774 SafetyStackThreadSize = Value;
8775}
8776
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008777}
Guy Benyei11169dd2012-12-18 14:30:41 +00008778
8779void clang::setThreadBackgroundPriority() {
8780 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8781 return;
8782
Nico Weber18cfd9f2019-04-21 19:18:41 +00008783#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008784 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008785#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008786}
8787
8788void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8789 if (!Unit)
8790 return;
8791
8792 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8793 DEnd = Unit->stored_diag_end();
8794 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008795 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008796 CXString Msg = clang_formatDiagnostic(&Diag,
8797 clang_defaultDiagnosticDisplayOptions());
8798 fprintf(stderr, "%s\n", clang_getCString(Msg));
8799 clang_disposeString(Msg);
8800 }
Nico Weber1865df42018-04-27 19:11:14 +00008801#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008802 // On Windows, force a flush, since there may be multiple copies of
8803 // stderr and stdout in the file system, all with different buffers
8804 // but writing to the same device.
8805 fflush(stderr);
8806#endif
8807}
8808
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008809MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8810 SourceLocation MacroDefLoc,
8811 CXTranslationUnit TU){
8812 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008813 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008814 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008815 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008816
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008817 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008818 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008819 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008820 if (MD) {
8821 for (MacroDirective::DefInfo
8822 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8823 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8824 return Def.getMacroInfo();
8825 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008826 }
8827
Craig Topper69186e72014-06-08 08:38:04 +00008828 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008829}
8830
Richard Smith66a81862015-05-04 02:25:31 +00008831const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008832 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008833 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008834 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008835 const IdentifierInfo *II = MacroDef->getName();
8836 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008837 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008838
8839 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8840}
8841
Richard Smith66a81862015-05-04 02:25:31 +00008842MacroDefinitionRecord *
8843cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8844 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008845 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008846 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008847 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008848 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008849
8850 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008851 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008852 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8853 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008854 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008855
8856 // Check that the token is inside the definition and not its argument list.
8857 SourceManager &SM = Unit->getSourceManager();
8858 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008859 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008860 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008861 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008862
8863 Preprocessor &PP = Unit->getPreprocessor();
8864 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8865 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008866 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008867
Alp Toker2d57cea2014-05-17 04:53:25 +00008868 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008869 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008870 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008871
8872 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008873 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008874 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008875
Richard Smith20e883e2015-04-29 23:20:19 +00008876 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008877 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008878 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008879
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008880 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008881}
8882
Richard Smith66a81862015-05-04 02:25:31 +00008883MacroDefinitionRecord *
8884cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8885 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008886 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008887 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008888
8889 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008890 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008891 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008892 Preprocessor &PP = Unit->getPreprocessor();
8893 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008894 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008895 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8896 Token Tok;
8897 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008898 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008899
8900 return checkForMacroInMacroDefinition(MI, Tok, TU);
8901}
8902
Guy Benyei11169dd2012-12-18 14:30:41 +00008903CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008904 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008905}
8906
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008907Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8908 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008909 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008910 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008911 if (Unit->isMainFileAST())
8912 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008913 return *this;
8914 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008915 } else {
8916 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008917 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008918 return *this;
8919}
8920
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008921Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8922 *this << FE->getName();
8923 return *this;
8924}
8925
8926Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8927 CXString cursorName = clang_getCursorDisplayName(cursor);
8928 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8929 clang_disposeString(cursorName);
8930 return *this;
8931}
8932
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008933Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8934 CXFile File;
8935 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008936 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008937 CXString FileName = clang_getFileName(File);
8938 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8939 clang_disposeString(FileName);
8940 return *this;
8941}
8942
8943Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8944 CXSourceLocation BLoc = clang_getRangeStart(range);
8945 CXSourceLocation ELoc = clang_getRangeEnd(range);
8946
8947 CXFile BFile;
8948 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008949 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008950
8951 CXFile EFile;
8952 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008953 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008954
8955 CXString BFileName = clang_getFileName(BFile);
8956 if (BFile == EFile) {
8957 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8958 BLine, BColumn, ELine, EColumn);
8959 } else {
8960 CXString EFileName = clang_getFileName(EFile);
8961 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8962 BLine, BColumn)
8963 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8964 ELine, EColumn);
8965 clang_disposeString(EFileName);
8966 }
8967 clang_disposeString(BFileName);
8968 return *this;
8969}
8970
8971Logger &cxindex::Logger::operator<<(CXString Str) {
8972 *this << clang_getCString(Str);
8973 return *this;
8974}
8975
8976Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8977 LogOS << Fmt;
8978 return *this;
8979}
8980
Benjamin Kramer762bc332019-08-07 14:44:40 +00008981static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00008982
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008983cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00008984 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008985
8986 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8987
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008988 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008989 OS << "[libclang:" << Name << ':';
8990
Alp Toker1a86ad22014-07-06 06:24:00 +00008991#ifdef USE_DARWIN_THREADS
8992 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008993 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8994 OS << tid << ':';
8995#endif
8996
8997 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8998 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008999 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009000
9001 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00009002 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009003 OS << "--------------------------------------------------\n";
9004 }
9005}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00009006
9007#ifdef CLANG_TOOL_EXTRA_BUILD
9008// This anchor is used to force the linker to link the clang-tidy plugin.
9009extern volatile int ClangTidyPluginAnchorSource;
9010static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9011 ClangTidyPluginAnchorSource;
9012
9013// This anchor is used to force the linker to link the clang-include-fixer
9014// plugin.
9015extern volatile int ClangIncludeFixerPluginAnchorSource;
9016static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9017 ClangIncludeFixerPluginAnchorSource;
9018#endif