blob: 5df02d51d0369594afbd6201816366d171057dae [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);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002055 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002056 void VisitOMPDistributeParallelForDirective(
2057 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002058 void VisitOMPDistributeParallelForSimdDirective(
2059 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002060 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002061 void VisitOMPTargetParallelForSimdDirective(
2062 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002063 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002064 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002065 void VisitOMPTeamsDistributeSimdDirective(
2066 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002067 void VisitOMPTeamsDistributeParallelForSimdDirective(
2068 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002069 void VisitOMPTeamsDistributeParallelForDirective(
2070 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002071 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002072 void VisitOMPTargetTeamsDistributeDirective(
2073 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002074 void VisitOMPTargetTeamsDistributeParallelForDirective(
2075 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002076 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2077 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002078 void VisitOMPTargetTeamsDistributeSimdDirective(
2079 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002080
Guy Benyei11169dd2012-12-18 14:30:41 +00002081private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002082 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002083 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002084 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2085 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002086 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2087 void AddStmt(const Stmt *S);
2088 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002089 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002090 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002091 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002092};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002093} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002094
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002095void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 // 'S' should always be non-null, since it comes from the
2097 // statement we are visiting.
2098 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2099}
2100
2101void
2102EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2103 if (Qualifier)
2104 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2105}
2106
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002107void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002108 if (S)
2109 WL.push_back(StmtVisit(S, Parent));
2110}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002111void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002112 if (D)
2113 WL.push_back(DeclVisit(D, Parent, isFirst));
2114}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002115void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2116 unsigned NumTemplateArgs) {
2117 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002118}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002119void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002120 if (D)
2121 WL.push_back(MemberRefVisit(D, L, Parent));
2122}
2123void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2124 if (TI)
2125 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2126 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002127void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002128 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002129 for (const Stmt *SubStmt : S->children()) {
2130 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002131 }
2132 if (size == WL.size())
2133 return;
2134 // Now reverse the entries we just added. This will match the DFS
2135 // ordering performed by the worklist.
2136 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2137 std::reverse(I, E);
2138}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002139namespace {
2140class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2141 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002142 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002143 template <typename T>
2144 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002145public:
2146 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2147#define OPENMP_CLAUSE(Name, Class) \
2148 void Visit##Class(const Class *C);
2149#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002150 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002151 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002152};
2153
Alexey Bataev3392d762016-02-16 11:18:12 +00002154void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2155 const OMPClauseWithPreInit *C) {
2156 Visitor->AddStmt(C->getPreInitStmt());
2157}
2158
Alexey Bataev005248a2016-02-25 05:25:57 +00002159void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2160 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002161 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002162 Visitor->AddStmt(C->getPostUpdateExpr());
2163}
2164
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002165void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002166 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002167 Visitor->AddStmt(C->getCondition());
2168}
2169
Alexey Bataev3778b602014-07-17 07:32:53 +00002170void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2171 Visitor->AddStmt(C->getCondition());
2172}
2173
Alexey Bataev568a8332014-03-06 06:15:19 +00002174void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002175 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002176 Visitor->AddStmt(C->getNumThreads());
2177}
2178
Alexey Bataev62c87d22014-03-21 04:51:18 +00002179void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2180 Visitor->AddStmt(C->getSafelen());
2181}
2182
Alexey Bataev66b15b52015-08-21 11:14:16 +00002183void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2184 Visitor->AddStmt(C->getSimdlen());
2185}
2186
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002187void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2188 Visitor->AddStmt(C->getAllocator());
2189}
2190
Alexander Musman8bd31e62014-05-27 15:12:19 +00002191void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2192 Visitor->AddStmt(C->getNumForLoops());
2193}
2194
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002195void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002196
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002197void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2198
Alexey Bataev56dafe82014-06-20 07:16:17 +00002199void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002200 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002201 Visitor->AddStmt(C->getChunkSize());
2202}
2203
Alexey Bataev10e775f2015-07-30 11:36:16 +00002204void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2205 Visitor->AddStmt(C->getNumForLoops());
2206}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002207
Alexey Bataev236070f2014-06-20 11:19:47 +00002208void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2209
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002210void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2211
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002212void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2213
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002214void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2215
Alexey Bataevdea47612014-07-23 07:46:59 +00002216void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2217
Alexey Bataev67a4f222014-07-23 10:25:33 +00002218void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2219
Alexey Bataev459dec02014-07-24 06:46:57 +00002220void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2221
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002222void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2223
Alexey Bataev346265e2015-09-25 10:37:12 +00002224void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2225
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002226void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2227
Alexey Bataevb825de12015-12-07 10:51:44 +00002228void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2229
Kelvin Li1408f912018-09-26 04:28:39 +00002230void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2231 const OMPUnifiedAddressClause *) {}
2232
Patrick Lyster4a370b92018-10-01 13:47:43 +00002233void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2234 const OMPUnifiedSharedMemoryClause *) {}
2235
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002236void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2237 const OMPReverseOffloadClause *) {}
2238
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002239void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2240 const OMPDynamicAllocatorsClause *) {}
2241
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002242void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2243 const OMPAtomicDefaultMemOrderClause *) {}
2244
Michael Wonge710d542015-08-07 16:16:36 +00002245void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2246 Visitor->AddStmt(C->getDevice());
2247}
2248
Kelvin Li099bb8c2015-11-24 20:50:12 +00002249void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002250 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002251 Visitor->AddStmt(C->getNumTeams());
2252}
2253
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002254void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002255 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002256 Visitor->AddStmt(C->getThreadLimit());
2257}
2258
Alexey Bataeva0569352015-12-01 10:17:31 +00002259void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2260 Visitor->AddStmt(C->getPriority());
2261}
2262
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002263void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2264 Visitor->AddStmt(C->getGrainsize());
2265}
2266
Alexey Bataev382967a2015-12-08 12:06:20 +00002267void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2268 Visitor->AddStmt(C->getNumTasks());
2269}
2270
Alexey Bataev28c75412015-12-15 08:19:24 +00002271void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2272 Visitor->AddStmt(C->getHint());
2273}
2274
Alexey Bataev756c1962013-09-24 03:17:45 +00002275template<typename T>
2276void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002277 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002278 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002279 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002280}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002281
Alexey Bataeve04483e2019-03-27 14:14:31 +00002282void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2283 VisitOMPClauseList(C);
2284 Visitor->AddStmt(C->getAllocator());
2285}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002286void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002287 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002288 for (const auto *E : C->private_copies()) {
2289 Visitor->AddStmt(E);
2290 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002291}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002292void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2293 const OMPFirstprivateClause *C) {
2294 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002295 VisitOMPClauseWithPreInit(C);
2296 for (const auto *E : C->private_copies()) {
2297 Visitor->AddStmt(E);
2298 }
2299 for (const auto *E : C->inits()) {
2300 Visitor->AddStmt(E);
2301 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002302}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002303void OMPClauseEnqueue::VisitOMPLastprivateClause(
2304 const OMPLastprivateClause *C) {
2305 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002306 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002307 for (auto *E : C->private_copies()) {
2308 Visitor->AddStmt(E);
2309 }
2310 for (auto *E : C->source_exprs()) {
2311 Visitor->AddStmt(E);
2312 }
2313 for (auto *E : C->destination_exprs()) {
2314 Visitor->AddStmt(E);
2315 }
2316 for (auto *E : C->assignment_ops()) {
2317 Visitor->AddStmt(E);
2318 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002319}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002320void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002321 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002322}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002323void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2324 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002325 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002326 for (auto *E : C->privates()) {
2327 Visitor->AddStmt(E);
2328 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002329 for (auto *E : C->lhs_exprs()) {
2330 Visitor->AddStmt(E);
2331 }
2332 for (auto *E : C->rhs_exprs()) {
2333 Visitor->AddStmt(E);
2334 }
2335 for (auto *E : C->reduction_ops()) {
2336 Visitor->AddStmt(E);
2337 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002338}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002339void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2340 const OMPTaskReductionClause *C) {
2341 VisitOMPClauseList(C);
2342 VisitOMPClauseWithPostUpdate(C);
2343 for (auto *E : C->privates()) {
2344 Visitor->AddStmt(E);
2345 }
2346 for (auto *E : C->lhs_exprs()) {
2347 Visitor->AddStmt(E);
2348 }
2349 for (auto *E : C->rhs_exprs()) {
2350 Visitor->AddStmt(E);
2351 }
2352 for (auto *E : C->reduction_ops()) {
2353 Visitor->AddStmt(E);
2354 }
2355}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002356void OMPClauseEnqueue::VisitOMPInReductionClause(
2357 const OMPInReductionClause *C) {
2358 VisitOMPClauseList(C);
2359 VisitOMPClauseWithPostUpdate(C);
2360 for (auto *E : C->privates()) {
2361 Visitor->AddStmt(E);
2362 }
2363 for (auto *E : C->lhs_exprs()) {
2364 Visitor->AddStmt(E);
2365 }
2366 for (auto *E : C->rhs_exprs()) {
2367 Visitor->AddStmt(E);
2368 }
2369 for (auto *E : C->reduction_ops()) {
2370 Visitor->AddStmt(E);
2371 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002372 for (auto *E : C->taskgroup_descriptors())
2373 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002374}
Alexander Musman8dba6642014-04-22 13:09:42 +00002375void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2376 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002377 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002378 for (const auto *E : C->privates()) {
2379 Visitor->AddStmt(E);
2380 }
Alexander Musman3276a272015-03-21 10:12:56 +00002381 for (const auto *E : C->inits()) {
2382 Visitor->AddStmt(E);
2383 }
2384 for (const auto *E : C->updates()) {
2385 Visitor->AddStmt(E);
2386 }
2387 for (const auto *E : C->finals()) {
2388 Visitor->AddStmt(E);
2389 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002390 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002391 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002392}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002393void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2394 VisitOMPClauseList(C);
2395 Visitor->AddStmt(C->getAlignment());
2396}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002397void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2398 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002399 for (auto *E : C->source_exprs()) {
2400 Visitor->AddStmt(E);
2401 }
2402 for (auto *E : C->destination_exprs()) {
2403 Visitor->AddStmt(E);
2404 }
2405 for (auto *E : C->assignment_ops()) {
2406 Visitor->AddStmt(E);
2407 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002408}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002409void
2410OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2411 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002412 for (auto *E : C->source_exprs()) {
2413 Visitor->AddStmt(E);
2414 }
2415 for (auto *E : C->destination_exprs()) {
2416 Visitor->AddStmt(E);
2417 }
2418 for (auto *E : C->assignment_ops()) {
2419 Visitor->AddStmt(E);
2420 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002421}
Alexey Bataev6125da92014-07-21 11:26:11 +00002422void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2423 VisitOMPClauseList(C);
2424}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002425void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2426 VisitOMPClauseList(C);
2427}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002428void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2429 VisitOMPClauseList(C);
2430}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002431void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2432 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002433 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002434 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002435}
Alexey Bataev3392d762016-02-16 11:18:12 +00002436void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2437 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002438void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2439 VisitOMPClauseList(C);
2440}
Samuel Antaoec172c62016-05-26 17:49:04 +00002441void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2442 VisitOMPClauseList(C);
2443}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002444void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2445 VisitOMPClauseList(C);
2446}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002447void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2448 VisitOMPClauseList(C);
2449}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002450}
Alexey Bataev756c1962013-09-24 03:17:45 +00002451
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002452void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2453 unsigned size = WL.size();
2454 OMPClauseEnqueue Visitor(this);
2455 Visitor.Visit(S);
2456 if (size == WL.size())
2457 return;
2458 // Now reverse the entries we just added. This will match the DFS
2459 // ordering performed by the worklist.
2460 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2461 std::reverse(I, E);
2462}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002463void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2465}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002466void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 AddDecl(B->getBlockDecl());
2468}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002469void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 EnqueueChildren(E);
2471 AddTypeLoc(E->getTypeSourceInfo());
2472}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002473void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002474 for (auto &I : llvm::reverse(S->body()))
2475 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002476}
2477void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002478VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 AddStmt(S->getSubStmt());
2480 AddDeclarationNameInfo(S);
2481 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2482 AddNestedNameSpecifierLoc(QualifierLoc);
2483}
2484
2485void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002486VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002487 if (E->hasExplicitTemplateArgs())
2488 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 AddDeclarationNameInfo(E);
2490 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2491 AddNestedNameSpecifierLoc(QualifierLoc);
2492 if (!E->isImplicitAccess())
2493 AddStmt(E->getBase());
2494}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002495void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 // Enqueue the initializer , if any.
2497 AddStmt(E->getInitializer());
2498 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002499 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 // Enqueue the allocated type.
2501 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2502 // Enqueue the placement arguments.
2503 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2504 AddStmt(E->getPlacementArg(I-1));
2505}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002506void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2508 AddStmt(CE->getArg(I-1));
2509 AddStmt(CE->getCallee());
2510 AddStmt(CE->getArg(0));
2511}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002512void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2513 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 // Visit the name of the type being destroyed.
2515 AddTypeLoc(E->getDestroyedTypeInfo());
2516 // Visit the scope type that looks disturbingly like the nested-name-specifier
2517 // but isn't.
2518 AddTypeLoc(E->getScopeTypeInfo());
2519 // Visit the nested-name-specifier.
2520 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2521 AddNestedNameSpecifierLoc(QualifierLoc);
2522 // Visit base expression.
2523 AddStmt(E->getBase());
2524}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002525void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2526 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 AddTypeLoc(E->getTypeSourceInfo());
2528}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002529void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2530 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 EnqueueChildren(E);
2532 AddTypeLoc(E->getTypeSourceInfo());
2533}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 EnqueueChildren(E);
2536 if (E->isTypeOperand())
2537 AddTypeLoc(E->getTypeOperandSourceInfo());
2538}
2539
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002540void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2541 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 EnqueueChildren(E);
2543 AddTypeLoc(E->getTypeSourceInfo());
2544}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002545void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 EnqueueChildren(E);
2547 if (E->isTypeOperand())
2548 AddTypeLoc(E->getTypeOperandSourceInfo());
2549}
2550
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002551void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 EnqueueChildren(S);
2553 AddDecl(S->getExceptionDecl());
2554}
2555
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002556void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002557 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002558 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002559 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002560}
2561
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002562void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002563 if (DR->hasExplicitTemplateArgs())
2564 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 WL.push_back(DeclRefExprParts(DR, Parent));
2566}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002567void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2568 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002569 if (E->hasExplicitTemplateArgs())
2570 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 AddDeclarationNameInfo(E);
2572 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2573}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002574void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 unsigned size = WL.size();
2576 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002577 for (const auto *D : S->decls()) {
2578 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 isFirst = false;
2580 }
2581 if (size == WL.size())
2582 return;
2583 // Now reverse the entries we just added. This will match the DFS
2584 // ordering performed by the worklist.
2585 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2586 std::reverse(I, E);
2587}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002588void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002590 for (const DesignatedInitExpr::Designator &D :
2591 llvm::reverse(E->designators())) {
2592 if (D.isFieldDesignator()) {
2593 if (FieldDecl *Field = D.getField())
2594 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 continue;
2596 }
David Majnemerf7e36092016-06-23 00:15:04 +00002597 if (D.isArrayDesignator()) {
2598 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 continue;
2600 }
David Majnemerf7e36092016-06-23 00:15:04 +00002601 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2602 AddStmt(E->getArrayRangeEnd(D));
2603 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 }
2605}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002606void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 EnqueueChildren(E);
2608 AddTypeLoc(E->getTypeInfoAsWritten());
2609}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002610void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 AddStmt(FS->getBody());
2612 AddStmt(FS->getInc());
2613 AddStmt(FS->getCond());
2614 AddDecl(FS->getConditionVariable());
2615 AddStmt(FS->getInit());
2616}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002617void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2619}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002620void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 AddStmt(If->getElse());
2622 AddStmt(If->getThen());
2623 AddStmt(If->getCond());
2624 AddDecl(If->getConditionVariable());
2625}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002626void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 // We care about the syntactic form of the initializer list, only.
2628 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2629 IE = Syntactic;
2630 EnqueueChildren(IE);
2631}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002632void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 WL.push_back(MemberExprParts(M, Parent));
2634
2635 // If the base of the member access expression is an implicit 'this', don't
2636 // visit it.
2637 // FIXME: If we ever want to show these implicit accesses, this will be
2638 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002639 if (M->isImplicitAccess())
2640 return;
2641
2642 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002643 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002644 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2645 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2646 if (FD->isAnonymousStructOrUnion()) {
2647 AddStmt(SubME->getBase());
2648 return;
2649 }
2650 }
2651 }
2652
2653 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002654}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002655void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 AddTypeLoc(E->getEncodedTypeSourceInfo());
2657}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002658void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 EnqueueChildren(M);
2660 AddTypeLoc(M->getClassReceiverTypeInfo());
2661}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002662void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 // Visit the components of the offsetof expression.
2664 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 const OffsetOfNode &Node = E->getComponent(I-1);
2666 switch (Node.getKind()) {
2667 case OffsetOfNode::Array:
2668 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2669 break;
2670 case OffsetOfNode::Field:
2671 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2672 break;
2673 case OffsetOfNode::Identifier:
2674 case OffsetOfNode::Base:
2675 continue;
2676 }
2677 }
2678 // Visit the type into which we're computing the offset.
2679 AddTypeLoc(E->getTypeSourceInfo());
2680}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002681void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002682 if (E->hasExplicitTemplateArgs())
2683 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 WL.push_back(OverloadExprParts(E, Parent));
2685}
2686void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002687 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 EnqueueChildren(E);
2689 if (E->isArgumentType())
2690 AddTypeLoc(E->getArgumentTypeInfo());
2691}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002692void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 EnqueueChildren(S);
2694}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002695void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 AddStmt(S->getBody());
2697 AddStmt(S->getCond());
2698 AddDecl(S->getConditionVariable());
2699}
2700
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002701void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 AddStmt(W->getBody());
2703 AddStmt(W->getCond());
2704 AddDecl(W->getConditionVariable());
2705}
2706
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002707void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 for (unsigned I = E->getNumArgs(); I > 0; --I)
2709 AddTypeLoc(E->getArg(I-1));
2710}
2711
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002712void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 AddTypeLoc(E->getQueriedTypeSourceInfo());
2714}
2715
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002716void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 EnqueueChildren(E);
2718}
2719
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002720void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 VisitOverloadExpr(U);
2722 if (!U->isImplicitAccess())
2723 AddStmt(U->getBase());
2724}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002725void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 AddStmt(E->getSubExpr());
2727 AddTypeLoc(E->getWrittenTypeInfo());
2728}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002729void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 WL.push_back(SizeOfPackExprParts(E, Parent));
2731}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002732void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 // If the opaque value has a source expression, just transparently
2734 // visit that. This is useful for (e.g.) pseudo-object expressions.
2735 if (Expr *SourceExpr = E->getSourceExpr())
2736 return Visit(SourceExpr);
2737}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002738void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 AddStmt(E->getBody());
2740 WL.push_back(LambdaExprParts(E, Parent));
2741}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002742void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 // Treat the expression like its syntactic form.
2744 Visit(E->getSyntacticForm());
2745}
2746
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002747void EnqueueVisitor::VisitOMPExecutableDirective(
2748 const OMPExecutableDirective *D) {
2749 EnqueueChildren(D);
2750 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2751 E = D->clauses().end();
2752 I != E; ++I)
2753 EnqueueChildren(*I);
2754}
2755
Alexander Musman3aaab662014-08-19 11:27:13 +00002756void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2757 VisitOMPExecutableDirective(D);
2758}
2759
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002760void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2761 VisitOMPExecutableDirective(D);
2762}
2763
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002764void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002765 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002766}
2767
Alexey Bataevf29276e2014-06-18 04:14:57 +00002768void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002769 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002770}
2771
Alexander Musmanf82886e2014-09-18 05:12:34 +00002772void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2773 VisitOMPLoopDirective(D);
2774}
2775
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002776void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2777 VisitOMPExecutableDirective(D);
2778}
2779
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002780void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2781 VisitOMPExecutableDirective(D);
2782}
2783
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002784void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2785 VisitOMPExecutableDirective(D);
2786}
2787
Alexander Musman80c22892014-07-17 08:54:58 +00002788void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2789 VisitOMPExecutableDirective(D);
2790}
2791
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002792void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2793 VisitOMPExecutableDirective(D);
2794 AddDeclarationNameInfo(D);
2795}
2796
Alexey Bataev4acb8592014-07-07 13:01:15 +00002797void
2798EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002799 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002800}
2801
Alexander Musmane4e893b2014-09-23 09:33:00 +00002802void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2803 const OMPParallelForSimdDirective *D) {
2804 VisitOMPLoopDirective(D);
2805}
2806
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002807void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2808 const OMPParallelSectionsDirective *D) {
2809 VisitOMPExecutableDirective(D);
2810}
2811
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002812void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2813 VisitOMPExecutableDirective(D);
2814}
2815
Alexey Bataev68446b72014-07-18 07:47:19 +00002816void
2817EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819}
2820
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002821void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2822 VisitOMPExecutableDirective(D);
2823}
2824
Alexey Bataev2df347a2014-07-18 10:17:07 +00002825void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2826 VisitOMPExecutableDirective(D);
2827}
2828
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002829void EnqueueVisitor::VisitOMPTaskgroupDirective(
2830 const OMPTaskgroupDirective *D) {
2831 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002832 if (const Expr *E = D->getReductionRef())
2833 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002834}
2835
Alexey Bataev6125da92014-07-21 11:26:11 +00002836void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2837 VisitOMPExecutableDirective(D);
2838}
2839
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002840void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2841 VisitOMPExecutableDirective(D);
2842}
2843
Alexey Bataev0162e452014-07-22 10:10:35 +00002844void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2845 VisitOMPExecutableDirective(D);
2846}
2847
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002848void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2849 VisitOMPExecutableDirective(D);
2850}
2851
Michael Wong65f367f2015-07-21 13:44:28 +00002852void EnqueueVisitor::VisitOMPTargetDataDirective(const
2853 OMPTargetDataDirective *D) {
2854 VisitOMPExecutableDirective(D);
2855}
2856
Samuel Antaodf67fc42016-01-19 19:15:56 +00002857void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2858 const OMPTargetEnterDataDirective *D) {
2859 VisitOMPExecutableDirective(D);
2860}
2861
Samuel Antao72590762016-01-19 20:04:50 +00002862void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2863 const OMPTargetExitDataDirective *D) {
2864 VisitOMPExecutableDirective(D);
2865}
2866
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002867void EnqueueVisitor::VisitOMPTargetParallelDirective(
2868 const OMPTargetParallelDirective *D) {
2869 VisitOMPExecutableDirective(D);
2870}
2871
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002872void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2873 const OMPTargetParallelForDirective *D) {
2874 VisitOMPLoopDirective(D);
2875}
2876
Alexey Bataev13314bf2014-10-09 04:18:56 +00002877void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2878 VisitOMPExecutableDirective(D);
2879}
2880
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002881void EnqueueVisitor::VisitOMPCancellationPointDirective(
2882 const OMPCancellationPointDirective *D) {
2883 VisitOMPExecutableDirective(D);
2884}
2885
Alexey Bataev80909872015-07-02 11:25:17 +00002886void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2887 VisitOMPExecutableDirective(D);
2888}
2889
Alexey Bataev49f6e782015-12-01 04:18:41 +00002890void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2891 VisitOMPLoopDirective(D);
2892}
2893
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002894void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2895 const OMPTaskLoopSimdDirective *D) {
2896 VisitOMPLoopDirective(D);
2897}
2898
Alexey Bataev60e51c42019-10-10 20:13:02 +00002899void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2900 const OMPMasterTaskLoopDirective *D) {
2901 VisitOMPLoopDirective(D);
2902}
2903
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002904void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2905 const OMPMasterTaskLoopSimdDirective *D) {
2906 VisitOMPLoopDirective(D);
2907}
2908
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002909void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2910 const OMPParallelMasterTaskLoopDirective *D) {
2911 VisitOMPLoopDirective(D);
2912}
2913
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002914void EnqueueVisitor::VisitOMPDistributeDirective(
2915 const OMPDistributeDirective *D) {
2916 VisitOMPLoopDirective(D);
2917}
2918
Carlo Bertolli9925f152016-06-27 14:55:37 +00002919void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2920 const OMPDistributeParallelForDirective *D) {
2921 VisitOMPLoopDirective(D);
2922}
2923
Kelvin Li4a39add2016-07-05 05:00:15 +00002924void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2925 const OMPDistributeParallelForSimdDirective *D) {
2926 VisitOMPLoopDirective(D);
2927}
2928
Kelvin Li787f3fc2016-07-06 04:45:38 +00002929void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2930 const OMPDistributeSimdDirective *D) {
2931 VisitOMPLoopDirective(D);
2932}
2933
Kelvin Lia579b912016-07-14 02:54:56 +00002934void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2935 const OMPTargetParallelForSimdDirective *D) {
2936 VisitOMPLoopDirective(D);
2937}
2938
Kelvin Li986330c2016-07-20 22:57:10 +00002939void EnqueueVisitor::VisitOMPTargetSimdDirective(
2940 const OMPTargetSimdDirective *D) {
2941 VisitOMPLoopDirective(D);
2942}
2943
Kelvin Li02532872016-08-05 14:37:37 +00002944void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2945 const OMPTeamsDistributeDirective *D) {
2946 VisitOMPLoopDirective(D);
2947}
2948
Kelvin Li4e325f72016-10-25 12:50:55 +00002949void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2950 const OMPTeamsDistributeSimdDirective *D) {
2951 VisitOMPLoopDirective(D);
2952}
2953
Kelvin Li579e41c2016-11-30 23:51:03 +00002954void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2955 const OMPTeamsDistributeParallelForSimdDirective *D) {
2956 VisitOMPLoopDirective(D);
2957}
2958
Kelvin Li7ade93f2016-12-09 03:24:30 +00002959void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2960 const OMPTeamsDistributeParallelForDirective *D) {
2961 VisitOMPLoopDirective(D);
2962}
2963
Kelvin Libf594a52016-12-17 05:48:59 +00002964void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2965 const OMPTargetTeamsDirective *D) {
2966 VisitOMPExecutableDirective(D);
2967}
2968
Kelvin Li83c451e2016-12-25 04:52:54 +00002969void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2970 const OMPTargetTeamsDistributeDirective *D) {
2971 VisitOMPLoopDirective(D);
2972}
2973
Kelvin Li80e8f562016-12-29 22:16:30 +00002974void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2975 const OMPTargetTeamsDistributeParallelForDirective *D) {
2976 VisitOMPLoopDirective(D);
2977}
2978
Kelvin Li1851df52017-01-03 05:23:48 +00002979void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2980 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2981 VisitOMPLoopDirective(D);
2982}
2983
Kelvin Lida681182017-01-10 18:08:18 +00002984void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2985 const OMPTargetTeamsDistributeSimdDirective *D) {
2986 VisitOMPLoopDirective(D);
2987}
2988
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002989void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002990 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2991}
2992
2993bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2994 if (RegionOfInterest.isValid()) {
2995 SourceRange Range = getRawCursorExtent(C);
2996 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2997 return false;
2998 }
2999 return true;
3000}
3001
3002bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3003 while (!WL.empty()) {
3004 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003005 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003006
3007 // Set the Parent field, then back to its old value once we're done.
3008 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3009
3010 switch (LI.getKind()) {
3011 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003012 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 if (!D)
3014 continue;
3015
3016 // For now, perform default visitation for Decls.
3017 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3018 cast<DeclVisit>(&LI)->isFirst())))
3019 return true;
3020
3021 continue;
3022 }
3023 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003024 for (const TemplateArgumentLoc &Arg :
3025 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3026 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 return true;
3028 }
3029 continue;
3030 }
3031 case VisitorJob::TypeLocVisitKind: {
3032 // Perform default visitation for TypeLocs.
3033 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3034 return true;
3035 continue;
3036 }
3037 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003038 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 if (LabelStmt *stmt = LS->getStmt()) {
3040 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3041 TU))) {
3042 return true;
3043 }
3044 }
3045 continue;
3046 }
3047
3048 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3049 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3050 if (VisitNestedNameSpecifierLoc(V->get()))
3051 return true;
3052 continue;
3053 }
3054
3055 case VisitorJob::DeclarationNameInfoVisitKind: {
3056 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3057 ->get()))
3058 return true;
3059 continue;
3060 }
3061 case VisitorJob::MemberRefVisitKind: {
3062 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3063 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3064 return true;
3065 continue;
3066 }
3067 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003068 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 if (!S)
3070 continue;
3071
3072 // Update the current cursor.
3073 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3074 if (!IsInRegionOfInterest(Cursor))
3075 continue;
3076 switch (Visitor(Cursor, Parent, ClientData)) {
3077 case CXChildVisit_Break: return true;
3078 case CXChildVisit_Continue: break;
3079 case CXChildVisit_Recurse:
3080 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003081 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 EnqueueWorkList(WL, S);
3083 break;
3084 }
3085 continue;
3086 }
3087 case VisitorJob::MemberExprPartsKind: {
3088 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003089 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003090
3091 // Visit the nested-name-specifier
3092 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3093 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3094 return true;
3095
3096 // Visit the declaration name.
3097 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3098 return true;
3099
3100 // Visit the explicitly-specified template arguments, if any.
3101 if (M->hasExplicitTemplateArgs()) {
3102 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3103 *ArgEnd = Arg + M->getNumTemplateArgs();
3104 Arg != ArgEnd; ++Arg) {
3105 if (VisitTemplateArgumentLoc(*Arg))
3106 return true;
3107 }
3108 }
3109 continue;
3110 }
3111 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003112 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 // Visit nested-name-specifier, if present.
3114 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3115 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3116 return true;
3117 // Visit declaration name.
3118 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3119 return true;
3120 continue;
3121 }
3122 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003123 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 // Visit the nested-name-specifier.
3125 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3126 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3127 return true;
3128 // Visit the declaration name.
3129 if (VisitDeclarationNameInfo(O->getNameInfo()))
3130 return true;
3131 // Visit the overloaded declaration reference.
3132 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3133 return true;
3134 continue;
3135 }
3136 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003137 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 NamedDecl *Pack = E->getPack();
3139 if (isa<TemplateTypeParmDecl>(Pack)) {
3140 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3141 E->getPackLoc(), TU)))
3142 return true;
3143
3144 continue;
3145 }
3146
3147 if (isa<TemplateTemplateParmDecl>(Pack)) {
3148 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3149 E->getPackLoc(), TU)))
3150 return true;
3151
3152 continue;
3153 }
3154
3155 // Non-type template parameter packs and function parameter packs are
3156 // treated like DeclRefExpr cursors.
3157 continue;
3158 }
3159
3160 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003161 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003162 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3164 CEnd = E->explicit_capture_end();
3165 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003166 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003168
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3170 C->getLocation(),
3171 TU)))
3172 return true;
3173 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003174 // Visit init captures
3175 for (auto InitExpr : E->capture_inits()) {
3176 if (Visit(InitExpr))
3177 return true;
3178 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003179
Haojian Wuef87c262018-12-18 15:29:12 +00003180 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003181 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003182 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3183 if (E->hasExplicitParameters()) {
3184 // Visit parameters.
3185 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3186 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003188 }
3189 if (E->hasExplicitResultType()) {
3190 // Visit result type.
3191 if (Visit(Proto.getReturnLoc()))
3192 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 }
3194 }
3195 break;
3196 }
3197
3198 case VisitorJob::PostChildrenVisitKind:
3199 if (PostChildrenVisitor(Parent, ClientData))
3200 return true;
3201 break;
3202 }
3203 }
3204 return false;
3205}
3206
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003207bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003208 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 if (!WorkListFreeList.empty()) {
3210 WL = WorkListFreeList.back();
3211 WL->clear();
3212 WorkListFreeList.pop_back();
3213 }
3214 else {
3215 WL = new VisitorWorkList();
3216 WorkListCache.push_back(WL);
3217 }
3218 EnqueueWorkList(*WL, S);
3219 bool result = RunVisitorWorkList(*WL);
3220 WorkListFreeList.push_back(WL);
3221 return result;
3222}
3223
3224namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003225typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003226RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3227 const DeclarationNameInfo &NI, SourceRange QLoc,
3228 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3230 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3231 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3232
3233 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3234
3235 RefNamePieces Pieces;
3236
3237 if (WantQualifier && QLoc.isValid())
3238 Pieces.push_back(QLoc);
3239
3240 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3241 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003242
3243 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3244 Pieces.push_back(*TemplateArgsLoc);
3245
Guy Benyei11169dd2012-12-18 14:30:41 +00003246 if (Kind == DeclarationName::CXXOperatorName) {
3247 Pieces.push_back(SourceLocation::getFromRawEncoding(
3248 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3249 Pieces.push_back(SourceLocation::getFromRawEncoding(
3250 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3251 }
3252
3253 if (WantSinglePiece) {
3254 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3255 Pieces.clear();
3256 Pieces.push_back(R);
3257 }
3258
3259 return Pieces;
3260}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003261}
Guy Benyei11169dd2012-12-18 14:30:41 +00003262
3263//===----------------------------------------------------------------------===//
3264// Misc. API hooks.
3265//===----------------------------------------------------------------------===//
3266
Chandler Carruth66660742014-06-27 16:37:27 +00003267namespace {
3268struct RegisterFatalErrorHandler {
3269 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003270 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003271 }
3272};
3273}
3274
3275static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3276
Guy Benyei11169dd2012-12-18 14:30:41 +00003277CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3278 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 // We use crash recovery to make some of our APIs more reliable, implicitly
3280 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003281 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3282 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003283
Chandler Carruth66660742014-06-27 16:37:27 +00003284 // Look through the managed static to trigger construction of the managed
3285 // static which registers our fatal error handler. This ensures it is only
3286 // registered once.
3287 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003288
Adrian Prantlbc068582015-07-08 01:00:30 +00003289 // Initialize targets for clang module support.
3290 llvm::InitializeAllTargets();
3291 llvm::InitializeAllTargetMCs();
3292 llvm::InitializeAllAsmPrinters();
3293 llvm::InitializeAllAsmParsers();
3294
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003295 CIndexer *CIdxr = new CIndexer();
3296
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 if (excludeDeclarationsFromPCH)
3298 CIdxr->setOnlyLocalDecls();
3299 if (displayDiagnostics)
3300 CIdxr->setDisplayDiagnostics();
3301
3302 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3303 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3304 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3305 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3306 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3307 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3308
3309 return CIdxr;
3310}
3311
3312void clang_disposeIndex(CXIndex CIdx) {
3313 if (CIdx)
3314 delete static_cast<CIndexer *>(CIdx);
3315}
3316
3317void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3318 if (CIdx)
3319 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3320}
3321
3322unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3323 if (CIdx)
3324 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3325 return 0;
3326}
3327
Alex Lorenz08615792017-12-04 21:56:36 +00003328void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3329 const char *Path) {
3330 if (CIdx)
3331 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3332}
3333
Guy Benyei11169dd2012-12-18 14:30:41 +00003334void clang_toggleCrashRecovery(unsigned isEnabled) {
3335 if (isEnabled)
3336 llvm::CrashRecoveryContext::Enable();
3337 else
3338 llvm::CrashRecoveryContext::Disable();
3339}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003340
Guy Benyei11169dd2012-12-18 14:30:41 +00003341CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3342 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003343 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003344 enum CXErrorCode Result =
3345 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003346 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003347 assert((TU && Result == CXError_Success) ||
3348 (!TU && Result != CXError_Success));
3349 return TU;
3350}
3351
3352enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3353 const char *ast_filename,
3354 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003355 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003356 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003357
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003358 if (!CIdx || !ast_filename || !out_TU)
3359 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003360
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003361 LOG_FUNC_SECTION {
3362 *Log << ast_filename;
3363 }
3364
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3366 FileSystemOptions FileSystemOpts;
3367
Justin Bognerd512c1e2014-10-15 00:33:06 +00003368 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3369 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003370 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003371 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3372 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003373 FileSystemOpts, /*UseDebugInfo=*/false,
3374 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003375 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003376 /*AllowPCHWithCompilerErrors=*/true,
3377 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003378 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003379 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003380}
3381
3382unsigned clang_defaultEditingTranslationUnitOptions() {
3383 return CXTranslationUnit_PrecompiledPreamble |
3384 CXTranslationUnit_CacheCompletionResults;
3385}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003386
Guy Benyei11169dd2012-12-18 14:30:41 +00003387CXTranslationUnit
3388clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3389 const char *source_filename,
3390 int num_command_line_args,
3391 const char * const *command_line_args,
3392 unsigned num_unsaved_files,
3393 struct CXUnsavedFile *unsaved_files) {
3394 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3395 return clang_parseTranslationUnit(CIdx, source_filename,
3396 command_line_args, num_command_line_args,
3397 unsaved_files, num_unsaved_files,
3398 Options);
3399}
3400
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003401static CXErrorCode
3402clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3403 const char *const *command_line_args,
3404 int num_command_line_args,
3405 ArrayRef<CXUnsavedFile> unsaved_files,
3406 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003407 // Set up the initial return values.
3408 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003409 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003410
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003411 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003412 if (!CIdx || !out_TU)
3413 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003414
Guy Benyei11169dd2012-12-18 14:30:41 +00003415 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3416
3417 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3418 setThreadBackgroundPriority();
3419
3420 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003421 bool CreatePreambleOnFirstParse =
3422 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003423 // FIXME: Add a flag for modules.
3424 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003425 = (options & (CXTranslationUnit_Incomplete |
3426 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003427 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003428 = options & CXTranslationUnit_CacheCompletionResults;
3429 bool IncludeBriefCommentsInCodeCompletion
3430 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003431 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3432 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003433 bool RetainExcludedCB = options &
3434 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003435 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3436 if (options & CXTranslationUnit_SkipFunctionBodies) {
3437 SkipFunctionBodies =
3438 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3439 ? SkipFunctionBodiesScope::Preamble
3440 : SkipFunctionBodiesScope::PreambleAndMainFile;
3441 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003442
3443 // Configure the diagnostics.
3444 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003445 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003446
Manuel Klimek016c0242016-03-01 10:56:19 +00003447 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003448 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003449
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003450 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3451 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3452 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3453
Guy Benyei11169dd2012-12-18 14:30:41 +00003454 // Recover resources if we crash before exiting this function.
3455 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3456 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003457 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003458
Ahmed Charlesb8984322014-03-07 20:03:18 +00003459 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3460 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003461
3462 // Recover resources if we crash before exiting this function.
3463 llvm::CrashRecoveryContextCleanupRegistrar<
3464 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3465
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003466 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003467 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003468 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003469 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003470 }
3471
Ahmed Charlesb8984322014-03-07 20:03:18 +00003472 std::unique_ptr<std::vector<const char *>> Args(
3473 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003474
3475 // Recover resources if we crash before exiting this method.
3476 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3477 ArgsCleanup(Args.get());
3478
3479 // Since the Clang C library is primarily used by batch tools dealing with
3480 // (often very broken) source code, where spell-checking can have a
3481 // significant negative impact on performance (particularly when
3482 // precompiled headers are involved), we disable it by default.
3483 // Only do this if we haven't found a spell-checking-related argument.
3484 bool FoundSpellCheckingArgument = false;
3485 for (int I = 0; I != num_command_line_args; ++I) {
3486 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3487 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3488 FoundSpellCheckingArgument = true;
3489 break;
3490 }
3491 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 Args->insert(Args->end(), command_line_args,
3493 command_line_args + num_command_line_args);
3494
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003495 if (!FoundSpellCheckingArgument)
3496 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3497
Guy Benyei11169dd2012-12-18 14:30:41 +00003498 // The 'source_filename' argument is optional. If the caller does not
3499 // specify it then it is assumed that the source file is specified
3500 // in the actual argument list.
3501 // Put the source file after command_line_args otherwise if '-x' flag is
3502 // present it will be unused.
3503 if (source_filename)
3504 Args->push_back(source_filename);
3505
3506 // Do we need the detailed preprocessing record?
3507 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3508 Args->push_back("-Xclang");
3509 Args->push_back("-detailed-preprocessing-record");
3510 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003511
3512 // Suppress any editor placeholder diagnostics.
3513 Args->push_back("-fallow-editor-placeholders");
3514
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003516 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003517 // Unless the user specified that they want the preamble on the first parse
3518 // set it up to be created on the first reparse. This makes the first parse
3519 // faster, trading for a slower (first) reparse.
3520 unsigned PrecompilePreambleAfterNParses =
3521 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003522
Alex Lorenz08615792017-12-04 21:56:36 +00003523 LibclangInvocationReporter InvocationReporter(
3524 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003525 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3526 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003527 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003528 Args->data(), Args->data() + Args->size(),
3529 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003530 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003531 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003532 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3533 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003534 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003535 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003536 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3537 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003538
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003539 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003540 if (!Unit && !ErrUnit)
3541 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003542
Guy Benyei11169dd2012-12-18 14:30:41 +00003543 if (NumErrors != Diags->getClient()->getNumErrors()) {
3544 // Make sure to check that 'Unit' is non-NULL.
3545 if (CXXIdx->getDisplayDiagnostics())
3546 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3547 }
3548
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003549 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3550 return CXError_ASTReadError;
3551
David Blaikieea4395e2017-01-06 19:49:01 +00003552 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003553 if (CXTranslationUnitImpl *TU = *out_TU) {
3554 TU->ParsingOptions = options;
3555 TU->Arguments.reserve(Args->size());
3556 for (const char *Arg : *Args)
3557 TU->Arguments.push_back(Arg);
3558 return CXError_Success;
3559 }
3560 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003561}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003562
3563CXTranslationUnit
3564clang_parseTranslationUnit(CXIndex CIdx,
3565 const char *source_filename,
3566 const char *const *command_line_args,
3567 int num_command_line_args,
3568 struct CXUnsavedFile *unsaved_files,
3569 unsigned num_unsaved_files,
3570 unsigned options) {
3571 CXTranslationUnit TU;
3572 enum CXErrorCode Result = clang_parseTranslationUnit2(
3573 CIdx, source_filename, command_line_args, num_command_line_args,
3574 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003575 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003576 assert((TU && Result == CXError_Success) ||
3577 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003578 return TU;
3579}
3580
3581enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003582 CXIndex CIdx, const char *source_filename,
3583 const char *const *command_line_args, int num_command_line_args,
3584 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3585 unsigned options, CXTranslationUnit *out_TU) {
3586 SmallVector<const char *, 4> Args;
3587 Args.push_back("clang");
3588 Args.append(command_line_args, command_line_args + num_command_line_args);
3589 return clang_parseTranslationUnit2FullArgv(
3590 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3591 num_unsaved_files, options, out_TU);
3592}
3593
3594enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3595 CXIndex CIdx, const char *source_filename,
3596 const char *const *command_line_args, int num_command_line_args,
3597 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3598 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003599 LOG_FUNC_SECTION {
3600 *Log << source_filename << ": ";
3601 for (int i = 0; i != num_command_line_args; ++i)
3602 *Log << command_line_args[i] << " ";
3603 }
3604
Alp Toker9d85b182014-07-07 01:23:14 +00003605 if (num_unsaved_files && !unsaved_files)
3606 return CXError_InvalidArguments;
3607
Alp Toker5c532982014-07-07 22:42:03 +00003608 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003609 auto ParseTranslationUnitImpl = [=, &result] {
3610 result = clang_parseTranslationUnit_Impl(
3611 CIdx, source_filename, command_line_args, num_command_line_args,
3612 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3613 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003614
Guy Benyei11169dd2012-12-18 14:30:41 +00003615 llvm::CrashRecoveryContext CRC;
3616
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003617 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003618 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3619 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3620 fprintf(stderr, " 'command_line_args' : [");
3621 for (int i = 0; i != num_command_line_args; ++i) {
3622 if (i)
3623 fprintf(stderr, ", ");
3624 fprintf(stderr, "'%s'", command_line_args[i]);
3625 }
3626 fprintf(stderr, "],\n");
3627 fprintf(stderr, " 'unsaved_files' : [");
3628 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3629 if (i)
3630 fprintf(stderr, ", ");
3631 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3632 unsaved_files[i].Length);
3633 }
3634 fprintf(stderr, "],\n");
3635 fprintf(stderr, " 'options' : %d,\n", options);
3636 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003637
3638 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003639 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003640 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003641 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003642 }
Alp Toker5c532982014-07-07 22:42:03 +00003643
3644 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003645}
3646
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003647CXString clang_Type_getObjCEncoding(CXType CT) {
3648 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3649 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3650 std::string encoding;
3651 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3652 encoding);
3653
3654 return cxstring::createDup(encoding);
3655}
3656
3657static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3658 if (C.kind == CXCursor_MacroDefinition) {
3659 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3660 return MDR->getName();
3661 } else if (C.kind == CXCursor_MacroExpansion) {
3662 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3663 return ME.getName();
3664 }
3665 return nullptr;
3666}
3667
3668unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3669 const IdentifierInfo *II = getMacroIdentifier(C);
3670 if (!II) {
3671 return false;
3672 }
3673 ASTUnit *ASTU = getCursorASTUnit(C);
3674 Preprocessor &PP = ASTU->getPreprocessor();
3675 if (const MacroInfo *MI = PP.getMacroInfo(II))
3676 return MI->isFunctionLike();
3677 return false;
3678}
3679
3680unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3681 const IdentifierInfo *II = getMacroIdentifier(C);
3682 if (!II) {
3683 return false;
3684 }
3685 ASTUnit *ASTU = getCursorASTUnit(C);
3686 Preprocessor &PP = ASTU->getPreprocessor();
3687 if (const MacroInfo *MI = PP.getMacroInfo(II))
3688 return MI->isBuiltinMacro();
3689 return false;
3690}
3691
3692unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3693 const Decl *D = getCursorDecl(C);
3694 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3695 if (!FD) {
3696 return false;
3697 }
3698 return FD->isInlined();
3699}
3700
3701static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3702 if (callExpr->getNumArgs() != 1) {
3703 return nullptr;
3704 }
3705
3706 StringLiteral *S = nullptr;
3707 auto *arg = callExpr->getArg(0);
3708 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3709 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3710 auto *subExpr = I->getSubExprAsWritten();
3711
3712 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3713 return nullptr;
3714 }
3715
3716 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3717 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3718 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3719 } else {
3720 return nullptr;
3721 }
3722 return S;
3723}
3724
David Blaikie59272572016-04-13 18:23:33 +00003725struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003726 CXEvalResultKind EvalType;
3727 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003728 unsigned long long unsignedVal;
3729 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003730 double floatVal;
3731 char *stringVal;
3732 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003733 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003734 ~ExprEvalResult() {
3735 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3736 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003737 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003738 }
3739 }
3740};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003741
3742void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003743 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003744}
3745
3746CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3747 if (!E) {
3748 return CXEval_UnExposed;
3749 }
3750 return ((ExprEvalResult *)E)->EvalType;
3751}
3752
3753int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003754 return clang_EvalResult_getAsLongLong(E);
3755}
3756
3757long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003758 if (!E) {
3759 return 0;
3760 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003761 ExprEvalResult *Result = (ExprEvalResult*)E;
3762 if (Result->IsUnsignedInt)
3763 return Result->EvalData.unsignedVal;
3764 return Result->EvalData.intVal;
3765}
3766
3767unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3768 return ((ExprEvalResult *)E)->IsUnsignedInt;
3769}
3770
3771unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3772 if (!E) {
3773 return 0;
3774 }
3775
3776 ExprEvalResult *Result = (ExprEvalResult*)E;
3777 if (Result->IsUnsignedInt)
3778 return Result->EvalData.unsignedVal;
3779 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003780}
3781
3782double clang_EvalResult_getAsDouble(CXEvalResult E) {
3783 if (!E) {
3784 return 0;
3785 }
3786 return ((ExprEvalResult *)E)->EvalData.floatVal;
3787}
3788
3789const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3790 if (!E) {
3791 return nullptr;
3792 }
3793 return ((ExprEvalResult *)E)->EvalData.stringVal;
3794}
3795
3796static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3797 Expr::EvalResult ER;
3798 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003799 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003800 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003801
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003802 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003803 if (expr->isValueDependent())
3804 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003805 if (!expr->EvaluateAsRValue(ER, ctx))
3806 return nullptr;
3807
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003808 QualType rettype;
3809 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003810 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003811 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003812 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003813
David Blaikiebbc00882016-04-13 18:36:19 +00003814 if (ER.Val.isInt()) {
3815 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003816
3817 auto& val = ER.Val.getInt();
3818 if (val.isUnsigned()) {
3819 result->IsUnsignedInt = true;
3820 result->EvalData.unsignedVal = val.getZExtValue();
3821 } else {
3822 result->EvalData.intVal = val.getExtValue();
3823 }
3824
David Blaikiebbc00882016-04-13 18:36:19 +00003825 return result.release();
3826 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003827
David Blaikiebbc00882016-04-13 18:36:19 +00003828 if (ER.Val.isFloat()) {
3829 llvm::SmallVector<char, 100> Buffer;
3830 ER.Val.getFloat().toString(Buffer);
3831 std::string floatStr(Buffer.data(), Buffer.size());
3832 result->EvalType = CXEval_Float;
3833 bool ignored;
3834 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003835 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003836 llvm::APFloat::rmNearestTiesToEven, &ignored);
3837 result->EvalData.floatVal = apFloat.convertToDouble();
3838 return result.release();
3839 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003840
David Blaikiebbc00882016-04-13 18:36:19 +00003841 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3842 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3843 auto *subExpr = I->getSubExprAsWritten();
3844 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3845 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003846 const StringLiteral *StrE = nullptr;
3847 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003848 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003849
3850 if (ObjCExpr) {
3851 StrE = ObjCExpr->getString();
3852 result->EvalType = CXEval_ObjCStrLiteral;
3853 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003854 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003855 result->EvalType = CXEval_StrLiteral;
3856 }
3857
3858 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003859 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003860 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3861 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003862 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003863 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003864 }
3865 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3866 expr->getStmtClass() == Stmt::StringLiteralClass) {
3867 const StringLiteral *StrE = nullptr;
3868 const ObjCStringLiteral *ObjCExpr;
3869 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003870
David Blaikiebbc00882016-04-13 18:36:19 +00003871 if (ObjCExpr) {
3872 StrE = ObjCExpr->getString();
3873 result->EvalType = CXEval_ObjCStrLiteral;
3874 } else {
3875 StrE = cast<StringLiteral>(expr);
3876 result->EvalType = CXEval_StrLiteral;
3877 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003878
David Blaikiebbc00882016-04-13 18:36:19 +00003879 std::string strRef(StrE->getString().str());
3880 result->EvalData.stringVal = new char[strRef.size() + 1];
3881 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3882 result->EvalData.stringVal[strRef.size()] = '\0';
3883 return result.release();
3884 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003885
David Blaikiebbc00882016-04-13 18:36:19 +00003886 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3887 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003888
David Blaikiebbc00882016-04-13 18:36:19 +00003889 rettype = CC->getType();
3890 if (rettype.getAsString() == "CFStringRef" &&
3891 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003892
David Blaikiebbc00882016-04-13 18:36:19 +00003893 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3894 StringLiteral *S = getCFSTR_value(callExpr);
3895 if (S) {
3896 std::string strLiteral(S->getString().str());
3897 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003898
David Blaikiebbc00882016-04-13 18:36:19 +00003899 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3900 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3901 strLiteral.size());
3902 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003903 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003904 }
3905 }
3906
David Blaikiebbc00882016-04-13 18:36:19 +00003907 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3908 callExpr = static_cast<CallExpr *>(expr);
3909 rettype = callExpr->getCallReturnType(ctx);
3910
3911 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3912 return nullptr;
3913
3914 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3915 if (callExpr->getNumArgs() == 1 &&
3916 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3917 return nullptr;
3918 } else if (rettype.getAsString() == "CFStringRef") {
3919
3920 StringLiteral *S = getCFSTR_value(callExpr);
3921 if (S) {
3922 std::string strLiteral(S->getString().str());
3923 result->EvalType = CXEval_CFStr;
3924 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3925 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3926 strLiteral.size());
3927 result->EvalData.stringVal[strLiteral.size()] = '\0';
3928 return result.release();
3929 }
3930 }
3931 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3932 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3933 ValueDecl *V = D->getDecl();
3934 if (V->getKind() == Decl::Function) {
3935 std::string strName = V->getNameAsString();
3936 result->EvalType = CXEval_Other;
3937 result->EvalData.stringVal = new char[strName.size() + 1];
3938 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3939 result->EvalData.stringVal[strName.size()] = '\0';
3940 return result.release();
3941 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003942 }
3943
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003944 return nullptr;
3945}
3946
Alex Lorenz65317e12019-01-08 22:32:51 +00003947static const Expr *evaluateDeclExpr(const Decl *D) {
3948 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003949 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003950 if (auto *Var = dyn_cast<VarDecl>(D))
3951 return Var->getInit();
3952 else if (auto *Field = dyn_cast<FieldDecl>(D))
3953 return Field->getInClassInitializer();
3954 return nullptr;
3955}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003956
Alex Lorenz65317e12019-01-08 22:32:51 +00003957static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3958 assert(CS && "invalid compound statement");
3959 for (auto *bodyIterator : CS->body()) {
3960 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3961 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003962 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003963 return nullptr;
3964}
3965
Alex Lorenz65317e12019-01-08 22:32:51 +00003966CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3967 if (const Expr *E =
3968 clang_getCursorKind(C) == CXCursor_CompoundStmt
3969 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3970 : evaluateDeclExpr(getCursorDecl(C)))
3971 return const_cast<CXEvalResult>(
3972 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3973 return nullptr;
3974}
3975
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003976unsigned clang_Cursor_hasAttrs(CXCursor C) {
3977 const Decl *D = getCursorDecl(C);
3978 if (!D) {
3979 return 0;
3980 }
3981
3982 if (D->hasAttrs()) {
3983 return 1;
3984 }
3985
3986 return 0;
3987}
Guy Benyei11169dd2012-12-18 14:30:41 +00003988unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3989 return CXSaveTranslationUnit_None;
3990}
3991
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003992static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3993 const char *FileName,
3994 unsigned options) {
3995 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003996 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3997 setThreadBackgroundPriority();
3998
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003999 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4000 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004001}
4002
4003int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4004 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004005 LOG_FUNC_SECTION {
4006 *Log << TU << ' ' << FileName;
4007 }
4008
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004009 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004010 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004012 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004013
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004014 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4016 if (!CXXUnit->hasSema())
4017 return CXSaveError_InvalidTU;
4018
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004019 CXSaveError result;
4020 auto SaveTranslationUnitImpl = [=, &result]() {
4021 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4022 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004023
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004024 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004025 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004026
4027 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4028 PrintLibclangResourceUsage(TU);
4029
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004030 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004031 }
4032
4033 // We have an AST that has invalid nodes due to compiler errors.
4034 // Use a crash recovery thread for protection.
4035
4036 llvm::CrashRecoveryContext CRC;
4037
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004038 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004039 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4040 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4041 fprintf(stderr, " 'options' : %d,\n", options);
4042 fprintf(stderr, "}\n");
4043
4044 return CXSaveError_Unknown;
4045
4046 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4047 PrintLibclangResourceUsage(TU);
4048 }
4049
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004050 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004051}
4052
4053void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4054 if (CTUnit) {
4055 // If the translation unit has been marked as unsafe to free, just discard
4056 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004057 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4058 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 return;
4060
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004061 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004062 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004063 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4064 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004065 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 delete CTUnit;
4067 }
4068}
4069
Erik Verbruggen346066b2017-05-30 14:25:54 +00004070unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4071 if (CTUnit) {
4072 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4073
4074 if (Unit && Unit->isUnsafeToFree())
4075 return false;
4076
4077 Unit->ResetForParse();
4078 return true;
4079 }
4080
4081 return false;
4082}
4083
Guy Benyei11169dd2012-12-18 14:30:41 +00004084unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4085 return CXReparse_None;
4086}
4087
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004088static CXErrorCode
4089clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4090 ArrayRef<CXUnsavedFile> unsaved_files,
4091 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004092 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004093 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004094 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004095 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004096 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004097
4098 // Reset the associated diagnostics.
4099 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004100 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004101
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004102 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004103 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4104 setThreadBackgroundPriority();
4105
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004106 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004107 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004108
4109 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4110 new std::vector<ASTUnit::RemappedFile>());
4111
Guy Benyei11169dd2012-12-18 14:30:41 +00004112 // Recover resources if we crash before exiting this function.
4113 llvm::CrashRecoveryContextCleanupRegistrar<
4114 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004115
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004116 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004117 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004118 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004119 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004120 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004121
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004122 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4123 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004124 return CXError_Success;
4125 if (isASTReadError(CXXUnit))
4126 return CXError_ASTReadError;
4127 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004128}
4129
4130int clang_reparseTranslationUnit(CXTranslationUnit TU,
4131 unsigned num_unsaved_files,
4132 struct CXUnsavedFile *unsaved_files,
4133 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004134 LOG_FUNC_SECTION {
4135 *Log << TU;
4136 }
4137
Alp Toker9d85b182014-07-07 01:23:14 +00004138 if (num_unsaved_files && !unsaved_files)
4139 return CXError_InvalidArguments;
4140
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004141 CXErrorCode result;
4142 auto ReparseTranslationUnitImpl = [=, &result]() {
4143 result = clang_reparseTranslationUnit_Impl(
4144 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4145 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004146
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 llvm::CrashRecoveryContext CRC;
4148
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004149 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004150 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004151 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004152 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4154 PrintLibclangResourceUsage(TU);
4155
Alp Toker5c532982014-07-07 22:42:03 +00004156 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004157}
4158
4159
4160CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004161 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004162 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004163 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004164 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004165
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004166 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004167 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004168}
4169
4170CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004171 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004172 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004173 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004174 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004175
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004176 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4178}
4179
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004180CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4181 if (isNotUsableTU(CTUnit)) {
4182 LOG_BAD_TU(CTUnit);
4183 return nullptr;
4184 }
4185
4186 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4187 impl->TranslationUnit = CTUnit;
4188 return impl;
4189}
4190
4191CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4192 if (!TargetInfo)
4193 return cxstring::createEmpty();
4194
4195 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4196 assert(!isNotUsableTU(CTUnit) &&
4197 "Unexpected unusable translation unit in TargetInfo");
4198
4199 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4200 std::string Triple =
4201 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4202 return cxstring::createDup(Triple);
4203}
4204
4205int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4206 if (!TargetInfo)
4207 return -1;
4208
4209 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4210 assert(!isNotUsableTU(CTUnit) &&
4211 "Unexpected unusable translation unit in TargetInfo");
4212
4213 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4214 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4215}
4216
4217void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4218 if (!TargetInfo)
4219 return;
4220
4221 delete TargetInfo;
4222}
4223
Guy Benyei11169dd2012-12-18 14:30:41 +00004224//===----------------------------------------------------------------------===//
4225// CXFile Operations.
4226//===----------------------------------------------------------------------===//
4227
Guy Benyei11169dd2012-12-18 14:30:41 +00004228CXString clang_getFileName(CXFile SFile) {
4229 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004230 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004231
4232 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004233 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004234}
4235
4236time_t clang_getFileTime(CXFile SFile) {
4237 if (!SFile)
4238 return 0;
4239
4240 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4241 return FEnt->getModificationTime();
4242}
4243
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004244CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004245 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004246 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004247 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004248 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004249
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004250 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004251
4252 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004253 auto File = FMgr.getFile(file_name);
4254 if (!File)
4255 return nullptr;
4256 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004257}
4258
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004259const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4260 size_t *size) {
4261 if (isNotUsableTU(TU)) {
4262 LOG_BAD_TU(TU);
4263 return nullptr;
4264 }
4265
4266 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4267 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4268 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004269 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004270 if (Invalid) {
4271 if (size)
4272 *size = 0;
4273 return nullptr;
4274 }
4275 if (size)
4276 *size = buf->getBufferSize();
4277 return buf->getBufferStart();
4278}
4279
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004280unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4281 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004282 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004283 LOG_BAD_TU(TU);
4284 return 0;
4285 }
4286
4287 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 return 0;
4289
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004290 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 FileEntry *FEnt = static_cast<FileEntry *>(file);
4292 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4293 .isFileMultipleIncludeGuarded(FEnt);
4294}
4295
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004296int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4297 if (!file || !outID)
4298 return 1;
4299
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004300 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004301 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4302 outID->data[0] = ID.getDevice();
4303 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004304 outID->data[2] = FEnt->getModificationTime();
4305 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004306}
4307
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004308int clang_File_isEqual(CXFile file1, CXFile file2) {
4309 if (file1 == file2)
4310 return true;
4311
4312 if (!file1 || !file2)
4313 return false;
4314
4315 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4316 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4317 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4318}
4319
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004320CXString clang_File_tryGetRealPathName(CXFile SFile) {
4321 if (!SFile)
4322 return cxstring::createNull();
4323
4324 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4325 return cxstring::createRef(FEnt->tryGetRealPathName());
4326}
4327
Guy Benyei11169dd2012-12-18 14:30:41 +00004328//===----------------------------------------------------------------------===//
4329// CXCursor Operations.
4330//===----------------------------------------------------------------------===//
4331
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004332static const Decl *getDeclFromExpr(const Stmt *E) {
4333 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 return getDeclFromExpr(CE->getSubExpr());
4335
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004336 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004338 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004340 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004342 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 if (PRE->isExplicitProperty())
4344 return PRE->getExplicitProperty();
4345 // It could be messaging both getter and setter as in:
4346 // ++myobj.myprop;
4347 // in which case prefer to associate the setter since it is less obvious
4348 // from inspecting the source that the setter is going to get called.
4349 if (PRE->isMessagingSetter())
4350 return PRE->getImplicitPropertySetter();
4351 return PRE->getImplicitPropertyGetter();
4352 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004353 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004355 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 if (Expr *Src = OVE->getSourceExpr())
4357 return getDeclFromExpr(Src);
4358
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004359 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004361 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004362 if (!CE->isElidable())
4363 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004364 if (const CXXInheritedCtorInitExpr *CE =
4365 dyn_cast<CXXInheritedCtorInitExpr>(E))
4366 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004367 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 return OME->getMethodDecl();
4369
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004370 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004372 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4374 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004375 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4377 isa<ParmVarDecl>(SizeOfPack->getPack()))
4378 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004379
4380 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004381}
4382
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004383static SourceLocation getLocationFromExpr(const Expr *E) {
4384 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 return getLocationFromExpr(CE->getSubExpr());
4386
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004387 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004389 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004391 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004393 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004395 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004397 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004399
4400 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004401}
4402
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004403extern "C" {
4404
Guy Benyei11169dd2012-12-18 14:30:41 +00004405unsigned clang_visitChildren(CXCursor parent,
4406 CXCursorVisitor visitor,
4407 CXClientData client_data) {
4408 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4409 /*VisitPreprocessorLast=*/false);
4410 return CursorVis.VisitChildren(parent);
4411}
4412
4413#ifndef __has_feature
4414#define __has_feature(x) 0
4415#endif
4416#if __has_feature(blocks)
4417typedef enum CXChildVisitResult
4418 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4419
4420static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4421 CXClientData client_data) {
4422 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4423 return block(cursor, parent);
4424}
4425#else
4426// If we are compiled with a compiler that doesn't have native blocks support,
4427// define and call the block manually, so the
4428typedef struct _CXChildVisitResult
4429{
4430 void *isa;
4431 int flags;
4432 int reserved;
4433 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4434 CXCursor);
4435} *CXCursorVisitorBlock;
4436
4437static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4438 CXClientData client_data) {
4439 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4440 return block->invoke(block, cursor, parent);
4441}
4442#endif
4443
4444
4445unsigned clang_visitChildrenWithBlock(CXCursor parent,
4446 CXCursorVisitorBlock block) {
4447 return clang_visitChildren(parent, visitWithBlock, block);
4448}
4449
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004450static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004452 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004453
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004454 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004456 if (const ObjCPropertyImplDecl *PropImpl =
4457 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004459 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004460
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004461 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004463 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004464
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004465 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 }
4467
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004468 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004469 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004470
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004471 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4473 // and returns different names. NamedDecl returns the class name and
4474 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004475 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004476
4477 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004478 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004479
4480 SmallString<1024> S;
4481 llvm::raw_svector_ostream os(S);
4482 ND->printName(os);
4483
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004484 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004485}
4486
4487CXString clang_getCursorSpelling(CXCursor C) {
4488 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004489 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004490
4491 if (clang_isReference(C.kind)) {
4492 switch (C.kind) {
4493 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004494 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004495 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 }
4497 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004498 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004499 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 }
4501 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004502 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004504 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 }
4506 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004507 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004508 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 }
4510 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004511 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 assert(Type && "Missing type decl");
4513
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004514 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 getAsString());
4516 }
4517 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004518 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 assert(Template && "Missing template decl");
4520
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004521 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004522 }
4523
4524 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004525 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004526 assert(NS && "Missing namespace decl");
4527
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004528 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 }
4530
4531 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004532 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 assert(Field && "Missing member decl");
4534
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004535 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 }
4537
4538 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004539 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 assert(Label && "Missing label");
4541
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004542 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 }
4544
4545 case CXCursor_OverloadedDeclRef: {
4546 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004547 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4548 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004549 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004550 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004552 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004553 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 OverloadedTemplateStorage *Ovl
4555 = Storage.get<OverloadedTemplateStorage*>();
4556 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004557 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004558 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 }
4560
4561 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004562 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 assert(Var && "Missing variable decl");
4564
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004565 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 }
4567
4568 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004569 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 }
4571 }
4572
4573 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004574 const Expr *E = getCursorExpr(C);
4575
4576 if (C.kind == CXCursor_ObjCStringLiteral ||
4577 C.kind == CXCursor_StringLiteral) {
4578 const StringLiteral *SLit;
4579 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4580 SLit = OSL->getString();
4581 } else {
4582 SLit = cast<StringLiteral>(E);
4583 }
4584 SmallString<256> Buf;
4585 llvm::raw_svector_ostream OS(Buf);
4586 SLit->outputString(OS);
4587 return cxstring::createDup(OS.str());
4588 }
4589
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004590 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 if (D)
4592 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004593 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 }
4595
4596 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004597 const Stmt *S = getCursorStmt(C);
4598 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004599 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004600
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004601 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 }
4603
4604 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004605 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 ->getNameStart());
4607
4608 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004609 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 ->getNameStart());
4611
4612 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004613 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004614
4615 if (clang_isDeclaration(C.kind))
4616 return getDeclSpelling(getCursorDecl(C));
4617
4618 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004619 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004620 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 }
4622
4623 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004624 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004625 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 }
4627
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004628 if (C.kind == CXCursor_PackedAttr) {
4629 return cxstring::createRef("packed");
4630 }
4631
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004632 if (C.kind == CXCursor_VisibilityAttr) {
4633 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4634 switch (AA->getVisibility()) {
4635 case VisibilityAttr::VisibilityType::Default:
4636 return cxstring::createRef("default");
4637 case VisibilityAttr::VisibilityType::Hidden:
4638 return cxstring::createRef("hidden");
4639 case VisibilityAttr::VisibilityType::Protected:
4640 return cxstring::createRef("protected");
4641 }
4642 llvm_unreachable("unknown visibility type");
4643 }
4644
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004645 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004646}
4647
4648CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4649 unsigned pieceIndex,
4650 unsigned options) {
4651 if (clang_Cursor_isNull(C))
4652 return clang_getNullRange();
4653
4654 ASTContext &Ctx = getCursorContext(C);
4655
4656 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004657 const Stmt *S = getCursorStmt(C);
4658 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 if (pieceIndex > 0)
4660 return clang_getNullRange();
4661 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4662 }
4663
4664 return clang_getNullRange();
4665 }
4666
4667 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004668 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4670 if (pieceIndex >= ME->getNumSelectorLocs())
4671 return clang_getNullRange();
4672 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4673 }
4674 }
4675
4676 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4677 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004678 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4680 if (pieceIndex >= MD->getNumSelectorLocs())
4681 return clang_getNullRange();
4682 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4683 }
4684 }
4685
4686 if (C.kind == CXCursor_ObjCCategoryDecl ||
4687 C.kind == CXCursor_ObjCCategoryImplDecl) {
4688 if (pieceIndex > 0)
4689 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004690 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4692 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004693 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004694 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4695 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4696 }
4697
4698 if (C.kind == CXCursor_ModuleImportDecl) {
4699 if (pieceIndex > 0)
4700 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004701 if (const ImportDecl *ImportD =
4702 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4704 if (!Locs.empty())
4705 return cxloc::translateSourceRange(Ctx,
4706 SourceRange(Locs.front(), Locs.back()));
4707 }
4708 return clang_getNullRange();
4709 }
4710
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004711 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004712 C.kind == CXCursor_ConversionFunction ||
4713 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004714 if (pieceIndex > 0)
4715 return clang_getNullRange();
4716 if (const FunctionDecl *FD =
4717 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4718 DeclarationNameInfo FunctionName = FD->getNameInfo();
4719 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4720 }
4721 return clang_getNullRange();
4722 }
4723
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 // FIXME: A CXCursor_InclusionDirective should give the location of the
4725 // filename, but we don't keep track of this.
4726
4727 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4728 // but we don't keep track of this.
4729
4730 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4731 // but we don't keep track of this.
4732
4733 // Default handling, give the location of the cursor.
4734
4735 if (pieceIndex > 0)
4736 return clang_getNullRange();
4737
4738 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4739 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4740 return cxloc::translateSourceRange(Ctx, Loc);
4741}
4742
Eli Bendersky44a206f2014-07-31 18:04:56 +00004743CXString clang_Cursor_getMangling(CXCursor C) {
4744 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4745 return cxstring::createEmpty();
4746
Eli Bendersky44a206f2014-07-31 18:04:56 +00004747 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004748 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004749 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4750 return cxstring::createEmpty();
4751
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004752 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004753 ASTNameGenerator ASTNameGen(Ctx);
4754 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004755}
4756
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004757CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4758 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4759 return nullptr;
4760
4761 const Decl *D = getCursorDecl(C);
4762 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4763 return nullptr;
4764
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004765 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004766 ASTNameGenerator ASTNameGen(Ctx);
4767 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004768 return cxstring::createSet(Manglings);
4769}
4770
Dave Lee1a532c92017-09-22 16:58:57 +00004771CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4772 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4773 return nullptr;
4774
4775 const Decl *D = getCursorDecl(C);
4776 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4777 return nullptr;
4778
4779 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004780 ASTNameGenerator ASTNameGen(Ctx);
4781 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004782 return cxstring::createSet(Manglings);
4783}
4784
Jonathan Coe45ef5032018-01-16 10:19:56 +00004785CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4786 if (clang_Cursor_isNull(C))
4787 return 0;
4788 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4789}
4790
4791void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4792 if (Policy)
4793 delete static_cast<PrintingPolicy *>(Policy);
4794}
4795
4796unsigned
4797clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4798 enum CXPrintingPolicyProperty Property) {
4799 if (!Policy)
4800 return 0;
4801
4802 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4803 switch (Property) {
4804 case CXPrintingPolicy_Indentation:
4805 return P->Indentation;
4806 case CXPrintingPolicy_SuppressSpecifiers:
4807 return P->SuppressSpecifiers;
4808 case CXPrintingPolicy_SuppressTagKeyword:
4809 return P->SuppressTagKeyword;
4810 case CXPrintingPolicy_IncludeTagDefinition:
4811 return P->IncludeTagDefinition;
4812 case CXPrintingPolicy_SuppressScope:
4813 return P->SuppressScope;
4814 case CXPrintingPolicy_SuppressUnwrittenScope:
4815 return P->SuppressUnwrittenScope;
4816 case CXPrintingPolicy_SuppressInitializers:
4817 return P->SuppressInitializers;
4818 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4819 return P->ConstantArraySizeAsWritten;
4820 case CXPrintingPolicy_AnonymousTagLocations:
4821 return P->AnonymousTagLocations;
4822 case CXPrintingPolicy_SuppressStrongLifetime:
4823 return P->SuppressStrongLifetime;
4824 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4825 return P->SuppressLifetimeQualifiers;
4826 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4827 return P->SuppressTemplateArgsInCXXConstructors;
4828 case CXPrintingPolicy_Bool:
4829 return P->Bool;
4830 case CXPrintingPolicy_Restrict:
4831 return P->Restrict;
4832 case CXPrintingPolicy_Alignof:
4833 return P->Alignof;
4834 case CXPrintingPolicy_UnderscoreAlignof:
4835 return P->UnderscoreAlignof;
4836 case CXPrintingPolicy_UseVoidForZeroParams:
4837 return P->UseVoidForZeroParams;
4838 case CXPrintingPolicy_TerseOutput:
4839 return P->TerseOutput;
4840 case CXPrintingPolicy_PolishForDeclaration:
4841 return P->PolishForDeclaration;
4842 case CXPrintingPolicy_Half:
4843 return P->Half;
4844 case CXPrintingPolicy_MSWChar:
4845 return P->MSWChar;
4846 case CXPrintingPolicy_IncludeNewlines:
4847 return P->IncludeNewlines;
4848 case CXPrintingPolicy_MSVCFormatting:
4849 return P->MSVCFormatting;
4850 case CXPrintingPolicy_ConstantsAsWritten:
4851 return P->ConstantsAsWritten;
4852 case CXPrintingPolicy_SuppressImplicitBase:
4853 return P->SuppressImplicitBase;
4854 case CXPrintingPolicy_FullyQualifiedName:
4855 return P->FullyQualifiedName;
4856 }
4857
4858 assert(false && "Invalid CXPrintingPolicyProperty");
4859 return 0;
4860}
4861
4862void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4863 enum CXPrintingPolicyProperty Property,
4864 unsigned Value) {
4865 if (!Policy)
4866 return;
4867
4868 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4869 switch (Property) {
4870 case CXPrintingPolicy_Indentation:
4871 P->Indentation = Value;
4872 return;
4873 case CXPrintingPolicy_SuppressSpecifiers:
4874 P->SuppressSpecifiers = Value;
4875 return;
4876 case CXPrintingPolicy_SuppressTagKeyword:
4877 P->SuppressTagKeyword = Value;
4878 return;
4879 case CXPrintingPolicy_IncludeTagDefinition:
4880 P->IncludeTagDefinition = Value;
4881 return;
4882 case CXPrintingPolicy_SuppressScope:
4883 P->SuppressScope = Value;
4884 return;
4885 case CXPrintingPolicy_SuppressUnwrittenScope:
4886 P->SuppressUnwrittenScope = Value;
4887 return;
4888 case CXPrintingPolicy_SuppressInitializers:
4889 P->SuppressInitializers = Value;
4890 return;
4891 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4892 P->ConstantArraySizeAsWritten = Value;
4893 return;
4894 case CXPrintingPolicy_AnonymousTagLocations:
4895 P->AnonymousTagLocations = Value;
4896 return;
4897 case CXPrintingPolicy_SuppressStrongLifetime:
4898 P->SuppressStrongLifetime = Value;
4899 return;
4900 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4901 P->SuppressLifetimeQualifiers = Value;
4902 return;
4903 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4904 P->SuppressTemplateArgsInCXXConstructors = Value;
4905 return;
4906 case CXPrintingPolicy_Bool:
4907 P->Bool = Value;
4908 return;
4909 case CXPrintingPolicy_Restrict:
4910 P->Restrict = Value;
4911 return;
4912 case CXPrintingPolicy_Alignof:
4913 P->Alignof = Value;
4914 return;
4915 case CXPrintingPolicy_UnderscoreAlignof:
4916 P->UnderscoreAlignof = Value;
4917 return;
4918 case CXPrintingPolicy_UseVoidForZeroParams:
4919 P->UseVoidForZeroParams = Value;
4920 return;
4921 case CXPrintingPolicy_TerseOutput:
4922 P->TerseOutput = Value;
4923 return;
4924 case CXPrintingPolicy_PolishForDeclaration:
4925 P->PolishForDeclaration = Value;
4926 return;
4927 case CXPrintingPolicy_Half:
4928 P->Half = Value;
4929 return;
4930 case CXPrintingPolicy_MSWChar:
4931 P->MSWChar = Value;
4932 return;
4933 case CXPrintingPolicy_IncludeNewlines:
4934 P->IncludeNewlines = Value;
4935 return;
4936 case CXPrintingPolicy_MSVCFormatting:
4937 P->MSVCFormatting = Value;
4938 return;
4939 case CXPrintingPolicy_ConstantsAsWritten:
4940 P->ConstantsAsWritten = Value;
4941 return;
4942 case CXPrintingPolicy_SuppressImplicitBase:
4943 P->SuppressImplicitBase = Value;
4944 return;
4945 case CXPrintingPolicy_FullyQualifiedName:
4946 P->FullyQualifiedName = Value;
4947 return;
4948 }
4949
4950 assert(false && "Invalid CXPrintingPolicyProperty");
4951}
4952
4953CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4954 if (clang_Cursor_isNull(C))
4955 return cxstring::createEmpty();
4956
4957 if (clang_isDeclaration(C.kind)) {
4958 const Decl *D = getCursorDecl(C);
4959 if (!D)
4960 return cxstring::createEmpty();
4961
4962 SmallString<128> Str;
4963 llvm::raw_svector_ostream OS(Str);
4964 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4965 D->print(OS, UserPolicy ? *UserPolicy
4966 : getCursorContext(C).getPrintingPolicy());
4967
4968 return cxstring::createDup(OS.str());
4969 }
4970
4971 return cxstring::createEmpty();
4972}
4973
Guy Benyei11169dd2012-12-18 14:30:41 +00004974CXString clang_getCursorDisplayName(CXCursor C) {
4975 if (!clang_isDeclaration(C.kind))
4976 return clang_getCursorSpelling(C);
4977
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004978 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004980 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004981
4982 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004983 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 D = FunTmpl->getTemplatedDecl();
4985
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004986 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004987 SmallString<64> Str;
4988 llvm::raw_svector_ostream OS(Str);
4989 OS << *Function;
4990 if (Function->getPrimaryTemplate())
4991 OS << "<>";
4992 OS << "(";
4993 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4994 if (I)
4995 OS << ", ";
4996 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4997 }
4998
4999 if (Function->isVariadic()) {
5000 if (Function->getNumParams())
5001 OS << ", ";
5002 OS << "...";
5003 }
5004 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005005 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 }
5007
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005008 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 SmallString<64> Str;
5010 llvm::raw_svector_ostream OS(Str);
5011 OS << *ClassTemplate;
5012 OS << "<";
5013 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5014 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5015 if (I)
5016 OS << ", ";
5017
5018 NamedDecl *Param = Params->getParam(I);
5019 if (Param->getIdentifier()) {
5020 OS << Param->getIdentifier()->getName();
5021 continue;
5022 }
5023
5024 // There is no parameter name, which makes this tricky. Try to come up
5025 // with something useful that isn't too long.
5026 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5027 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
5028 else if (NonTypeTemplateParmDecl *NTTP
5029 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5030 OS << NTTP->getType().getAsString(Policy);
5031 else
5032 OS << "template<...> class";
5033 }
5034
5035 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005036 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 }
5038
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005039 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5041 // If the type was explicitly written, use that.
5042 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005043 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005044
Benjamin Kramer9170e912013-02-22 15:46:01 +00005045 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 llvm::raw_svector_ostream OS(Str);
5047 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005048 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5049 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005050 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 }
5052
5053 return clang_getCursorSpelling(C);
5054}
5055
5056CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5057 switch (Kind) {
5058 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005059 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005061 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005063 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005065 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005067 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005069 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005071 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005073 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005075 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005077 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005079 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005081 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005083 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005085 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005087 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005089 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005091 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005093 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005097 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005101 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005122 case CXCursor_FixedPointLiteral:
5123 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005138 case CXCursor_OMPArraySectionExpr:
5139 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005190 case CXCursor_ObjCAvailabilityCheckExpr:
5191 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005192 case CXCursor_ObjCSelfExpr:
5193 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005220 case CXCursor_BuiltinBitCastExpr:
5221 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005257 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005265 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005277 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005284 case CXCursor_SEHLeaveStmt:
5285 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005297 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005307 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005309 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005311 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005313 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005314 case CXCursor_PackedAttr:
5315 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005316 case CXCursor_PureAttr:
5317 return cxstring::createRef("attribute(pure)");
5318 case CXCursor_ConstAttr:
5319 return cxstring::createRef("attribute(const)");
5320 case CXCursor_NoDuplicateAttr:
5321 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005322 case CXCursor_CUDAConstantAttr:
5323 return cxstring::createRef("attribute(constant)");
5324 case CXCursor_CUDADeviceAttr:
5325 return cxstring::createRef("attribute(device)");
5326 case CXCursor_CUDAGlobalAttr:
5327 return cxstring::createRef("attribute(global)");
5328 case CXCursor_CUDAHostAttr:
5329 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005330 case CXCursor_CUDASharedAttr:
5331 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005332 case CXCursor_VisibilityAttr:
5333 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005334 case CXCursor_DLLExport:
5335 return cxstring::createRef("attribute(dllexport)");
5336 case CXCursor_DLLImport:
5337 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005338 case CXCursor_NSReturnsRetained:
5339 return cxstring::createRef("attribute(ns_returns_retained)");
5340 case CXCursor_NSReturnsNotRetained:
5341 return cxstring::createRef("attribute(ns_returns_not_retained)");
5342 case CXCursor_NSReturnsAutoreleased:
5343 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5344 case CXCursor_NSConsumesSelf:
5345 return cxstring::createRef("attribute(ns_consumes_self)");
5346 case CXCursor_NSConsumed:
5347 return cxstring::createRef("attribute(ns_consumed)");
5348 case CXCursor_ObjCException:
5349 return cxstring::createRef("attribute(objc_exception)");
5350 case CXCursor_ObjCNSObject:
5351 return cxstring::createRef("attribute(NSObject)");
5352 case CXCursor_ObjCIndependentClass:
5353 return cxstring::createRef("attribute(objc_independent_class)");
5354 case CXCursor_ObjCPreciseLifetime:
5355 return cxstring::createRef("attribute(objc_precise_lifetime)");
5356 case CXCursor_ObjCReturnsInnerPointer:
5357 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5358 case CXCursor_ObjCRequiresSuper:
5359 return cxstring::createRef("attribute(objc_requires_super)");
5360 case CXCursor_ObjCRootClass:
5361 return cxstring::createRef("attribute(objc_root_class)");
5362 case CXCursor_ObjCSubclassingRestricted:
5363 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5364 case CXCursor_ObjCExplicitProtocolImpl:
5365 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5366 case CXCursor_ObjCDesignatedInitializer:
5367 return cxstring::createRef("attribute(objc_designated_initializer)");
5368 case CXCursor_ObjCRuntimeVisible:
5369 return cxstring::createRef("attribute(objc_runtime_visible)");
5370 case CXCursor_ObjCBoxable:
5371 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005372 case CXCursor_FlagEnum:
5373 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005374 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005375 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005376 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005377 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005378 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005379 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005380 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005381 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005382 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005383 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005384 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005385 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005386 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005387 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005388 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005389 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005390 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005391 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005392 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005393 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005394 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005395 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005396 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005397 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005398 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005399 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005400 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005401 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005402 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005403 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005404 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005405 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005406 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005407 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005408 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005409 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005410 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005411 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005412 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005413 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005414 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005415 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005416 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005417 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005418 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005419 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005420 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005421 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005422 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005423 return cxstring::createRef("OMPParallelDirective");
5424 case CXCursor_OMPSimdDirective:
5425 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005426 case CXCursor_OMPForDirective:
5427 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005428 case CXCursor_OMPForSimdDirective:
5429 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005430 case CXCursor_OMPSectionsDirective:
5431 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005432 case CXCursor_OMPSectionDirective:
5433 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005434 case CXCursor_OMPSingleDirective:
5435 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005436 case CXCursor_OMPMasterDirective:
5437 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005438 case CXCursor_OMPCriticalDirective:
5439 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005440 case CXCursor_OMPParallelForDirective:
5441 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005442 case CXCursor_OMPParallelForSimdDirective:
5443 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005444 case CXCursor_OMPParallelSectionsDirective:
5445 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005446 case CXCursor_OMPTaskDirective:
5447 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005448 case CXCursor_OMPTaskyieldDirective:
5449 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005450 case CXCursor_OMPBarrierDirective:
5451 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005452 case CXCursor_OMPTaskwaitDirective:
5453 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005454 case CXCursor_OMPTaskgroupDirective:
5455 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005456 case CXCursor_OMPFlushDirective:
5457 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005458 case CXCursor_OMPOrderedDirective:
5459 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005460 case CXCursor_OMPAtomicDirective:
5461 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005462 case CXCursor_OMPTargetDirective:
5463 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005464 case CXCursor_OMPTargetDataDirective:
5465 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005466 case CXCursor_OMPTargetEnterDataDirective:
5467 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005468 case CXCursor_OMPTargetExitDataDirective:
5469 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005470 case CXCursor_OMPTargetParallelDirective:
5471 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005472 case CXCursor_OMPTargetParallelForDirective:
5473 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005474 case CXCursor_OMPTargetUpdateDirective:
5475 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005476 case CXCursor_OMPTeamsDirective:
5477 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005478 case CXCursor_OMPCancellationPointDirective:
5479 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005480 case CXCursor_OMPCancelDirective:
5481 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005482 case CXCursor_OMPTaskLoopDirective:
5483 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005484 case CXCursor_OMPTaskLoopSimdDirective:
5485 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005486 case CXCursor_OMPMasterTaskLoopDirective:
5487 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005488 case CXCursor_OMPMasterTaskLoopSimdDirective:
5489 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005490 case CXCursor_OMPParallelMasterTaskLoopDirective:
5491 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005492 case CXCursor_OMPDistributeDirective:
5493 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005494 case CXCursor_OMPDistributeParallelForDirective:
5495 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005496 case CXCursor_OMPDistributeParallelForSimdDirective:
5497 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005498 case CXCursor_OMPDistributeSimdDirective:
5499 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005500 case CXCursor_OMPTargetParallelForSimdDirective:
5501 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005502 case CXCursor_OMPTargetSimdDirective:
5503 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005504 case CXCursor_OMPTeamsDistributeDirective:
5505 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005506 case CXCursor_OMPTeamsDistributeSimdDirective:
5507 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005508 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5509 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005510 case CXCursor_OMPTeamsDistributeParallelForDirective:
5511 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005512 case CXCursor_OMPTargetTeamsDirective:
5513 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005514 case CXCursor_OMPTargetTeamsDistributeDirective:
5515 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005516 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5517 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005518 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5519 return cxstring::createRef(
5520 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005521 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5522 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005523 case CXCursor_OverloadCandidate:
5524 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005525 case CXCursor_TypeAliasTemplateDecl:
5526 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005527 case CXCursor_StaticAssert:
5528 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005529 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005530 return cxstring::createRef("FriendDecl");
5531 case CXCursor_ConvergentAttr:
5532 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005533 case CXCursor_WarnUnusedAttr:
5534 return cxstring::createRef("attribute(warn_unused)");
5535 case CXCursor_WarnUnusedResultAttr:
5536 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005537 case CXCursor_AlignedAttr:
5538 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 }
5540
5541 llvm_unreachable("Unhandled CXCursorKind");
5542}
5543
5544struct GetCursorData {
5545 SourceLocation TokenBeginLoc;
5546 bool PointsAtMacroArgExpansion;
5547 bool VisitedObjCPropertyImplDecl;
5548 SourceLocation VisitedDeclaratorDeclStartLoc;
5549 CXCursor &BestCursor;
5550
5551 GetCursorData(SourceManager &SM,
5552 SourceLocation tokenBegin, CXCursor &outputCursor)
5553 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5554 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5555 VisitedObjCPropertyImplDecl = false;
5556 }
5557};
5558
5559static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5560 CXCursor parent,
5561 CXClientData client_data) {
5562 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5563 CXCursor *BestCursor = &Data->BestCursor;
5564
5565 // If we point inside a macro argument we should provide info of what the
5566 // token is so use the actual cursor, don't replace it with a macro expansion
5567 // cursor.
5568 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5569 return CXChildVisit_Recurse;
5570
5571 if (clang_isDeclaration(cursor.kind)) {
5572 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005573 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005574 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5575 if (MD->isImplicit())
5576 return CXChildVisit_Break;
5577
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005578 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005579 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5580 // Check that when we have multiple @class references in the same line,
5581 // that later ones do not override the previous ones.
5582 // If we have:
5583 // @class Foo, Bar;
5584 // source ranges for both start at '@', so 'Bar' will end up overriding
5585 // 'Foo' even though the cursor location was at 'Foo'.
5586 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5587 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005588 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005589 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5590 if (PrevID != ID &&
5591 !PrevID->isThisDeclarationADefinition() &&
5592 !ID->isThisDeclarationADefinition())
5593 return CXChildVisit_Break;
5594 }
5595
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005596 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005597 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5598 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5599 // Check that when we have multiple declarators in the same line,
5600 // that later ones do not override the previous ones.
5601 // If we have:
5602 // int Foo, Bar;
5603 // source ranges for both start at 'int', so 'Bar' will end up overriding
5604 // 'Foo' even though the cursor location was at 'Foo'.
5605 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5606 return CXChildVisit_Break;
5607 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5608
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005609 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005610 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5611 (void)PropImp;
5612 // Check that when we have multiple @synthesize in the same line,
5613 // that later ones do not override the previous ones.
5614 // If we have:
5615 // @synthesize Foo, Bar;
5616 // source ranges for both start at '@', so 'Bar' will end up overriding
5617 // 'Foo' even though the cursor location was at 'Foo'.
5618 if (Data->VisitedObjCPropertyImplDecl)
5619 return CXChildVisit_Break;
5620 Data->VisitedObjCPropertyImplDecl = true;
5621 }
5622 }
5623
5624 if (clang_isExpression(cursor.kind) &&
5625 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005626 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005627 // Avoid having the cursor of an expression replace the declaration cursor
5628 // when the expression source range overlaps the declaration range.
5629 // This can happen for C++ constructor expressions whose range generally
5630 // include the variable declaration, e.g.:
5631 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5632 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5633 D->getLocation() == Data->TokenBeginLoc)
5634 return CXChildVisit_Break;
5635 }
5636 }
5637
5638 // If our current best cursor is the construction of a temporary object,
5639 // don't replace that cursor with a type reference, because we want
5640 // clang_getCursor() to point at the constructor.
5641 if (clang_isExpression(BestCursor->kind) &&
5642 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5643 cursor.kind == CXCursor_TypeRef) {
5644 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5645 // as having the actual point on the type reference.
5646 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5647 return CXChildVisit_Recurse;
5648 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005649
5650 // If we already have an Objective-C superclass reference, don't
5651 // update it further.
5652 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5653 return CXChildVisit_Break;
5654
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 *BestCursor = cursor;
5656 return CXChildVisit_Recurse;
5657}
5658
5659CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005660 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005661 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005663 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005664
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005665 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005666 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5667
5668 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5669 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5670
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005671 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005672 CXFile SearchFile;
5673 unsigned SearchLine, SearchColumn;
5674 CXFile ResultFile;
5675 unsigned ResultLine, ResultColumn;
5676 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5677 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5678 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005679
5680 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5681 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005682 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005683 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005684 SearchFileName = clang_getFileName(SearchFile);
5685 ResultFileName = clang_getFileName(ResultFile);
5686 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5687 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005688 *Log << llvm::format("(%s:%d:%d) = %s",
5689 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5690 clang_getCString(KindSpelling))
5691 << llvm::format("(%s:%d:%d):%s%s",
5692 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5693 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005694 clang_disposeString(SearchFileName);
5695 clang_disposeString(ResultFileName);
5696 clang_disposeString(KindSpelling);
5697 clang_disposeString(USR);
5698
5699 CXCursor Definition = clang_getCursorDefinition(Result);
5700 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5701 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5702 CXString DefinitionKindSpelling
5703 = clang_getCursorKindSpelling(Definition.kind);
5704 CXFile DefinitionFile;
5705 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005706 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005707 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005708 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005709 *Log << llvm::format(" -> %s(%s:%d:%d)",
5710 clang_getCString(DefinitionKindSpelling),
5711 clang_getCString(DefinitionFileName),
5712 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005713 clang_disposeString(DefinitionFileName);
5714 clang_disposeString(DefinitionKindSpelling);
5715 }
5716 }
5717
5718 return Result;
5719}
5720
5721CXCursor clang_getNullCursor(void) {
5722 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5723}
5724
5725unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005726 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5727 // can't set consistently. For example, when visiting a DeclStmt we will set
5728 // it but we don't set it on the result of clang_getCursorDefinition for
5729 // a reference of the same declaration.
5730 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5731 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5732 // to provide that kind of info.
5733 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005734 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005735 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005736 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005737
Guy Benyei11169dd2012-12-18 14:30:41 +00005738 return X == Y;
5739}
5740
5741unsigned clang_hashCursor(CXCursor C) {
5742 unsigned Index = 0;
5743 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5744 Index = 1;
5745
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005746 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005747 std::make_pair(C.kind, C.data[Index]));
5748}
5749
5750unsigned clang_isInvalid(enum CXCursorKind K) {
5751 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5752}
5753
5754unsigned clang_isDeclaration(enum CXCursorKind K) {
5755 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005756 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5757}
5758
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005759unsigned clang_isInvalidDeclaration(CXCursor C) {
5760 if (clang_isDeclaration(C.kind)) {
5761 if (const Decl *D = getCursorDecl(C))
5762 return D->isInvalidDecl();
5763 }
5764
5765 return 0;
5766}
5767
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005768unsigned clang_isReference(enum CXCursorKind K) {
5769 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5770}
Guy Benyei11169dd2012-12-18 14:30:41 +00005771
5772unsigned clang_isExpression(enum CXCursorKind K) {
5773 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5774}
5775
5776unsigned clang_isStatement(enum CXCursorKind K) {
5777 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5778}
5779
5780unsigned clang_isAttribute(enum CXCursorKind K) {
5781 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5782}
5783
5784unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5785 return K == CXCursor_TranslationUnit;
5786}
5787
5788unsigned clang_isPreprocessing(enum CXCursorKind K) {
5789 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5790}
5791
5792unsigned clang_isUnexposed(enum CXCursorKind K) {
5793 switch (K) {
5794 case CXCursor_UnexposedDecl:
5795 case CXCursor_UnexposedExpr:
5796 case CXCursor_UnexposedStmt:
5797 case CXCursor_UnexposedAttr:
5798 return true;
5799 default:
5800 return false;
5801 }
5802}
5803
5804CXCursorKind clang_getCursorKind(CXCursor C) {
5805 return C.kind;
5806}
5807
5808CXSourceLocation clang_getCursorLocation(CXCursor C) {
5809 if (clang_isReference(C.kind)) {
5810 switch (C.kind) {
5811 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005812 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005813 = getCursorObjCSuperClassRef(C);
5814 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5815 }
5816
5817 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005818 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005819 = getCursorObjCProtocolRef(C);
5820 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5821 }
5822
5823 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005824 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005825 = getCursorObjCClassRef(C);
5826 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5827 }
5828
5829 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005830 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005831 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5832 }
5833
5834 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005835 std::pair<const TemplateDecl *, SourceLocation> P =
5836 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005837 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5838 }
5839
5840 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005841 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005842 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5843 }
5844
5845 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005846 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005847 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5848 }
5849
5850 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005851 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005852 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5853 }
5854
5855 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005856 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005857 if (!BaseSpec)
5858 return clang_getNullLocation();
5859
5860 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5861 return cxloc::translateSourceLocation(getCursorContext(C),
5862 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005863
Guy Benyei11169dd2012-12-18 14:30:41 +00005864 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005865 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005866 }
5867
5868 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005869 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005870 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5871 }
5872
5873 case CXCursor_OverloadedDeclRef:
5874 return cxloc::translateSourceLocation(getCursorContext(C),
5875 getCursorOverloadedDeclRef(C).second);
5876
5877 default:
5878 // FIXME: Need a way to enumerate all non-reference cases.
5879 llvm_unreachable("Missed a reference kind");
5880 }
5881 }
5882
5883 if (clang_isExpression(C.kind))
5884 return cxloc::translateSourceLocation(getCursorContext(C),
5885 getLocationFromExpr(getCursorExpr(C)));
5886
5887 if (clang_isStatement(C.kind))
5888 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005889 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005890
5891 if (C.kind == CXCursor_PreprocessingDirective) {
5892 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5893 return cxloc::translateSourceLocation(getCursorContext(C), L);
5894 }
5895
5896 if (C.kind == CXCursor_MacroExpansion) {
5897 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005898 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005899 return cxloc::translateSourceLocation(getCursorContext(C), L);
5900 }
5901
5902 if (C.kind == CXCursor_MacroDefinition) {
5903 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5904 return cxloc::translateSourceLocation(getCursorContext(C), L);
5905 }
5906
5907 if (C.kind == CXCursor_InclusionDirective) {
5908 SourceLocation L
5909 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5910 return cxloc::translateSourceLocation(getCursorContext(C), L);
5911 }
5912
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005913 if (clang_isAttribute(C.kind)) {
5914 SourceLocation L
5915 = cxcursor::getCursorAttr(C)->getLocation();
5916 return cxloc::translateSourceLocation(getCursorContext(C), L);
5917 }
5918
Guy Benyei11169dd2012-12-18 14:30:41 +00005919 if (!clang_isDeclaration(C.kind))
5920 return clang_getNullLocation();
5921
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005922 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005923 if (!D)
5924 return clang_getNullLocation();
5925
5926 SourceLocation Loc = D->getLocation();
5927 // FIXME: Multiple variables declared in a single declaration
5928 // currently lack the information needed to correctly determine their
5929 // ranges when accounting for the type-specifier. We use context
5930 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5931 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005932 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005933 if (!cxcursor::isFirstInDeclGroup(C))
5934 Loc = VD->getLocation();
5935 }
5936
5937 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005938 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005939 Loc = MD->getSelectorStartLoc();
5940
5941 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5942}
5943
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005944} // end extern "C"
5945
Guy Benyei11169dd2012-12-18 14:30:41 +00005946CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5947 assert(TU);
5948
5949 // Guard against an invalid SourceLocation, or we may assert in one
5950 // of the following calls.
5951 if (SLoc.isInvalid())
5952 return clang_getNullCursor();
5953
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005954 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005955
5956 // Translate the given source location to make it point at the beginning of
5957 // the token under the cursor.
5958 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5959 CXXUnit->getASTContext().getLangOpts());
5960
5961 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5962 if (SLoc.isValid()) {
5963 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5964 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5965 /*VisitPreprocessorLast=*/true,
5966 /*VisitIncludedEntities=*/false,
5967 SourceLocation(SLoc));
5968 CursorVis.visitFileRegion();
5969 }
5970
5971 return Result;
5972}
5973
5974static SourceRange getRawCursorExtent(CXCursor C) {
5975 if (clang_isReference(C.kind)) {
5976 switch (C.kind) {
5977 case CXCursor_ObjCSuperClassRef:
5978 return getCursorObjCSuperClassRef(C).second;
5979
5980 case CXCursor_ObjCProtocolRef:
5981 return getCursorObjCProtocolRef(C).second;
5982
5983 case CXCursor_ObjCClassRef:
5984 return getCursorObjCClassRef(C).second;
5985
5986 case CXCursor_TypeRef:
5987 return getCursorTypeRef(C).second;
5988
5989 case CXCursor_TemplateRef:
5990 return getCursorTemplateRef(C).second;
5991
5992 case CXCursor_NamespaceRef:
5993 return getCursorNamespaceRef(C).second;
5994
5995 case CXCursor_MemberRef:
5996 return getCursorMemberRef(C).second;
5997
5998 case CXCursor_CXXBaseSpecifier:
5999 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6000
6001 case CXCursor_LabelRef:
6002 return getCursorLabelRef(C).second;
6003
6004 case CXCursor_OverloadedDeclRef:
6005 return getCursorOverloadedDeclRef(C).second;
6006
6007 case CXCursor_VariableRef:
6008 return getCursorVariableRef(C).second;
6009
6010 default:
6011 // FIXME: Need a way to enumerate all non-reference cases.
6012 llvm_unreachable("Missed a reference kind");
6013 }
6014 }
6015
6016 if (clang_isExpression(C.kind))
6017 return getCursorExpr(C)->getSourceRange();
6018
6019 if (clang_isStatement(C.kind))
6020 return getCursorStmt(C)->getSourceRange();
6021
6022 if (clang_isAttribute(C.kind))
6023 return getCursorAttr(C)->getRange();
6024
6025 if (C.kind == CXCursor_PreprocessingDirective)
6026 return cxcursor::getCursorPreprocessingDirective(C);
6027
6028 if (C.kind == CXCursor_MacroExpansion) {
6029 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006030 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006031 return TU->mapRangeFromPreamble(Range);
6032 }
6033
6034 if (C.kind == CXCursor_MacroDefinition) {
6035 ASTUnit *TU = getCursorASTUnit(C);
6036 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6037 return TU->mapRangeFromPreamble(Range);
6038 }
6039
6040 if (C.kind == CXCursor_InclusionDirective) {
6041 ASTUnit *TU = getCursorASTUnit(C);
6042 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6043 return TU->mapRangeFromPreamble(Range);
6044 }
6045
6046 if (C.kind == CXCursor_TranslationUnit) {
6047 ASTUnit *TU = getCursorASTUnit(C);
6048 FileID MainID = TU->getSourceManager().getMainFileID();
6049 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6050 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6051 return SourceRange(Start, End);
6052 }
6053
6054 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006055 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006056 if (!D)
6057 return SourceRange();
6058
6059 SourceRange R = D->getSourceRange();
6060 // FIXME: Multiple variables declared in a single declaration
6061 // currently lack the information needed to correctly determine their
6062 // ranges when accounting for the type-specifier. We use context
6063 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6064 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006065 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006066 if (!cxcursor::isFirstInDeclGroup(C))
6067 R.setBegin(VD->getLocation());
6068 }
6069 return R;
6070 }
6071 return SourceRange();
6072}
6073
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006074/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006075/// the decl-specifier-seq for declarations.
6076static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6077 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006078 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006079 if (!D)
6080 return SourceRange();
6081
6082 SourceRange R = D->getSourceRange();
6083
6084 // Adjust the start of the location for declarations preceded by
6085 // declaration specifiers.
6086 SourceLocation StartLoc;
6087 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6088 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006089 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006090 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006092 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 }
6094
6095 if (StartLoc.isValid() && R.getBegin().isValid() &&
6096 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6097 R.setBegin(StartLoc);
6098
6099 // FIXME: Multiple variables declared in a single declaration
6100 // currently lack the information needed to correctly determine their
6101 // ranges when accounting for the type-specifier. We use context
6102 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6103 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006104 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 if (!cxcursor::isFirstInDeclGroup(C))
6106 R.setBegin(VD->getLocation());
6107 }
6108
6109 return R;
6110 }
6111
6112 return getRawCursorExtent(C);
6113}
6114
Guy Benyei11169dd2012-12-18 14:30:41 +00006115CXSourceRange clang_getCursorExtent(CXCursor C) {
6116 SourceRange R = getRawCursorExtent(C);
6117 if (R.isInvalid())
6118 return clang_getNullRange();
6119
6120 return cxloc::translateSourceRange(getCursorContext(C), R);
6121}
6122
6123CXCursor clang_getCursorReferenced(CXCursor C) {
6124 if (clang_isInvalid(C.kind))
6125 return clang_getNullCursor();
6126
6127 CXTranslationUnit tu = getCursorTU(C);
6128 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006129 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006130 if (!D)
6131 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006132 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006133 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006134 if (const ObjCPropertyImplDecl *PropImpl =
6135 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6137 return MakeCXCursor(Property, tu);
6138
6139 return C;
6140 }
6141
6142 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006143 const Expr *E = getCursorExpr(C);
6144 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 if (D) {
6146 CXCursor declCursor = MakeCXCursor(D, tu);
6147 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6148 declCursor);
6149 return declCursor;
6150 }
6151
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006152 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 return MakeCursorOverloadedDeclRef(Ovl, tu);
6154
6155 return clang_getNullCursor();
6156 }
6157
6158 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006159 const Stmt *S = getCursorStmt(C);
6160 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006161 if (LabelDecl *label = Goto->getLabel())
6162 if (LabelStmt *labelS = label->getStmt())
6163 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6164
6165 return clang_getNullCursor();
6166 }
Richard Smith66a81862015-05-04 02:25:31 +00006167
Guy Benyei11169dd2012-12-18 14:30:41 +00006168 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006169 if (const MacroDefinitionRecord *Def =
6170 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 return MakeMacroDefinitionCursor(Def, tu);
6172 }
6173
6174 if (!clang_isReference(C.kind))
6175 return clang_getNullCursor();
6176
6177 switch (C.kind) {
6178 case CXCursor_ObjCSuperClassRef:
6179 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6180
6181 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006182 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6183 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006184 return MakeCXCursor(Def, tu);
6185
6186 return MakeCXCursor(Prot, tu);
6187 }
6188
6189 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006190 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6191 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 return MakeCXCursor(Def, tu);
6193
6194 return MakeCXCursor(Class, tu);
6195 }
6196
6197 case CXCursor_TypeRef:
6198 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6199
6200 case CXCursor_TemplateRef:
6201 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6202
6203 case CXCursor_NamespaceRef:
6204 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6205
6206 case CXCursor_MemberRef:
6207 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6208
6209 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006210 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006211 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6212 tu ));
6213 }
6214
6215 case CXCursor_LabelRef:
6216 // FIXME: We end up faking the "parent" declaration here because we
6217 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006218 return MakeCXCursor(getCursorLabelRef(C).first,
6219 cxtu::getASTUnit(tu)->getASTContext()
6220 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006221 tu);
6222
6223 case CXCursor_OverloadedDeclRef:
6224 return C;
6225
6226 case CXCursor_VariableRef:
6227 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6228
6229 default:
6230 // We would prefer to enumerate all non-reference cursor kinds here.
6231 llvm_unreachable("Unhandled reference cursor kind");
6232 }
6233}
6234
6235CXCursor clang_getCursorDefinition(CXCursor C) {
6236 if (clang_isInvalid(C.kind))
6237 return clang_getNullCursor();
6238
6239 CXTranslationUnit TU = getCursorTU(C);
6240
6241 bool WasReference = false;
6242 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6243 C = clang_getCursorReferenced(C);
6244 WasReference = true;
6245 }
6246
6247 if (C.kind == CXCursor_MacroExpansion)
6248 return clang_getCursorReferenced(C);
6249
6250 if (!clang_isDeclaration(C.kind))
6251 return clang_getNullCursor();
6252
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006253 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006254 if (!D)
6255 return clang_getNullCursor();
6256
6257 switch (D->getKind()) {
6258 // Declaration kinds that don't really separate the notions of
6259 // declaration and definition.
6260 case Decl::Namespace:
6261 case Decl::Typedef:
6262 case Decl::TypeAlias:
6263 case Decl::TypeAliasTemplate:
6264 case Decl::TemplateTypeParm:
6265 case Decl::EnumConstant:
6266 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006267 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006268 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006269 case Decl::IndirectField:
6270 case Decl::ObjCIvar:
6271 case Decl::ObjCAtDefsField:
6272 case Decl::ImplicitParam:
6273 case Decl::ParmVar:
6274 case Decl::NonTypeTemplateParm:
6275 case Decl::TemplateTemplateParm:
6276 case Decl::ObjCCategoryImpl:
6277 case Decl::ObjCImplementation:
6278 case Decl::AccessSpec:
6279 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006280 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006281 case Decl::ObjCPropertyImpl:
6282 case Decl::FileScopeAsm:
6283 case Decl::StaticAssert:
6284 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006285 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006286 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006287 case Decl::Label: // FIXME: Is this right??
6288 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006289 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006291 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006292 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006293 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006294 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006295 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006296 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006297 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006298 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006299 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006300 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006301 case Decl::Concept:
Guy Benyei11169dd2012-12-18 14:30:41 +00006302 return C;
6303
6304 // Declaration kinds that don't make any sense here, but are
6305 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006306 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006308 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006309 break;
6310
6311 // Declaration kinds for which the definition is not resolvable.
6312 case Decl::UnresolvedUsingTypename:
6313 case Decl::UnresolvedUsingValue:
6314 break;
6315
6316 case Decl::UsingDirective:
6317 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6318 TU);
6319
6320 case Decl::NamespaceAlias:
6321 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6322
6323 case Decl::Enum:
6324 case Decl::Record:
6325 case Decl::CXXRecord:
6326 case Decl::ClassTemplateSpecialization:
6327 case Decl::ClassTemplatePartialSpecialization:
6328 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6329 return MakeCXCursor(Def, TU);
6330 return clang_getNullCursor();
6331
6332 case Decl::Function:
6333 case Decl::CXXMethod:
6334 case Decl::CXXConstructor:
6335 case Decl::CXXDestructor:
6336 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006337 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006338 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006339 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 return clang_getNullCursor();
6341 }
6342
Larisse Voufo39a1e502013-08-06 01:03:05 +00006343 case Decl::Var:
6344 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006345 case Decl::VarTemplatePartialSpecialization:
6346 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006348 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 return MakeCXCursor(Def, TU);
6350 return clang_getNullCursor();
6351 }
6352
6353 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006354 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006355 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6356 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6357 return clang_getNullCursor();
6358 }
6359
6360 case Decl::ClassTemplate: {
6361 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6362 ->getDefinition())
6363 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6364 TU);
6365 return clang_getNullCursor();
6366 }
6367
Larisse Voufo39a1e502013-08-06 01:03:05 +00006368 case Decl::VarTemplate: {
6369 if (VarDecl *Def =
6370 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6371 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6372 return clang_getNullCursor();
6373 }
6374
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 case Decl::Using:
6376 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6377 D->getLocation(), TU);
6378
6379 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006380 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 return clang_getCursorDefinition(
6382 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6383 TU));
6384
6385 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006386 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006387 if (Method->isThisDeclarationADefinition())
6388 return C;
6389
6390 // Dig out the method definition in the associated
6391 // @implementation, if we have it.
6392 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006393 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6395 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6396 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6397 Method->isInstanceMethod()))
6398 if (Def->isThisDeclarationADefinition())
6399 return MakeCXCursor(Def, TU);
6400
6401 return clang_getNullCursor();
6402 }
6403
6404 case Decl::ObjCCategory:
6405 if (ObjCCategoryImplDecl *Impl
6406 = cast<ObjCCategoryDecl>(D)->getImplementation())
6407 return MakeCXCursor(Impl, TU);
6408 return clang_getNullCursor();
6409
6410 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006411 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 return MakeCXCursor(Def, TU);
6413 return clang_getNullCursor();
6414
6415 case Decl::ObjCInterface: {
6416 // There are two notions of a "definition" for an Objective-C
6417 // class: the interface and its implementation. When we resolved a
6418 // reference to an Objective-C class, produce the @interface as
6419 // the definition; when we were provided with the interface,
6420 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006421 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006423 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006424 return MakeCXCursor(Def, TU);
6425 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6426 return MakeCXCursor(Impl, TU);
6427 return clang_getNullCursor();
6428 }
6429
6430 case Decl::ObjCProperty:
6431 // FIXME: We don't really know where to find the
6432 // ObjCPropertyImplDecls that implement this property.
6433 return clang_getNullCursor();
6434
6435 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006436 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006437 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006438 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 return MakeCXCursor(Def, TU);
6440
6441 return clang_getNullCursor();
6442
6443 case Decl::Friend:
6444 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6445 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6446 return clang_getNullCursor();
6447
6448 case Decl::FriendTemplate:
6449 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6450 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6451 return clang_getNullCursor();
6452 }
6453
6454 return clang_getNullCursor();
6455}
6456
6457unsigned clang_isCursorDefinition(CXCursor C) {
6458 if (!clang_isDeclaration(C.kind))
6459 return 0;
6460
6461 return clang_getCursorDefinition(C) == C;
6462}
6463
6464CXCursor clang_getCanonicalCursor(CXCursor C) {
6465 if (!clang_isDeclaration(C.kind))
6466 return C;
6467
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006468 if (const Decl *D = getCursorDecl(C)) {
6469 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006470 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6471 return MakeCXCursor(CatD, getCursorTU(C));
6472
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006473 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6474 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 return MakeCXCursor(IFD, getCursorTU(C));
6476
6477 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6478 }
6479
6480 return C;
6481}
6482
6483int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6484 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6485}
6486
6487unsigned clang_getNumOverloadedDecls(CXCursor C) {
6488 if (C.kind != CXCursor_OverloadedDeclRef)
6489 return 0;
6490
6491 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006492 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006493 return E->getNumDecls();
6494
6495 if (OverloadedTemplateStorage *S
6496 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6497 return S->size();
6498
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006499 const Decl *D = Storage.get<const Decl *>();
6500 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006501 return Using->shadow_size();
6502
6503 return 0;
6504}
6505
6506CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6507 if (cursor.kind != CXCursor_OverloadedDeclRef)
6508 return clang_getNullCursor();
6509
6510 if (index >= clang_getNumOverloadedDecls(cursor))
6511 return clang_getNullCursor();
6512
6513 CXTranslationUnit TU = getCursorTU(cursor);
6514 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006515 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006516 return MakeCXCursor(E->decls_begin()[index], TU);
6517
6518 if (OverloadedTemplateStorage *S
6519 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6520 return MakeCXCursor(S->begin()[index], TU);
6521
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006522 const Decl *D = Storage.get<const Decl *>();
6523 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006524 // FIXME: This is, unfortunately, linear time.
6525 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6526 std::advance(Pos, index);
6527 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6528 }
6529
6530 return clang_getNullCursor();
6531}
6532
6533void clang_getDefinitionSpellingAndExtent(CXCursor C,
6534 const char **startBuf,
6535 const char **endBuf,
6536 unsigned *startLine,
6537 unsigned *startColumn,
6538 unsigned *endLine,
6539 unsigned *endColumn) {
6540 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006541 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006542 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6543
6544 SourceManager &SM = FD->getASTContext().getSourceManager();
6545 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6546 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6547 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6548 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6549 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6550 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6551}
6552
6553
6554CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6555 unsigned PieceIndex) {
6556 RefNamePieces Pieces;
6557
6558 switch (C.kind) {
6559 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006560 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006561 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6562 E->getQualifierLoc().getSourceRange());
6563 break;
6564
6565 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006566 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6567 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6568 Pieces =
6569 buildPieces(NameFlags, false, E->getNameInfo(),
6570 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6571 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006572 break;
6573
6574 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006575 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006576 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006577 const Expr *Callee = OCE->getCallee();
6578 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006579 Callee = ICE->getSubExpr();
6580
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006581 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006582 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6583 DRE->getQualifierLoc().getSourceRange());
6584 }
6585 break;
6586
6587 default:
6588 break;
6589 }
6590
6591 if (Pieces.empty()) {
6592 if (PieceIndex == 0)
6593 return clang_getCursorExtent(C);
6594 } else if (PieceIndex < Pieces.size()) {
6595 SourceRange R = Pieces[PieceIndex];
6596 if (R.isValid())
6597 return cxloc::translateSourceRange(getCursorContext(C), R);
6598 }
6599
6600 return clang_getNullRange();
6601}
6602
6603void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006604 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6605 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006606}
6607
6608void clang_executeOnThread(void (*fn)(void*), void *user_data,
6609 unsigned stack_size) {
Sam McCalla9c3c172019-10-23 15:34:48 +02006610 llvm::llvm_execute_on_thread(
6611 fn, user_data,
6612 stack_size == 0 ? llvm::None : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006613}
6614
Guy Benyei11169dd2012-12-18 14:30:41 +00006615//===----------------------------------------------------------------------===//
6616// Token-based Operations.
6617//===----------------------------------------------------------------------===//
6618
6619/* CXToken layout:
6620 * int_data[0]: a CXTokenKind
6621 * int_data[1]: starting token location
6622 * int_data[2]: token length
6623 * int_data[3]: reserved
6624 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6625 * otherwise unused.
6626 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006627CXTokenKind clang_getTokenKind(CXToken CXTok) {
6628 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6629}
6630
6631CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6632 switch (clang_getTokenKind(CXTok)) {
6633 case CXToken_Identifier:
6634 case CXToken_Keyword:
6635 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006636 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006637 ->getNameStart());
6638
6639 case CXToken_Literal: {
6640 // We have stashed the starting pointer in the ptr_data field. Use it.
6641 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006642 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006643 }
6644
6645 case CXToken_Punctuation:
6646 case CXToken_Comment:
6647 break;
6648 }
6649
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006650 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006651 LOG_BAD_TU(TU);
6652 return cxstring::createEmpty();
6653 }
6654
Guy Benyei11169dd2012-12-18 14:30:41 +00006655 // We have to find the starting buffer pointer the hard way, by
6656 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006657 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006658 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006659 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006660
6661 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6662 std::pair<FileID, unsigned> LocInfo
6663 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6664 bool Invalid = false;
6665 StringRef Buffer
6666 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6667 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006668 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006669
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006670 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006671}
6672
6673CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006674 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006675 LOG_BAD_TU(TU);
6676 return clang_getNullLocation();
6677 }
6678
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006679 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006680 if (!CXXUnit)
6681 return clang_getNullLocation();
6682
6683 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6684 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6685}
6686
6687CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006688 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006689 LOG_BAD_TU(TU);
6690 return clang_getNullRange();
6691 }
6692
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006693 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 if (!CXXUnit)
6695 return clang_getNullRange();
6696
6697 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6698 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6699}
6700
6701static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6702 SmallVectorImpl<CXToken> &CXTokens) {
6703 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6704 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006705 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006707 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006708
6709 // Cannot tokenize across files.
6710 if (BeginLocInfo.first != EndLocInfo.first)
6711 return;
6712
6713 // Create a lexer
6714 bool Invalid = false;
6715 StringRef Buffer
6716 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6717 if (Invalid)
6718 return;
6719
6720 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6721 CXXUnit->getASTContext().getLangOpts(),
6722 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6723 Lex.SetCommentRetentionState(true);
6724
6725 // Lex tokens until we hit the end of the range.
6726 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6727 Token Tok;
6728 bool previousWasAt = false;
6729 do {
6730 // Lex the next token
6731 Lex.LexFromRawLexer(Tok);
6732 if (Tok.is(tok::eof))
6733 break;
6734
6735 // Initialize the CXToken.
6736 CXToken CXTok;
6737
6738 // - Common fields
6739 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6740 CXTok.int_data[2] = Tok.getLength();
6741 CXTok.int_data[3] = 0;
6742
6743 // - Kind-specific fields
6744 if (Tok.isLiteral()) {
6745 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006746 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006747 } else if (Tok.is(tok::raw_identifier)) {
6748 // Lookup the identifier to determine whether we have a keyword.
6749 IdentifierInfo *II
6750 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6751
6752 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6753 CXTok.int_data[0] = CXToken_Keyword;
6754 }
6755 else {
6756 CXTok.int_data[0] = Tok.is(tok::identifier)
6757 ? CXToken_Identifier
6758 : CXToken_Keyword;
6759 }
6760 CXTok.ptr_data = II;
6761 } else if (Tok.is(tok::comment)) {
6762 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006763 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006764 } else {
6765 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006766 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006767 }
6768 CXTokens.push_back(CXTok);
6769 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006770 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006771}
6772
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006773CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6774 LOG_FUNC_SECTION {
6775 *Log << TU << ' ' << Location;
6776 }
6777
6778 if (isNotUsableTU(TU)) {
6779 LOG_BAD_TU(TU);
6780 return NULL;
6781 }
6782
6783 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6784 if (!CXXUnit)
6785 return NULL;
6786
6787 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6788 if (Begin.isInvalid())
6789 return NULL;
6790 SourceManager &SM = CXXUnit->getSourceManager();
6791 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6792 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6793
6794 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6795
6796 SmallVector<CXToken, 32> CXTokens;
6797 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6798
6799 if (CXTokens.empty())
6800 return NULL;
6801
6802 CXTokens.resize(1);
6803 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6804
6805 memmove(Token, CXTokens.data(), sizeof(CXToken));
6806 return Token;
6807}
6808
Guy Benyei11169dd2012-12-18 14:30:41 +00006809void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6810 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006811 LOG_FUNC_SECTION {
6812 *Log << TU << ' ' << Range;
6813 }
6814
Guy Benyei11169dd2012-12-18 14:30:41 +00006815 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006816 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006817 if (NumTokens)
6818 *NumTokens = 0;
6819
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006820 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006821 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006822 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006823 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006824
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006825 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006826 if (!CXXUnit || !Tokens || !NumTokens)
6827 return;
6828
6829 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6830
6831 SourceRange R = cxloc::translateCXSourceRange(Range);
6832 if (R.isInvalid())
6833 return;
6834
6835 SmallVector<CXToken, 32> CXTokens;
6836 getTokens(CXXUnit, R, CXTokens);
6837
6838 if (CXTokens.empty())
6839 return;
6840
Serge Pavlov52525732018-02-21 02:02:39 +00006841 *Tokens = static_cast<CXToken *>(
6842 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006843 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6844 *NumTokens = CXTokens.size();
6845}
6846
6847void clang_disposeTokens(CXTranslationUnit TU,
6848 CXToken *Tokens, unsigned NumTokens) {
6849 free(Tokens);
6850}
6851
Guy Benyei11169dd2012-12-18 14:30:41 +00006852//===----------------------------------------------------------------------===//
6853// Token annotation APIs.
6854//===----------------------------------------------------------------------===//
6855
Guy Benyei11169dd2012-12-18 14:30:41 +00006856static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6857 CXCursor parent,
6858 CXClientData client_data);
6859static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6860 CXClientData client_data);
6861
6862namespace {
6863class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006864 CXToken *Tokens;
6865 CXCursor *Cursors;
6866 unsigned NumTokens;
6867 unsigned TokIdx;
6868 unsigned PreprocessingTokIdx;
6869 CursorVisitor AnnotateVis;
6870 SourceManager &SrcMgr;
6871 bool HasContextSensitiveKeywords;
6872
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006873 struct PostChildrenAction {
6874 CXCursor cursor;
6875 enum Action { Invalid, Ignore, Postpone } action;
6876 };
6877 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6878
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 struct PostChildrenInfo {
6880 CXCursor Cursor;
6881 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006882 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006883 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006884 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006885 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006886 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006887
6888 CXToken &getTok(unsigned Idx) {
6889 assert(Idx < NumTokens);
6890 return Tokens[Idx];
6891 }
6892 const CXToken &getTok(unsigned Idx) const {
6893 assert(Idx < NumTokens);
6894 return Tokens[Idx];
6895 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006896 bool MoreTokens() const { return TokIdx < NumTokens; }
6897 unsigned NextToken() const { return TokIdx; }
6898 void AdvanceToken() { ++TokIdx; }
6899 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006900 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006901 }
6902 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006903 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006904 }
6905 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006906 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 }
6908
6909 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006910 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006911 SourceRange);
6912
6913public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006914 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006915 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006916 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006917 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006918 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006919 AnnotateTokensVisitor, this,
6920 /*VisitPreprocessorLast=*/true,
6921 /*VisitIncludedEntities=*/false,
6922 RegionOfInterest,
6923 /*VisitDeclsOnly=*/false,
6924 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006925 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 HasContextSensitiveKeywords(false) { }
6927
6928 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6929 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006930 bool IsIgnoredChildCursor(CXCursor cursor) const;
6931 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6932
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006934 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6935 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6936
Guy Benyei11169dd2012-12-18 14:30:41 +00006937 void AnnotateTokens();
6938
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006939 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 /// context-sensitive keywords.
6941 bool hasContextSensitiveKeywords() const {
6942 return HasContextSensitiveKeywords;
6943 }
6944
6945 ~AnnotateTokensWorker() {
6946 assert(PostChildrenInfos.empty());
6947 }
6948};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006949}
Guy Benyei11169dd2012-12-18 14:30:41 +00006950
6951void AnnotateTokensWorker::AnnotateTokens() {
6952 // Walk the AST within the region of interest, annotating tokens
6953 // along the way.
6954 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006955}
Guy Benyei11169dd2012-12-18 14:30:41 +00006956
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006957bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6958 if (PostChildrenInfos.empty())
6959 return false;
6960
6961 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6962 if (ChildAction.cursor == cursor &&
6963 ChildAction.action == PostChildrenAction::Ignore) {
6964 return true;
6965 }
6966 }
6967
6968 return false;
6969}
6970
6971const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6972 if (!clang_isExpression(Cursor.kind))
6973 return nullptr;
6974
6975 const Expr *E = getCursorExpr(Cursor);
6976 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6977 const OverloadedOperatorKind Kind = OCE->getOperator();
6978 if (Kind == OO_Call || Kind == OO_Subscript)
6979 return OCE;
6980 }
6981
6982 return nullptr;
6983}
6984
6985AnnotateTokensWorker::PostChildrenActions
6986AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6987 PostChildrenActions actions;
6988
6989 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6990 // visited before the arguments to the operator call. For the Call and
6991 // Subscript operator the range of this DeclRefExpr includes the whole call
6992 // expression, so that all tokens in that range would be mapped to the
6993 // operator function, including the tokens of the arguments. To avoid that,
6994 // ensure to visit this DeclRefExpr as last node.
6995 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6996 const Expr *Callee = OCE->getCallee();
6997 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6998 const Expr *SubExpr = ICE->getSubExpr();
6999 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007000 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007001 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7002
7003 // Visit the DeclRefExpr as last.
7004 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7005 actions.push_back({cxChild, PostChildrenAction::Postpone});
7006
7007 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7008 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7009 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7010 actions.push_back({cxChild, PostChildrenAction::Ignore});
7011 }
7012 }
7013 }
7014
7015 return actions;
7016}
7017
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007018static inline void updateCursorAnnotation(CXCursor &Cursor,
7019 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007020 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007021 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007022 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007023}
7024
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007025/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007026//// between the cursor location and the source range is the same as
7027/// \arg compResult.
7028///
7029/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7030/// Pass RangeOverlap to annotate tokens inside a range.
7031void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7032 RangeComparisonResult compResult,
7033 SourceRange range) {
7034 while (MoreTokens()) {
7035 const unsigned I = NextToken();
7036 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007037 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7038 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007039
7040 SourceLocation TokLoc = GetTokenLoc(I);
7041 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007042 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007043 AdvanceToken();
7044 continue;
7045 }
7046 break;
7047 }
7048}
7049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007050/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007051/// \returns true if it advanced beyond all macro tokens, false otherwise.
7052bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007053 CXCursor updateC,
7054 RangeComparisonResult compResult,
7055 SourceRange range) {
7056 assert(MoreTokens());
7057 assert(isFunctionMacroToken(NextToken()) &&
7058 "Should be called only for macro arg tokens");
7059
7060 // This works differently than annotateAndAdvanceTokens; because expanded
7061 // macro arguments can have arbitrary translation-unit source order, we do not
7062 // advance the token index one by one until a token fails the range test.
7063 // We only advance once past all of the macro arg tokens if all of them
7064 // pass the range test. If one of them fails we keep the token index pointing
7065 // at the start of the macro arg tokens so that the failing token will be
7066 // annotated by a subsequent annotation try.
7067
7068 bool atLeastOneCompFail = false;
7069
7070 unsigned I = NextToken();
7071 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7072 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7073 if (TokLoc.isFileID())
7074 continue; // not macro arg token, it's parens or comma.
7075 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7076 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7077 Cursors[I] = updateC;
7078 } else
7079 atLeastOneCompFail = true;
7080 }
7081
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007082 if (atLeastOneCompFail)
7083 return false;
7084
7085 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7086 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007087}
7088
7089enum CXChildVisitResult
7090AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007091 SourceRange cursorRange = getRawCursorExtent(cursor);
7092 if (cursorRange.isInvalid())
7093 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007094
7095 if (IsIgnoredChildCursor(cursor))
7096 return CXChildVisit_Continue;
7097
Guy Benyei11169dd2012-12-18 14:30:41 +00007098 if (!HasContextSensitiveKeywords) {
7099 // Objective-C properties can have context-sensitive keywords.
7100 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007101 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007102 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7103 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7104 }
7105 // Objective-C methods can have context-sensitive keywords.
7106 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7107 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007108 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007109 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7110 if (Method->getObjCDeclQualifier())
7111 HasContextSensitiveKeywords = true;
7112 else {
David Majnemer59f77922016-06-24 04:05:48 +00007113 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007114 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007115 HasContextSensitiveKeywords = true;
7116 break;
7117 }
7118 }
7119 }
7120 }
7121 }
7122 // C++ methods can have context-sensitive keywords.
7123 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007124 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007125 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7126 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7127 HasContextSensitiveKeywords = true;
7128 }
7129 }
7130 // C++ classes can have context-sensitive keywords.
7131 else if (cursor.kind == CXCursor_StructDecl ||
7132 cursor.kind == CXCursor_ClassDecl ||
7133 cursor.kind == CXCursor_ClassTemplate ||
7134 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007135 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007136 if (D->hasAttr<FinalAttr>())
7137 HasContextSensitiveKeywords = true;
7138 }
7139 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007140
7141 // Don't override a property annotation with its getter/setter method.
7142 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7143 parent.kind == CXCursor_ObjCPropertyDecl)
7144 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007145
7146 if (clang_isPreprocessing(cursor.kind)) {
7147 // Items in the preprocessing record are kept separate from items in
7148 // declarations, so we keep a separate token index.
7149 unsigned SavedTokIdx = TokIdx;
7150 TokIdx = PreprocessingTokIdx;
7151
7152 // Skip tokens up until we catch up to the beginning of the preprocessing
7153 // entry.
7154 while (MoreTokens()) {
7155 const unsigned I = NextToken();
7156 SourceLocation TokLoc = GetTokenLoc(I);
7157 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7158 case RangeBefore:
7159 AdvanceToken();
7160 continue;
7161 case RangeAfter:
7162 case RangeOverlap:
7163 break;
7164 }
7165 break;
7166 }
7167
7168 // Look at all of the tokens within this range.
7169 while (MoreTokens()) {
7170 const unsigned I = NextToken();
7171 SourceLocation TokLoc = GetTokenLoc(I);
7172 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7173 case RangeBefore:
7174 llvm_unreachable("Infeasible");
7175 case RangeAfter:
7176 break;
7177 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007178 // For macro expansions, just note where the beginning of the macro
7179 // expansion occurs.
7180 if (cursor.kind == CXCursor_MacroExpansion) {
7181 if (TokLoc == cursorRange.getBegin())
7182 Cursors[I] = cursor;
7183 AdvanceToken();
7184 break;
7185 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007186 // We may have already annotated macro names inside macro definitions.
7187 if (Cursors[I].kind != CXCursor_MacroExpansion)
7188 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007189 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007190 continue;
7191 }
7192 break;
7193 }
7194
7195 // Save the preprocessing token index; restore the non-preprocessing
7196 // token index.
7197 PreprocessingTokIdx = TokIdx;
7198 TokIdx = SavedTokIdx;
7199 return CXChildVisit_Recurse;
7200 }
7201
7202 if (cursorRange.isInvalid())
7203 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007204
7205 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007206 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007207 const enum CXCursorKind K = clang_getCursorKind(parent);
7208 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007209 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7210 // Attributes are annotated out-of-order, skip tokens until we reach it.
7211 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007212 ? clang_getNullCursor() : parent;
7213
7214 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7215
7216 // Avoid having the cursor of an expression "overwrite" the annotation of the
7217 // variable declaration that it belongs to.
7218 // This can happen for C++ constructor expressions whose range generally
7219 // include the variable declaration, e.g.:
7220 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007221 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007222 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007223 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007224 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007225 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7226 E->getBeginLoc() == D->getLocation() &&
7227 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007228 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007229 AdvanceToken();
7230 }
7231 }
7232 }
7233
7234 // Before recursing into the children keep some state that we are going
7235 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7236 // extra work after the child nodes are visited.
7237 // Note that we don't call VisitChildren here to avoid traversing statements
7238 // code-recursively which can blow the stack.
7239
7240 PostChildrenInfo Info;
7241 Info.Cursor = cursor;
7242 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007243 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007245 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007246 PostChildrenInfos.push_back(Info);
7247
7248 return CXChildVisit_Recurse;
7249}
7250
7251bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7252 if (PostChildrenInfos.empty())
7253 return false;
7254 const PostChildrenInfo &Info = PostChildrenInfos.back();
7255 if (!clang_equalCursors(Info.Cursor, cursor))
7256 return false;
7257
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007258 HandlePostPonedChildCursors(Info);
7259
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7261 const unsigned AfterChildren = NextToken();
7262 SourceRange cursorRange = Info.CursorRange;
7263
7264 // Scan the tokens that are at the end of the cursor, but are not captured
7265 // but the child cursors.
7266 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7267
7268 // Scan the tokens that are at the beginning of the cursor, but are not
7269 // capture by the child cursors.
7270 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7271 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7272 break;
7273
7274 Cursors[I] = cursor;
7275 }
7276
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007277 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7278 // encountered the attribute cursor.
7279 if (clang_isAttribute(cursor.kind))
7280 TokIdx = Info.BeforeReachingCursorIdx;
7281
Guy Benyei11169dd2012-12-18 14:30:41 +00007282 PostChildrenInfos.pop_back();
7283 return false;
7284}
7285
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007286void AnnotateTokensWorker::HandlePostPonedChildCursors(
7287 const PostChildrenInfo &Info) {
7288 for (const auto &ChildAction : Info.ChildActions) {
7289 if (ChildAction.action == PostChildrenAction::Postpone) {
7290 HandlePostPonedChildCursor(ChildAction.cursor,
7291 Info.BeforeChildrenTokenIdx);
7292 }
7293 }
7294}
7295
7296void AnnotateTokensWorker::HandlePostPonedChildCursor(
7297 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007298 unsigned I = StartTokenIndex;
7299
7300 // The bracket tokens of a Call or Subscript operator are mapped to
7301 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7302 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7303 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007304 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7305 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007306 if (clang_Range_isNull(CXRefNameRange))
7307 break; // All ranges handled.
7308
7309 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7310 while (I < NumTokens) {
7311 const SourceLocation TokenLocation = GetTokenLoc(I);
7312 if (!TokenLocation.isValid())
7313 break;
7314
7315 // Adapt the end range, because LocationCompare() reports
7316 // RangeOverlap even for the not-inclusive end location.
7317 const SourceLocation fixedEnd =
7318 RefNameRange.getEnd().getLocWithOffset(-1);
7319 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7320
7321 const RangeComparisonResult ComparisonResult =
7322 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7323
7324 if (ComparisonResult == RangeOverlap) {
7325 Cursors[I++] = Cursor;
7326 } else if (ComparisonResult == RangeBefore) {
7327 ++I; // Not relevant token, check next one.
7328 } else if (ComparisonResult == RangeAfter) {
7329 break; // All tokens updated for current range, check next.
7330 }
7331 }
7332 }
7333}
7334
Guy Benyei11169dd2012-12-18 14:30:41 +00007335static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7336 CXCursor parent,
7337 CXClientData client_data) {
7338 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7339}
7340
7341static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7342 CXClientData client_data) {
7343 return static_cast<AnnotateTokensWorker*>(client_data)->
7344 postVisitChildren(cursor);
7345}
7346
7347namespace {
7348
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007349/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007350/// and mark tokens that are macro arguments. This info is used by the
7351/// AnnotateTokensWorker.
7352class MarkMacroArgTokensVisitor {
7353 SourceManager &SM;
7354 CXToken *Tokens;
7355 unsigned NumTokens;
7356 unsigned CurIdx;
7357
7358public:
7359 MarkMacroArgTokensVisitor(SourceManager &SM,
7360 CXToken *tokens, unsigned numTokens)
7361 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7362
7363 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7364 if (cursor.kind != CXCursor_MacroExpansion)
7365 return CXChildVisit_Continue;
7366
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007367 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007368 if (macroRange.getBegin() == macroRange.getEnd())
7369 return CXChildVisit_Continue; // it's not a function macro.
7370
7371 for (; CurIdx < NumTokens; ++CurIdx) {
7372 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7373 macroRange.getBegin()))
7374 break;
7375 }
7376
7377 if (CurIdx == NumTokens)
7378 return CXChildVisit_Break;
7379
7380 for (; CurIdx < NumTokens; ++CurIdx) {
7381 SourceLocation tokLoc = getTokenLoc(CurIdx);
7382 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7383 break;
7384
7385 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7386 }
7387
7388 if (CurIdx == NumTokens)
7389 return CXChildVisit_Break;
7390
7391 return CXChildVisit_Continue;
7392 }
7393
7394private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007395 CXToken &getTok(unsigned Idx) {
7396 assert(Idx < NumTokens);
7397 return Tokens[Idx];
7398 }
7399 const CXToken &getTok(unsigned Idx) const {
7400 assert(Idx < NumTokens);
7401 return Tokens[Idx];
7402 }
7403
Guy Benyei11169dd2012-12-18 14:30:41 +00007404 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007405 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007406 }
7407
7408 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7409 // The third field is reserved and currently not used. Use it here
7410 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007411 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007412 }
7413};
7414
7415} // end anonymous namespace
7416
7417static CXChildVisitResult
7418MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7419 CXClientData client_data) {
7420 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7421 parent);
7422}
7423
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007424/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007425/// \returns true if lexing was finished, false otherwise.
7426static bool lexNext(Lexer &Lex, Token &Tok,
7427 unsigned &NextIdx, unsigned NumTokens) {
7428 if (NextIdx >= NumTokens)
7429 return true;
7430
7431 ++NextIdx;
7432 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007433 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007434}
7435
Guy Benyei11169dd2012-12-18 14:30:41 +00007436static void annotatePreprocessorTokens(CXTranslationUnit TU,
7437 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007438 CXCursor *Cursors,
7439 CXToken *Tokens,
7440 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007441 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007442
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007443 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007444 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7445 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007446 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007447 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007448 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007449
7450 if (BeginLocInfo.first != EndLocInfo.first)
7451 return;
7452
7453 StringRef Buffer;
7454 bool Invalid = false;
7455 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7456 if (Buffer.empty() || Invalid)
7457 return;
7458
7459 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7460 CXXUnit->getASTContext().getLangOpts(),
7461 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7462 Buffer.end());
7463 Lex.SetCommentRetentionState(true);
7464
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007465 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007466 // Lex tokens in raw mode until we hit the end of the range, to avoid
7467 // entering #includes or expanding macros.
7468 while (true) {
7469 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007470 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7471 break;
7472 unsigned TokIdx = NextIdx-1;
7473 assert(Tok.getLocation() ==
7474 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007475
7476 reprocess:
7477 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007478 // We have found a preprocessing directive. Annotate the tokens
7479 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007480 //
7481 // FIXME: Some simple tests here could identify macro definitions and
7482 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007483
7484 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007485 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7486 break;
7487
Craig Topper69186e72014-06-08 08:38:04 +00007488 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007489 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007490 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7491 break;
7492
7493 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007494 IdentifierInfo &II =
7495 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007496 SourceLocation MappedTokLoc =
7497 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7498 MI = getMacroInfo(II, MappedTokLoc, TU);
7499 }
7500 }
7501
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007502 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007503 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007504 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7505 finished = true;
7506 break;
7507 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007508 // If we are in a macro definition, check if the token was ever a
7509 // macro name and annotate it if that's the case.
7510 if (MI) {
7511 SourceLocation SaveLoc = Tok.getLocation();
7512 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007513 MacroDefinitionRecord *MacroDef =
7514 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007515 Tok.setLocation(SaveLoc);
7516 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007517 Cursors[NextIdx - 1] =
7518 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007519 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007520 } while (!Tok.isAtStartOfLine());
7521
7522 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7523 assert(TokIdx <= LastIdx);
7524 SourceLocation EndLoc =
7525 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7526 CXCursor Cursor =
7527 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7528
7529 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007530 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007531
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007532 if (finished)
7533 break;
7534 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007535 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007536 }
7537}
7538
7539// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007540static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7541 CXToken *Tokens, unsigned NumTokens,
7542 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007543 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007544 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7545 setThreadBackgroundPriority();
7546
7547 // Determine the region of interest, which contains all of the tokens.
7548 SourceRange RegionOfInterest;
7549 RegionOfInterest.setBegin(
7550 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7551 RegionOfInterest.setEnd(
7552 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7553 Tokens[NumTokens-1])));
7554
Guy Benyei11169dd2012-12-18 14:30:41 +00007555 // Relex the tokens within the source range to look for preprocessing
7556 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007557 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007558
7559 // If begin location points inside a macro argument, set it to the expansion
7560 // location so we can have the full context when annotating semantically.
7561 {
7562 SourceManager &SM = CXXUnit->getSourceManager();
7563 SourceLocation Loc =
7564 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7565 if (Loc.isMacroID())
7566 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7567 }
7568
Guy Benyei11169dd2012-12-18 14:30:41 +00007569 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7570 // Search and mark tokens that are macro argument expansions.
7571 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7572 Tokens, NumTokens);
7573 CursorVisitor MacroArgMarker(TU,
7574 MarkMacroArgTokensVisitorDelegate, &Visitor,
7575 /*VisitPreprocessorLast=*/true,
7576 /*VisitIncludedEntities=*/false,
7577 RegionOfInterest);
7578 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7579 }
7580
7581 // Annotate all of the source locations in the region of interest that map to
7582 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007583 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007584
7585 // FIXME: We use a ridiculous stack size here because the data-recursion
7586 // algorithm uses a large stack frame than the non-data recursive version,
7587 // and AnnotationTokensWorker currently transforms the data-recursion
7588 // algorithm back into a traditional recursion by explicitly calling
7589 // VisitChildren(). We will need to remove this explicit recursive call.
7590 W.AnnotateTokens();
7591
7592 // If we ran into any entities that involve context-sensitive keywords,
7593 // take another pass through the tokens to mark them as such.
7594 if (W.hasContextSensitiveKeywords()) {
7595 for (unsigned I = 0; I != NumTokens; ++I) {
7596 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7597 continue;
7598
7599 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7600 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007601 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007602 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7603 if (Property->getPropertyAttributesAsWritten() != 0 &&
7604 llvm::StringSwitch<bool>(II->getName())
7605 .Case("readonly", true)
7606 .Case("assign", true)
7607 .Case("unsafe_unretained", true)
7608 .Case("readwrite", true)
7609 .Case("retain", true)
7610 .Case("copy", true)
7611 .Case("nonatomic", true)
7612 .Case("atomic", true)
7613 .Case("getter", true)
7614 .Case("setter", true)
7615 .Case("strong", true)
7616 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007617 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007618 .Default(false))
7619 Tokens[I].int_data[0] = CXToken_Keyword;
7620 }
7621 continue;
7622 }
7623
7624 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7625 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7626 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7627 if (llvm::StringSwitch<bool>(II->getName())
7628 .Case("in", true)
7629 .Case("out", true)
7630 .Case("inout", true)
7631 .Case("oneway", true)
7632 .Case("bycopy", true)
7633 .Case("byref", true)
7634 .Default(false))
7635 Tokens[I].int_data[0] = CXToken_Keyword;
7636 continue;
7637 }
7638
7639 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7640 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7641 Tokens[I].int_data[0] = CXToken_Keyword;
7642 continue;
7643 }
7644 }
7645 }
7646}
7647
Guy Benyei11169dd2012-12-18 14:30:41 +00007648void clang_annotateTokens(CXTranslationUnit TU,
7649 CXToken *Tokens, unsigned NumTokens,
7650 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007651 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007652 LOG_BAD_TU(TU);
7653 return;
7654 }
7655 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007656 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007657 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007658 }
7659
7660 LOG_FUNC_SECTION {
7661 *Log << TU << ' ';
7662 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7663 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7664 *Log << clang_getRange(bloc, eloc);
7665 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007666
7667 // Any token we don't specifically annotate will have a NULL cursor.
7668 CXCursor C = clang_getNullCursor();
7669 for (unsigned I = 0; I != NumTokens; ++I)
7670 Cursors[I] = C;
7671
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007672 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007673 if (!CXXUnit)
7674 return;
7675
7676 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007677
7678 auto AnnotateTokensImpl = [=]() {
7679 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7680 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007681 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007682 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007683 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7684 }
7685}
7686
Guy Benyei11169dd2012-12-18 14:30:41 +00007687//===----------------------------------------------------------------------===//
7688// Operations for querying linkage of a cursor.
7689//===----------------------------------------------------------------------===//
7690
Guy Benyei11169dd2012-12-18 14:30:41 +00007691CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7692 if (!clang_isDeclaration(cursor.kind))
7693 return CXLinkage_Invalid;
7694
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007695 const Decl *D = cxcursor::getCursorDecl(cursor);
7696 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007697 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007698 case NoLinkage:
7699 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007700 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007701 case InternalLinkage: return CXLinkage_Internal;
7702 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007703 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007704 case ExternalLinkage: return CXLinkage_External;
7705 };
7706
7707 return CXLinkage_Invalid;
7708}
Guy Benyei11169dd2012-12-18 14:30:41 +00007709
7710//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007711// Operations for querying visibility of a cursor.
7712//===----------------------------------------------------------------------===//
7713
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007714CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7715 if (!clang_isDeclaration(cursor.kind))
7716 return CXVisibility_Invalid;
7717
7718 const Decl *D = cxcursor::getCursorDecl(cursor);
7719 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7720 switch (ND->getVisibility()) {
7721 case HiddenVisibility: return CXVisibility_Hidden;
7722 case ProtectedVisibility: return CXVisibility_Protected;
7723 case DefaultVisibility: return CXVisibility_Default;
7724 };
7725
7726 return CXVisibility_Invalid;
7727}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007728
7729//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007730// Operations for querying language of a cursor.
7731//===----------------------------------------------------------------------===//
7732
7733static CXLanguageKind getDeclLanguage(const Decl *D) {
7734 if (!D)
7735 return CXLanguage_C;
7736
7737 switch (D->getKind()) {
7738 default:
7739 break;
7740 case Decl::ImplicitParam:
7741 case Decl::ObjCAtDefsField:
7742 case Decl::ObjCCategory:
7743 case Decl::ObjCCategoryImpl:
7744 case Decl::ObjCCompatibleAlias:
7745 case Decl::ObjCImplementation:
7746 case Decl::ObjCInterface:
7747 case Decl::ObjCIvar:
7748 case Decl::ObjCMethod:
7749 case Decl::ObjCProperty:
7750 case Decl::ObjCPropertyImpl:
7751 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007752 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007753 return CXLanguage_ObjC;
7754 case Decl::CXXConstructor:
7755 case Decl::CXXConversion:
7756 case Decl::CXXDestructor:
7757 case Decl::CXXMethod:
7758 case Decl::CXXRecord:
7759 case Decl::ClassTemplate:
7760 case Decl::ClassTemplatePartialSpecialization:
7761 case Decl::ClassTemplateSpecialization:
7762 case Decl::Friend:
7763 case Decl::FriendTemplate:
7764 case Decl::FunctionTemplate:
7765 case Decl::LinkageSpec:
7766 case Decl::Namespace:
7767 case Decl::NamespaceAlias:
7768 case Decl::NonTypeTemplateParm:
7769 case Decl::StaticAssert:
7770 case Decl::TemplateTemplateParm:
7771 case Decl::TemplateTypeParm:
7772 case Decl::UnresolvedUsingTypename:
7773 case Decl::UnresolvedUsingValue:
7774 case Decl::Using:
7775 case Decl::UsingDirective:
7776 case Decl::UsingShadow:
7777 return CXLanguage_CPlusPlus;
7778 }
7779
7780 return CXLanguage_C;
7781}
7782
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007783static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7784 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007785 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007786
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007787 switch (D->getAvailability()) {
7788 case AR_Available:
7789 case AR_NotYetIntroduced:
7790 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007791 return getCursorAvailabilityForDecl(
7792 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007793 return CXAvailability_Available;
7794
7795 case AR_Deprecated:
7796 return CXAvailability_Deprecated;
7797
7798 case AR_Unavailable:
7799 return CXAvailability_NotAvailable;
7800 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007801
7802 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007803}
7804
Guy Benyei11169dd2012-12-18 14:30:41 +00007805enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7806 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007807 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7808 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007809
7810 return CXAvailability_Available;
7811}
7812
7813static CXVersion convertVersion(VersionTuple In) {
7814 CXVersion Out = { -1, -1, -1 };
7815 if (In.empty())
7816 return Out;
7817
7818 Out.Major = In.getMajor();
7819
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007820 Optional<unsigned> Minor = In.getMinor();
7821 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007822 Out.Minor = *Minor;
7823 else
7824 return Out;
7825
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007826 Optional<unsigned> Subminor = In.getSubminor();
7827 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007828 Out.Subminor = *Subminor;
7829
7830 return Out;
7831}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007832
Alex Lorenz1345ea22017-06-12 19:06:30 +00007833static void getCursorPlatformAvailabilityForDecl(
7834 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7835 int *always_unavailable, CXString *unavailable_message,
7836 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007837 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007838 for (auto A : D->attrs()) {
7839 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007840 HadAvailAttr = true;
7841 if (always_deprecated)
7842 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007843 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007844 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007845 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007846 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007847 continue;
7848 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007849
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007850 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007851 HadAvailAttr = true;
7852 if (always_unavailable)
7853 *always_unavailable = 1;
7854 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007855 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007856 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7857 }
7858 continue;
7859 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007860
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007861 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007862 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007863 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007864 }
7865 }
7866
7867 if (!HadAvailAttr)
7868 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7869 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007870 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7871 deprecated_message, always_unavailable, unavailable_message,
7872 AvailabilityAttrs);
7873
7874 if (AvailabilityAttrs.empty())
7875 return;
7876
Fangrui Song55fab262018-09-26 22:16:28 +00007877 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007878 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7879 return LHS->getPlatform()->getName() <
7880 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007881 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007882 ASTContext &Ctx = D->getASTContext();
7883 auto It = std::unique(
7884 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7885 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7886 if (LHS->getPlatform() != RHS->getPlatform())
7887 return false;
7888
7889 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7890 LHS->getDeprecated() == RHS->getDeprecated() &&
7891 LHS->getObsoleted() == RHS->getObsoleted() &&
7892 LHS->getMessage() == RHS->getMessage() &&
7893 LHS->getReplacement() == RHS->getReplacement())
7894 return true;
7895
7896 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7897 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7898 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7899 return false;
7900
7901 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7902 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7903
7904 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7905 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7906 if (LHS->getMessage().empty())
7907 LHS->setMessage(Ctx, RHS->getMessage());
7908 if (LHS->getReplacement().empty())
7909 LHS->setReplacement(Ctx, RHS->getReplacement());
7910 }
7911
7912 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7913 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7914 if (LHS->getMessage().empty())
7915 LHS->setMessage(Ctx, RHS->getMessage());
7916 if (LHS->getReplacement().empty())
7917 LHS->setReplacement(Ctx, RHS->getReplacement());
7918 }
7919
7920 return true;
7921 });
7922 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007923}
7924
Alex Lorenz1345ea22017-06-12 19:06:30 +00007925int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007926 CXString *deprecated_message,
7927 int *always_unavailable,
7928 CXString *unavailable_message,
7929 CXPlatformAvailability *availability,
7930 int availability_size) {
7931 if (always_deprecated)
7932 *always_deprecated = 0;
7933 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007934 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007935 if (always_unavailable)
7936 *always_unavailable = 0;
7937 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007938 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007939
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 if (!clang_isDeclaration(cursor.kind))
7941 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007942
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007943 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007944 if (!D)
7945 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007946
Alex Lorenz1345ea22017-06-12 19:06:30 +00007947 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7948 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7949 always_unavailable, unavailable_message,
7950 AvailabilityAttrs);
7951 for (const auto &Avail :
7952 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7953 .take_front(availability_size))) {
7954 availability[Avail.index()].Platform =
7955 cxstring::createDup(Avail.value()->getPlatform()->getName());
7956 availability[Avail.index()].Introduced =
7957 convertVersion(Avail.value()->getIntroduced());
7958 availability[Avail.index()].Deprecated =
7959 convertVersion(Avail.value()->getDeprecated());
7960 availability[Avail.index()].Obsoleted =
7961 convertVersion(Avail.value()->getObsoleted());
7962 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7963 availability[Avail.index()].Message =
7964 cxstring::createDup(Avail.value()->getMessage());
7965 }
7966
7967 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007968}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007969
Guy Benyei11169dd2012-12-18 14:30:41 +00007970void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7971 clang_disposeString(availability->Platform);
7972 clang_disposeString(availability->Message);
7973}
7974
7975CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7976 if (clang_isDeclaration(cursor.kind))
7977 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7978
7979 return CXLanguage_Invalid;
7980}
7981
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007982CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7983 const Decl *D = cxcursor::getCursorDecl(cursor);
7984 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7985 switch (VD->getTLSKind()) {
7986 case VarDecl::TLS_None:
7987 return CXTLS_None;
7988 case VarDecl::TLS_Dynamic:
7989 return CXTLS_Dynamic;
7990 case VarDecl::TLS_Static:
7991 return CXTLS_Static;
7992 }
7993 }
7994
7995 return CXTLS_None;
7996}
7997
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007998 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007999 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008000 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008001static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008002 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008003 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008004
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008005 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008006 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8007 return FunTmpl;
8008
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008009 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008010 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8011 return ClassTmpl;
8012
8013 return D;
8014}
8015
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008016
8017enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8018 StorageClass sc = SC_None;
8019 const Decl *D = getCursorDecl(C);
8020 if (D) {
8021 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8022 sc = FD->getStorageClass();
8023 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8024 sc = VD->getStorageClass();
8025 } else {
8026 return CX_SC_Invalid;
8027 }
8028 } else {
8029 return CX_SC_Invalid;
8030 }
8031 switch (sc) {
8032 case SC_None:
8033 return CX_SC_None;
8034 case SC_Extern:
8035 return CX_SC_Extern;
8036 case SC_Static:
8037 return CX_SC_Static;
8038 case SC_PrivateExtern:
8039 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008040 case SC_Auto:
8041 return CX_SC_Auto;
8042 case SC_Register:
8043 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008044 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008045 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008046}
8047
Guy Benyei11169dd2012-12-18 14:30:41 +00008048CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8049 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008050 if (const Decl *D = getCursorDecl(cursor)) {
8051 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008052 if (!DC)
8053 return clang_getNullCursor();
8054
8055 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8056 getCursorTU(cursor));
8057 }
8058 }
8059
8060 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008061 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008062 return MakeCXCursor(D, getCursorTU(cursor));
8063 }
8064
8065 return clang_getNullCursor();
8066}
8067
8068CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8069 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008070 if (const Decl *D = getCursorDecl(cursor)) {
8071 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008072 if (!DC)
8073 return clang_getNullCursor();
8074
8075 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8076 getCursorTU(cursor));
8077 }
8078 }
8079
8080 // FIXME: Note that we can't easily compute the lexical context of a
8081 // statement or expression, so we return nothing.
8082 return clang_getNullCursor();
8083}
8084
8085CXFile clang_getIncludedFile(CXCursor cursor) {
8086 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008087 return nullptr;
8088
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008089 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008090 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008091}
8092
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008093unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8094 if (C.kind != CXCursor_ObjCPropertyDecl)
8095 return CXObjCPropertyAttr_noattr;
8096
8097 unsigned Result = CXObjCPropertyAttr_noattr;
8098 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8099 ObjCPropertyDecl::PropertyAttributeKind Attr =
8100 PD->getPropertyAttributesAsWritten();
8101
8102#define SET_CXOBJCPROP_ATTR(A) \
8103 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8104 Result |= CXObjCPropertyAttr_##A
8105 SET_CXOBJCPROP_ATTR(readonly);
8106 SET_CXOBJCPROP_ATTR(getter);
8107 SET_CXOBJCPROP_ATTR(assign);
8108 SET_CXOBJCPROP_ATTR(readwrite);
8109 SET_CXOBJCPROP_ATTR(retain);
8110 SET_CXOBJCPROP_ATTR(copy);
8111 SET_CXOBJCPROP_ATTR(nonatomic);
8112 SET_CXOBJCPROP_ATTR(setter);
8113 SET_CXOBJCPROP_ATTR(atomic);
8114 SET_CXOBJCPROP_ATTR(weak);
8115 SET_CXOBJCPROP_ATTR(strong);
8116 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008117 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008118#undef SET_CXOBJCPROP_ATTR
8119
8120 return Result;
8121}
8122
Michael Wu6e88f532018-08-03 05:38:29 +00008123CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8124 if (C.kind != CXCursor_ObjCPropertyDecl)
8125 return cxstring::createNull();
8126
8127 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8128 Selector sel = PD->getGetterName();
8129 if (sel.isNull())
8130 return cxstring::createNull();
8131
8132 return cxstring::createDup(sel.getAsString());
8133}
8134
8135CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8136 if (C.kind != CXCursor_ObjCPropertyDecl)
8137 return cxstring::createNull();
8138
8139 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8140 Selector sel = PD->getSetterName();
8141 if (sel.isNull())
8142 return cxstring::createNull();
8143
8144 return cxstring::createDup(sel.getAsString());
8145}
8146
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008147unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8148 if (!clang_isDeclaration(C.kind))
8149 return CXObjCDeclQualifier_None;
8150
8151 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8152 const Decl *D = getCursorDecl(C);
8153 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8154 QT = MD->getObjCDeclQualifier();
8155 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8156 QT = PD->getObjCDeclQualifier();
8157 if (QT == Decl::OBJC_TQ_None)
8158 return CXObjCDeclQualifier_None;
8159
8160 unsigned Result = CXObjCDeclQualifier_None;
8161 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8162 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8163 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8164 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8165 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8166 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8167
8168 return Result;
8169}
8170
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008171unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8172 if (!clang_isDeclaration(C.kind))
8173 return 0;
8174
8175 const Decl *D = getCursorDecl(C);
8176 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8177 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8178 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8179 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8180
8181 return 0;
8182}
8183
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008184unsigned clang_Cursor_isVariadic(CXCursor C) {
8185 if (!clang_isDeclaration(C.kind))
8186 return 0;
8187
8188 const Decl *D = getCursorDecl(C);
8189 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8190 return FD->isVariadic();
8191 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8192 return MD->isVariadic();
8193
8194 return 0;
8195}
8196
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008197unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8198 CXString *language, CXString *definedIn,
8199 unsigned *isGenerated) {
8200 if (!clang_isDeclaration(C.kind))
8201 return 0;
8202
8203 const Decl *D = getCursorDecl(C);
8204
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008205 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008206 if (language)
8207 *language = cxstring::createDup(attr->getLanguage());
8208 if (definedIn)
8209 *definedIn = cxstring::createDup(attr->getDefinedIn());
8210 if (isGenerated)
8211 *isGenerated = attr->getGeneratedDeclaration();
8212 return 1;
8213 }
8214 return 0;
8215}
8216
Guy Benyei11169dd2012-12-18 14:30:41 +00008217CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8218 if (!clang_isDeclaration(C.kind))
8219 return clang_getNullRange();
8220
8221 const Decl *D = getCursorDecl(C);
8222 ASTContext &Context = getCursorContext(C);
8223 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8224 if (!RC)
8225 return clang_getNullRange();
8226
8227 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8228}
8229
8230CXString clang_Cursor_getRawCommentText(CXCursor C) {
8231 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008232 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008233
8234 const Decl *D = getCursorDecl(C);
8235 ASTContext &Context = getCursorContext(C);
8236 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8237 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8238 StringRef();
8239
8240 // Don't duplicate the string because RawText points directly into source
8241 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008242 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008243}
8244
8245CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8246 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008247 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008248
8249 const Decl *D = getCursorDecl(C);
8250 const ASTContext &Context = getCursorContext(C);
8251 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8252
8253 if (RC) {
8254 StringRef BriefText = RC->getBriefText(Context);
8255
8256 // Don't duplicate the string because RawComment ensures that this memory
8257 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008258 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008259 }
8260
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008261 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008262}
8263
Guy Benyei11169dd2012-12-18 14:30:41 +00008264CXModule clang_Cursor_getModule(CXCursor C) {
8265 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008266 if (const ImportDecl *ImportD =
8267 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008268 return ImportD->getImportedModule();
8269 }
8270
Craig Topper69186e72014-06-08 08:38:04 +00008271 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008272}
8273
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008274CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8275 if (isNotUsableTU(TU)) {
8276 LOG_BAD_TU(TU);
8277 return nullptr;
8278 }
8279 if (!File)
8280 return nullptr;
8281 FileEntry *FE = static_cast<FileEntry *>(File);
8282
8283 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8284 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8285 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8286
Richard Smithfeb54b62014-10-23 02:01:19 +00008287 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008288}
8289
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008290CXFile clang_Module_getASTFile(CXModule CXMod) {
8291 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008292 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008293 Module *Mod = static_cast<Module*>(CXMod);
8294 return const_cast<FileEntry *>(Mod->getASTFile());
8295}
8296
Guy Benyei11169dd2012-12-18 14:30:41 +00008297CXModule clang_Module_getParent(CXModule CXMod) {
8298 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008299 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 Module *Mod = static_cast<Module*>(CXMod);
8301 return Mod->Parent;
8302}
8303
8304CXString clang_Module_getName(CXModule CXMod) {
8305 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008306 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008307 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008308 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008309}
8310
8311CXString clang_Module_getFullName(CXModule CXMod) {
8312 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008313 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008314 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008315 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008316}
8317
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008318int clang_Module_isSystem(CXModule CXMod) {
8319 if (!CXMod)
8320 return 0;
8321 Module *Mod = static_cast<Module*>(CXMod);
8322 return Mod->IsSystem;
8323}
8324
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008325unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8326 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008327 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008328 LOG_BAD_TU(TU);
8329 return 0;
8330 }
8331 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008332 return 0;
8333 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008334 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8335 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8336 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008337}
8338
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008339CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8340 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008341 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008342 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008343 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008344 }
8345 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008346 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008347 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008348 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008349
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008350 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8351 if (Index < TopHeaders.size())
8352 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008353
Craig Topper69186e72014-06-08 08:38:04 +00008354 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008355}
8356
Guy Benyei11169dd2012-12-18 14:30:41 +00008357//===----------------------------------------------------------------------===//
8358// C++ AST instrospection.
8359//===----------------------------------------------------------------------===//
8360
Jonathan Coe29565352016-04-27 12:48:25 +00008361unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8362 if (!clang_isDeclaration(C.kind))
8363 return 0;
8364
8365 const Decl *D = cxcursor::getCursorDecl(C);
8366 const CXXConstructorDecl *Constructor =
8367 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8368 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8369}
8370
8371unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8372 if (!clang_isDeclaration(C.kind))
8373 return 0;
8374
8375 const Decl *D = cxcursor::getCursorDecl(C);
8376 const CXXConstructorDecl *Constructor =
8377 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8378 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8379}
8380
8381unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8382 if (!clang_isDeclaration(C.kind))
8383 return 0;
8384
8385 const Decl *D = cxcursor::getCursorDecl(C);
8386 const CXXConstructorDecl *Constructor =
8387 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8388 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8389}
8390
8391unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8392 if (!clang_isDeclaration(C.kind))
8393 return 0;
8394
8395 const Decl *D = cxcursor::getCursorDecl(C);
8396 const CXXConstructorDecl *Constructor =
8397 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8398 // Passing 'false' excludes constructors marked 'explicit'.
8399 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8400}
8401
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008402unsigned clang_CXXField_isMutable(CXCursor C) {
8403 if (!clang_isDeclaration(C.kind))
8404 return 0;
8405
8406 if (const auto D = cxcursor::getCursorDecl(C))
8407 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8408 return FD->isMutable() ? 1 : 0;
8409 return 0;
8410}
8411
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008412unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8413 if (!clang_isDeclaration(C.kind))
8414 return 0;
8415
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008416 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008417 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008418 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008419 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8420}
8421
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008422unsigned clang_CXXMethod_isConst(CXCursor C) {
8423 if (!clang_isDeclaration(C.kind))
8424 return 0;
8425
8426 const Decl *D = cxcursor::getCursorDecl(C);
8427 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008428 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008429 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008430}
8431
Jonathan Coe29565352016-04-27 12:48:25 +00008432unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8433 if (!clang_isDeclaration(C.kind))
8434 return 0;
8435
8436 const Decl *D = cxcursor::getCursorDecl(C);
8437 const CXXMethodDecl *Method =
8438 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8439 return (Method && Method->isDefaulted()) ? 1 : 0;
8440}
8441
Guy Benyei11169dd2012-12-18 14:30:41 +00008442unsigned clang_CXXMethod_isStatic(CXCursor C) {
8443 if (!clang_isDeclaration(C.kind))
8444 return 0;
8445
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008446 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008447 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008448 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008449 return (Method && Method->isStatic()) ? 1 : 0;
8450}
8451
8452unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8453 if (!clang_isDeclaration(C.kind))
8454 return 0;
8455
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008456 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008457 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008458 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008459 return (Method && Method->isVirtual()) ? 1 : 0;
8460}
Guy Benyei11169dd2012-12-18 14:30:41 +00008461
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008462unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8463 if (!clang_isDeclaration(C.kind))
8464 return 0;
8465
8466 const auto *D = cxcursor::getCursorDecl(C);
8467 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8468 if (RD)
8469 RD = RD->getDefinition();
8470 return (RD && RD->isAbstract()) ? 1 : 0;
8471}
8472
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008473unsigned clang_EnumDecl_isScoped(CXCursor C) {
8474 if (!clang_isDeclaration(C.kind))
8475 return 0;
8476
8477 const Decl *D = cxcursor::getCursorDecl(C);
8478 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8479 return (Enum && Enum->isScoped()) ? 1 : 0;
8480}
8481
Guy Benyei11169dd2012-12-18 14:30:41 +00008482//===----------------------------------------------------------------------===//
8483// Attribute introspection.
8484//===----------------------------------------------------------------------===//
8485
Guy Benyei11169dd2012-12-18 14:30:41 +00008486CXType clang_getIBOutletCollectionType(CXCursor C) {
8487 if (C.kind != CXCursor_IBOutletCollectionAttr)
8488 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8489
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008490 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008491 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8492
8493 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8494}
Guy Benyei11169dd2012-12-18 14:30:41 +00008495
8496//===----------------------------------------------------------------------===//
8497// Inspecting memory usage.
8498//===----------------------------------------------------------------------===//
8499
8500typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8501
8502static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8503 enum CXTUResourceUsageKind k,
8504 unsigned long amount) {
8505 CXTUResourceUsageEntry entry = { k, amount };
8506 entries.push_back(entry);
8507}
8508
Guy Benyei11169dd2012-12-18 14:30:41 +00008509const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8510 const char *str = "";
8511 switch (kind) {
8512 case CXTUResourceUsage_AST:
8513 str = "ASTContext: expressions, declarations, and types";
8514 break;
8515 case CXTUResourceUsage_Identifiers:
8516 str = "ASTContext: identifiers";
8517 break;
8518 case CXTUResourceUsage_Selectors:
8519 str = "ASTContext: selectors";
8520 break;
8521 case CXTUResourceUsage_GlobalCompletionResults:
8522 str = "Code completion: cached global results";
8523 break;
8524 case CXTUResourceUsage_SourceManagerContentCache:
8525 str = "SourceManager: content cache allocator";
8526 break;
8527 case CXTUResourceUsage_AST_SideTables:
8528 str = "ASTContext: side tables";
8529 break;
8530 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8531 str = "SourceManager: malloc'ed memory buffers";
8532 break;
8533 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8534 str = "SourceManager: mmap'ed memory buffers";
8535 break;
8536 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8537 str = "ExternalASTSource: malloc'ed memory buffers";
8538 break;
8539 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8540 str = "ExternalASTSource: mmap'ed memory buffers";
8541 break;
8542 case CXTUResourceUsage_Preprocessor:
8543 str = "Preprocessor: malloc'ed memory";
8544 break;
8545 case CXTUResourceUsage_PreprocessingRecord:
8546 str = "Preprocessor: PreprocessingRecord";
8547 break;
8548 case CXTUResourceUsage_SourceManager_DataStructures:
8549 str = "SourceManager: data structures and tables";
8550 break;
8551 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8552 str = "Preprocessor: header search tables";
8553 break;
8554 }
8555 return str;
8556}
8557
8558CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008559 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008560 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008561 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008562 return usage;
8563 }
8564
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008565 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008566 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008567 ASTContext &astContext = astUnit->getASTContext();
8568
8569 // How much memory is used by AST nodes and types?
8570 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8571 (unsigned long) astContext.getASTAllocatedMemory());
8572
8573 // How much memory is used by identifiers?
8574 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8575 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8576
8577 // How much memory is used for selectors?
8578 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8579 (unsigned long) astContext.Selectors.getTotalMemory());
8580
8581 // How much memory is used by ASTContext's side tables?
8582 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8583 (unsigned long) astContext.getSideTableAllocatedMemory());
8584
8585 // How much memory is used for caching global code completion results?
8586 unsigned long completionBytes = 0;
8587 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008588 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008589 completionBytes = completionAllocator->getTotalMemory();
8590 }
8591 createCXTUResourceUsageEntry(*entries,
8592 CXTUResourceUsage_GlobalCompletionResults,
8593 completionBytes);
8594
8595 // How much memory is being used by SourceManager's content cache?
8596 createCXTUResourceUsageEntry(*entries,
8597 CXTUResourceUsage_SourceManagerContentCache,
8598 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8599
8600 // How much memory is being used by the MemoryBuffer's in SourceManager?
8601 const SourceManager::MemoryBufferSizes &srcBufs =
8602 astUnit->getSourceManager().getMemoryBufferSizes();
8603
8604 createCXTUResourceUsageEntry(*entries,
8605 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8606 (unsigned long) srcBufs.malloc_bytes);
8607 createCXTUResourceUsageEntry(*entries,
8608 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8609 (unsigned long) srcBufs.mmap_bytes);
8610 createCXTUResourceUsageEntry(*entries,
8611 CXTUResourceUsage_SourceManager_DataStructures,
8612 (unsigned long) astContext.getSourceManager()
8613 .getDataStructureSizes());
8614
8615 // How much memory is being used by the ExternalASTSource?
8616 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8617 const ExternalASTSource::MemoryBufferSizes &sizes =
8618 esrc->getMemoryBufferSizes();
8619
8620 createCXTUResourceUsageEntry(*entries,
8621 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8622 (unsigned long) sizes.malloc_bytes);
8623 createCXTUResourceUsageEntry(*entries,
8624 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8625 (unsigned long) sizes.mmap_bytes);
8626 }
8627
8628 // How much memory is being used by the Preprocessor?
8629 Preprocessor &pp = astUnit->getPreprocessor();
8630 createCXTUResourceUsageEntry(*entries,
8631 CXTUResourceUsage_Preprocessor,
8632 pp.getTotalMemory());
8633
8634 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8635 createCXTUResourceUsageEntry(*entries,
8636 CXTUResourceUsage_PreprocessingRecord,
8637 pRec->getTotalMemory());
8638 }
8639
8640 createCXTUResourceUsageEntry(*entries,
8641 CXTUResourceUsage_Preprocessor_HeaderSearch,
8642 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008643
Guy Benyei11169dd2012-12-18 14:30:41 +00008644 CXTUResourceUsage usage = { (void*) entries.get(),
8645 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008646 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008647 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008648 return usage;
8649}
8650
8651void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8652 if (usage.data)
8653 delete (MemUsageEntries*) usage.data;
8654}
8655
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008656CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8657 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008658 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008659 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008660
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008661 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008662 LOG_BAD_TU(TU);
8663 return skipped;
8664 }
8665
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008666 if (!file)
8667 return skipped;
8668
8669 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8670 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8671 if (!ppRec)
8672 return skipped;
8673
8674 ASTContext &Ctx = astUnit->getASTContext();
8675 SourceManager &sm = Ctx.getSourceManager();
8676 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8677 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008678 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008679
8680 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8681 std::vector<SourceRange> wantedRanges;
8682 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8683 i != ei; ++i) {
8684 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8685 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008686 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8687 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008688 }
8689
8690 skipped->count = wantedRanges.size();
8691 skipped->ranges = new CXSourceRange[skipped->count];
8692 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8693 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8694
8695 return skipped;
8696}
8697
Cameron Desrochersd8091282016-08-18 15:43:55 +00008698CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8699 CXSourceRangeList *skipped = new CXSourceRangeList;
8700 skipped->count = 0;
8701 skipped->ranges = nullptr;
8702
8703 if (isNotUsableTU(TU)) {
8704 LOG_BAD_TU(TU);
8705 return skipped;
8706 }
8707
8708 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8709 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8710 if (!ppRec)
8711 return skipped;
8712
8713 ASTContext &Ctx = astUnit->getASTContext();
8714
8715 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8716
8717 skipped->count = SkippedRanges.size();
8718 skipped->ranges = new CXSourceRange[skipped->count];
8719 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8720 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8721
8722 return skipped;
8723}
8724
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008725void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8726 if (ranges) {
8727 delete[] ranges->ranges;
8728 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008729 }
8730}
8731
Guy Benyei11169dd2012-12-18 14:30:41 +00008732void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8733 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8734 for (unsigned I = 0; I != Usage.numEntries; ++I)
8735 fprintf(stderr, " %s: %lu\n",
8736 clang_getTUResourceUsageName(Usage.entries[I].kind),
8737 Usage.entries[I].amount);
8738
8739 clang_disposeCXTUResourceUsage(Usage);
8740}
8741
8742//===----------------------------------------------------------------------===//
8743// Misc. utility functions.
8744//===----------------------------------------------------------------------===//
8745
Richard Smith0a7b2972018-07-03 21:34:13 +00008746/// Default to using our desired 8 MB stack size on "safety" threads.
8747static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008748
8749namespace clang {
8750
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008751bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008752 unsigned Size) {
8753 if (!Size)
8754 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008755 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008756 return CRC.RunSafelyOnThread(Fn, Size);
8757 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008758}
8759
8760unsigned GetSafetyThreadStackSize() {
8761 return SafetyStackThreadSize;
8762}
8763
8764void SetSafetyThreadStackSize(unsigned Value) {
8765 SafetyStackThreadSize = Value;
8766}
8767
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008768}
Guy Benyei11169dd2012-12-18 14:30:41 +00008769
8770void clang::setThreadBackgroundPriority() {
8771 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8772 return;
8773
Nico Weber18cfd9f2019-04-21 19:18:41 +00008774#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008775 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008776#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008777}
8778
8779void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8780 if (!Unit)
8781 return;
8782
8783 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8784 DEnd = Unit->stored_diag_end();
8785 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008786 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008787 CXString Msg = clang_formatDiagnostic(&Diag,
8788 clang_defaultDiagnosticDisplayOptions());
8789 fprintf(stderr, "%s\n", clang_getCString(Msg));
8790 clang_disposeString(Msg);
8791 }
Nico Weber1865df42018-04-27 19:11:14 +00008792#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008793 // On Windows, force a flush, since there may be multiple copies of
8794 // stderr and stdout in the file system, all with different buffers
8795 // but writing to the same device.
8796 fflush(stderr);
8797#endif
8798}
8799
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008800MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8801 SourceLocation MacroDefLoc,
8802 CXTranslationUnit TU){
8803 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008804 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008805 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008806 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008807
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008808 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008809 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008810 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008811 if (MD) {
8812 for (MacroDirective::DefInfo
8813 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8814 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8815 return Def.getMacroInfo();
8816 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008817 }
8818
Craig Topper69186e72014-06-08 08:38:04 +00008819 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008820}
8821
Richard Smith66a81862015-05-04 02:25:31 +00008822const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008823 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008824 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008825 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008826 const IdentifierInfo *II = MacroDef->getName();
8827 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008828 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008829
8830 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8831}
8832
Richard Smith66a81862015-05-04 02:25:31 +00008833MacroDefinitionRecord *
8834cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8835 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008836 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008837 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008838 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008839 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008840
8841 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008842 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008843 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8844 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008845 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008846
8847 // Check that the token is inside the definition and not its argument list.
8848 SourceManager &SM = Unit->getSourceManager();
8849 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008850 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008851 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008852 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008853
8854 Preprocessor &PP = Unit->getPreprocessor();
8855 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8856 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008857 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008858
Alp Toker2d57cea2014-05-17 04:53:25 +00008859 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008860 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008861 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008862
8863 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008864 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008865 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008866
Richard Smith20e883e2015-04-29 23:20:19 +00008867 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008868 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008869 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008870
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008871 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008872}
8873
Richard Smith66a81862015-05-04 02:25:31 +00008874MacroDefinitionRecord *
8875cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8876 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008877 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008878 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008879
8880 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008881 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008882 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008883 Preprocessor &PP = Unit->getPreprocessor();
8884 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008885 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008886 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8887 Token Tok;
8888 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008889 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008890
8891 return checkForMacroInMacroDefinition(MI, Tok, TU);
8892}
8893
Guy Benyei11169dd2012-12-18 14:30:41 +00008894CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008895 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008896}
8897
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008898Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8899 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008900 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008901 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008902 if (Unit->isMainFileAST())
8903 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008904 return *this;
8905 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008906 } else {
8907 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008908 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008909 return *this;
8910}
8911
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008912Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8913 *this << FE->getName();
8914 return *this;
8915}
8916
8917Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8918 CXString cursorName = clang_getCursorDisplayName(cursor);
8919 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8920 clang_disposeString(cursorName);
8921 return *this;
8922}
8923
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008924Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8925 CXFile File;
8926 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008927 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008928 CXString FileName = clang_getFileName(File);
8929 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8930 clang_disposeString(FileName);
8931 return *this;
8932}
8933
8934Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8935 CXSourceLocation BLoc = clang_getRangeStart(range);
8936 CXSourceLocation ELoc = clang_getRangeEnd(range);
8937
8938 CXFile BFile;
8939 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008940 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008941
8942 CXFile EFile;
8943 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008944 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008945
8946 CXString BFileName = clang_getFileName(BFile);
8947 if (BFile == EFile) {
8948 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8949 BLine, BColumn, ELine, EColumn);
8950 } else {
8951 CXString EFileName = clang_getFileName(EFile);
8952 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8953 BLine, BColumn)
8954 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8955 ELine, EColumn);
8956 clang_disposeString(EFileName);
8957 }
8958 clang_disposeString(BFileName);
8959 return *this;
8960}
8961
8962Logger &cxindex::Logger::operator<<(CXString Str) {
8963 *this << clang_getCString(Str);
8964 return *this;
8965}
8966
8967Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8968 LogOS << Fmt;
8969 return *this;
8970}
8971
Benjamin Kramer762bc332019-08-07 14:44:40 +00008972static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00008973
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008974cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00008975 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008976
8977 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8978
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008979 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008980 OS << "[libclang:" << Name << ':';
8981
Alp Toker1a86ad22014-07-06 06:24:00 +00008982#ifdef USE_DARWIN_THREADS
8983 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008984 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8985 OS << tid << ':';
8986#endif
8987
8988 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8989 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008990 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008991
8992 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008993 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008994 OS << "--------------------------------------------------\n";
8995 }
8996}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00008997
8998#ifdef CLANG_TOOL_EXTRA_BUILD
8999// This anchor is used to force the linker to link the clang-tidy plugin.
9000extern volatile int ClangTidyPluginAnchorSource;
9001static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9002 ClangTidyPluginAnchorSource;
9003
9004// This anchor is used to force the linker to link the clang-include-fixer
9005// plugin.
9006extern volatile int ClangIncludeFixerPluginAnchorSource;
9007static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9008 ClangIncludeFixerPluginAnchorSource;
9009#endif