blob: 6bd9d7387384a073ec0b71505164844e276315fa [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
Guy Benyei11169dd2012-12-18 14:30:41 +000015#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000017#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000029#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000030#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000031#include "clang/Basic/Version.h"
32#include "clang/Frontend/ASTUnit.h"
33#include "clang/Frontend/CompilerInstance.h"
34#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000035#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000036#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "clang/Lex/HeaderSearch.h"
38#include "clang/Lex/Lexer.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000041#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000042#include "llvm/ADT/Optional.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000045#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "llvm/Support/Compiler.h"
47#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000048#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000049#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000052#include "llvm/Support/Program.h"
53#include "llvm/Support/SaveAndRestore.h"
54#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000055#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include "llvm/Support/Threading.h"
57#include "llvm/Support/Timer.h"
58#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000059
Alp Toker1a86ad22014-07-06 06:24:00 +000060#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
61#define USE_DARWIN_THREADS
62#endif
63
64#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000065#include <pthread.h>
66#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000067
68using namespace clang;
69using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000070using namespace clang::cxtu;
71using namespace clang::cxindex;
72
David Blaikieea4395e2017-01-06 19:49:01 +000073CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
74 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000075 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000076 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000077 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000078 CXTranslationUnit D = new CXTranslationUnitImpl();
79 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000080 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000081 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000082 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000083 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000084 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000085 D->ParsingOptions = 0;
86 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000087 return D;
88}
89
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000090bool cxtu::isASTReadError(ASTUnit *AU) {
91 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
92 DEnd = AU->stored_diag_end();
93 D != DEnd; ++D) {
94 if (D->getLevel() >= DiagnosticsEngine::Error &&
95 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
96 diag::DiagCat_AST_Deserialization_Issue)
97 return true;
98 }
99 return false;
100}
101
Guy Benyei11169dd2012-12-18 14:30:41 +0000102cxtu::CXTUOwner::~CXTUOwner() {
103 if (TU)
104 clang_disposeTranslationUnit(TU);
105}
106
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000107/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000108/// the translation unit.
109static RangeComparisonResult RangeCompare(SourceManager &SM,
110 SourceRange R1,
111 SourceRange R2) {
112 assert(R1.isValid() && "First range is invalid?");
113 assert(R2.isValid() && "Second range is invalid?");
114 if (R1.getEnd() != R2.getBegin() &&
115 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
116 return RangeBefore;
117 if (R2.getEnd() != R1.getBegin() &&
118 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
119 return RangeAfter;
120 return RangeOverlap;
121}
122
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000123/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000124/// a given source range.
125static RangeComparisonResult LocationCompare(SourceManager &SM,
126 SourceLocation L, SourceRange R) {
127 assert(R.isValid() && "First range is invalid?");
128 assert(L.isValid() && "Second range is invalid?");
129 if (L == R.getBegin() || L == R.getEnd())
130 return RangeOverlap;
131 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
132 return RangeBefore;
133 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
134 return RangeAfter;
135 return RangeOverlap;
136}
137
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000138/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000139///
140/// Clang internally represents ranges where the end location points to the
141/// start of the token at the end. However, for external clients it is more
142/// useful to have a CXSourceRange be a proper half-open interval. This routine
143/// does the appropriate translation.
144CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
145 const LangOptions &LangOpts,
146 const CharSourceRange &R) {
147 // We want the last character in this location, so we will adjust the
148 // location accordingly.
149 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000150 bool IsTokenRange = R.isTokenRange();
151 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
152 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
153 EndLoc = Expansion.getEnd();
154 IsTokenRange = Expansion.isTokenRange();
155 }
156 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000157 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
158 SM, LangOpts);
159 EndLoc = EndLoc.getLocWithOffset(Length);
160 }
161
Bill Wendlingeade3622013-01-23 08:25:41 +0000162 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000163 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000164 R.getBegin().getRawEncoding(),
165 EndLoc.getRawEncoding()
166 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000167 return Result;
168}
169
170//===----------------------------------------------------------------------===//
171// Cursor visitor.
172//===----------------------------------------------------------------------===//
173
174static SourceRange getRawCursorExtent(CXCursor C);
175static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
176
177
178RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
179 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
180}
181
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000182/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000183/// its children.
184///
185/// \param Cursor the cursor to visit.
186///
187/// \param CheckedRegionOfInterest if true, then the caller already checked
188/// that this cursor is within the region of interest.
189///
190/// \returns true if the visitation should be aborted, false if it
191/// should continue.
192bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
193 if (clang_isInvalid(Cursor.kind))
194 return false;
195
196 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000197 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000198 if (!D) {
199 assert(0 && "Invalid declaration cursor");
200 return true; // abort.
201 }
202
203 // Ignore implicit declarations, unless it's an objc method because
204 // currently we should report implicit methods for properties when indexing.
205 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
206 return false;
207 }
208
209 // If we have a range of interest, and this cursor doesn't intersect with it,
210 // we're done.
211 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
212 SourceRange Range = getRawCursorExtent(Cursor);
213 if (Range.isInvalid() || CompareRegionOfInterest(Range))
214 return false;
215 }
216
217 switch (Visitor(Cursor, Parent, ClientData)) {
218 case CXChildVisit_Break:
219 return true;
220
221 case CXChildVisit_Continue:
222 return false;
223
224 case CXChildVisit_Recurse: {
225 bool ret = VisitChildren(Cursor);
226 if (PostChildrenVisitor)
227 if (PostChildrenVisitor(Cursor, ClientData))
228 return true;
229 return ret;
230 }
231 }
232
233 llvm_unreachable("Invalid CXChildVisitResult!");
234}
235
236static bool visitPreprocessedEntitiesInRange(SourceRange R,
237 PreprocessingRecord &PPRec,
238 CursorVisitor &Visitor) {
239 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
240 FileID FID;
241
242 if (!Visitor.shouldVisitIncludedEntities()) {
243 // If the begin/end of the range lie in the same FileID, do the optimization
244 // where we skip preprocessed entities that do not come from the same FileID.
245 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
246 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
247 FID = FileID();
248 }
249
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000250 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
251 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000252 PPRec, FID);
253}
254
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000255bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000256 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000257 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000258
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000259 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000260 SourceManager &SM = Unit->getSourceManager();
261
262 std::pair<FileID, unsigned>
263 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
264 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
265
266 if (End.first != Begin.first) {
267 // If the end does not reside in the same file, try to recover by
268 // picking the end of the file of begin location.
269 End.first = Begin.first;
270 End.second = SM.getFileIDSize(Begin.first);
271 }
272
273 assert(Begin.first == End.first);
274 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000275 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000276
277 FileID File = Begin.first;
278 unsigned Offset = Begin.second;
279 unsigned Length = End.second - Begin.second;
280
281 if (!VisitDeclsOnly && !VisitPreprocessorLast)
282 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000283 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000285 if (visitDeclsFromFileRegion(File, Offset, Length))
286 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000287
288 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000289 return visitPreprocessedEntitiesInRegion();
290
291 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000292}
293
294static bool isInLexicalContext(Decl *D, DeclContext *DC) {
295 if (!DC)
296 return false;
297
298 for (DeclContext *DeclDC = D->getLexicalDeclContext();
299 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
300 if (DeclDC == DC)
301 return true;
302 }
303 return false;
304}
305
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000306bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000307 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000308 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000309 SourceManager &SM = Unit->getSourceManager();
310 SourceRange Range = RegionOfInterest;
311
312 SmallVector<Decl *, 16> Decls;
313 Unit->findFileRegionDecls(File, Offset, Length, Decls);
314
315 // If we didn't find any file level decls for the file, try looking at the
316 // file that it was included from.
317 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
318 bool Invalid = false;
319 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
320 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000321 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000322
323 SourceLocation Outer;
324 if (SLEntry.isFile())
325 Outer = SLEntry.getFile().getIncludeLoc();
326 else
327 Outer = SLEntry.getExpansion().getExpansionLocStart();
328 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000329 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000330
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000331 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000332 Length = 0;
333 Unit->findFileRegionDecls(File, Offset, Length, Decls);
334 }
335
336 assert(!Decls.empty());
337
338 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000339 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000340 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
341 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000342 Decl *D = *DIt;
343 if (D->getSourceRange().isInvalid())
344 continue;
345
346 if (isInLexicalContext(D, CurDC))
347 continue;
348
349 CurDC = dyn_cast<DeclContext>(D);
350
351 if (TagDecl *TD = dyn_cast<TagDecl>(D))
352 if (!TD->isFreeStanding())
353 continue;
354
355 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
356 if (CompRes == RangeBefore)
357 continue;
358 if (CompRes == RangeAfter)
359 break;
360
361 assert(CompRes == RangeOverlap);
362 VisitedAtLeastOnce = true;
363
364 if (isa<ObjCContainerDecl>(D)) {
365 FileDI_current = &DIt;
366 FileDE_current = DE;
367 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000368 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000369 }
370
371 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000372 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000373 }
374
375 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000376 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000377
378 // No Decls overlapped with the range. Move up the lexical context until there
379 // is a context that contains the range or we reach the translation unit
380 // level.
381 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
382 : (*(DIt-1))->getLexicalDeclContext();
383
384 while (DC && !DC->isTranslationUnit()) {
385 Decl *D = cast<Decl>(DC);
386 SourceRange CurDeclRange = D->getSourceRange();
387 if (CurDeclRange.isInvalid())
388 break;
389
390 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000391 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
392 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 }
394
395 DC = D->getLexicalDeclContext();
396 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000397
398 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000399}
400
401bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
402 if (!AU->getPreprocessor().getPreprocessingRecord())
403 return false;
404
405 PreprocessingRecord &PPRec
406 = *AU->getPreprocessor().getPreprocessingRecord();
407 SourceManager &SM = AU->getSourceManager();
408
409 if (RegionOfInterest.isValid()) {
410 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
411 SourceLocation B = MappedRange.getBegin();
412 SourceLocation E = MappedRange.getEnd();
413
414 if (AU->isInPreambleFileID(B)) {
415 if (SM.isLoadedSourceLocation(E))
416 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
417 PPRec, *this);
418
419 // Beginning of range lies in the preamble but it also extends beyond
420 // it into the main file. Split the range into 2 parts, one covering
421 // the preamble and another covering the main file. This allows subsequent
422 // calls to visitPreprocessedEntitiesInRange to accept a source range that
423 // lies in the same FileID, allowing it to skip preprocessed entities that
424 // do not come from the same FileID.
425 bool breaked =
426 visitPreprocessedEntitiesInRange(
427 SourceRange(B, AU->getEndOfPreambleFileID()),
428 PPRec, *this);
429 if (breaked) return true;
430 return visitPreprocessedEntitiesInRange(
431 SourceRange(AU->getStartOfMainFileID(), E),
432 PPRec, *this);
433 }
434
435 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
436 }
437
438 bool OnlyLocalDecls
439 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
440
441 if (OnlyLocalDecls)
442 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
443 PPRec);
444
445 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
446}
447
448template<typename InputIterator>
449bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
450 InputIterator Last,
451 PreprocessingRecord &PPRec,
452 FileID FID) {
453 for (; First != Last; ++First) {
454 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
455 continue;
456
457 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000458 if (!PPE)
459 continue;
460
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
462 if (Visit(MakeMacroExpansionCursor(ME, TU)))
463 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000464
Guy Benyei11169dd2012-12-18 14:30:41 +0000465 continue;
466 }
Richard Smith66a81862015-05-04 02:25:31 +0000467
468 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000469 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
470 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000471
Guy Benyei11169dd2012-12-18 14:30:41 +0000472 continue;
473 }
474
475 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
476 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
477 return true;
478
479 continue;
480 }
481 }
482
483 return false;
484}
485
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000486/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000487///
488/// \returns true if the visitation should be aborted, false if it
489/// should continue.
490bool CursorVisitor::VisitChildren(CXCursor Cursor) {
491 if (clang_isReference(Cursor.kind) &&
492 Cursor.kind != CXCursor_CXXBaseSpecifier) {
493 // By definition, references have no children.
494 return false;
495 }
496
497 // Set the Parent field to Cursor, then back to its old value once we're
498 // done.
499 SetParentRAII SetParent(Parent, StmtParent, Cursor);
500
501 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000502 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000503 if (!D)
504 return false;
505
506 return VisitAttributes(D) || Visit(D);
507 }
508
509 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000510 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000511 return Visit(S);
512
513 return false;
514 }
515
516 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000517 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000518 return Visit(E);
519
520 return false;
521 }
522
523 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000524 CXTranslationUnit TU = getCursorTU(Cursor);
525 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000526
527 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
528 for (unsigned I = 0; I != 2; ++I) {
529 if (VisitOrder[I]) {
530 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
531 RegionOfInterest.isInvalid()) {
532 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
533 TLEnd = CXXUnit->top_level_end();
534 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000535 const Optional<bool> V = handleDeclForVisitation(*TL);
536 if (!V.hasValue())
537 continue;
538 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000539 }
540 } else if (VisitDeclContext(
541 CXXUnit->getASTContext().getTranslationUnitDecl()))
542 return true;
543 continue;
544 }
545
546 // Walk the preprocessing record.
547 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
548 visitPreprocessedEntitiesInRegion();
549 }
550
551 return false;
552 }
553
554 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000555 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000556 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
557 return Visit(BaseTSInfo->getTypeLoc());
558 }
559 }
560 }
561
562 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000563 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000565 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000566 return Visit(cxcursor::MakeCursorObjCClassRef(
567 ObjT->getInterface(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000568 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 }
570
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000571 // If pointing inside a macro definition, check if the token is an identifier
572 // that was ever defined as a macro. In such a case, create a "pseudo" macro
573 // expansion cursor for that token.
574 SourceLocation BeginLoc = RegionOfInterest.getBegin();
575 if (Cursor.kind == CXCursor_MacroDefinition &&
576 BeginLoc == RegionOfInterest.getEnd()) {
577 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000578 const MacroInfo *MI =
579 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000580 if (MacroDefinitionRecord *MacroDef =
581 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000582 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
583 }
584
Guy Benyei11169dd2012-12-18 14:30:41 +0000585 // Nothing to visit at the moment.
586 return false;
587}
588
589bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
590 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
591 if (Visit(TSInfo->getTypeLoc()))
592 return true;
593
594 if (Stmt *Body = B->getBody())
595 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
596
597 return false;
598}
599
Ted Kremenek03325582013-02-21 01:29:01 +0000600Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000601 if (RegionOfInterest.isValid()) {
602 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
603 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000604 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000605
606 switch (CompareRegionOfInterest(Range)) {
607 case RangeBefore:
608 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000609 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000610
611 case RangeAfter:
612 // This declaration comes after the region of interest; we're done.
613 return false;
614
615 case RangeOverlap:
616 // This declaration overlaps the region of interest; visit it.
617 break;
618 }
619 }
620 return true;
621}
622
623bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
624 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
625
626 // FIXME: Eventually remove. This part of a hack to support proper
627 // iteration over all Decls contained lexically within an ObjC container.
628 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
629 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
630
631 for ( ; I != E; ++I) {
632 Decl *D = *I;
633 if (D->getLexicalDeclContext() != DC)
634 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000635 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000636 if (!V.hasValue())
637 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000638 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 }
640 return false;
641}
642
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000643Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
644 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
645
646 // Ignore synthesized ivars here, otherwise if we have something like:
647 // @synthesize prop = _prop;
648 // and '_prop' is not declared, we will encounter a '_prop' ivar before
649 // encountering the 'prop' synthesize declaration and we will think that
650 // we passed the region-of-interest.
651 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
652 if (ivarD->getSynthesize())
653 return None;
654 }
655
656 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
657 // declarations is a mismatch with the compiler semantics.
658 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
659 auto *ID = cast<ObjCInterfaceDecl>(D);
660 if (!ID->isThisDeclarationADefinition())
661 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
662
663 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
664 auto *PD = cast<ObjCProtocolDecl>(D);
665 if (!PD->isThisDeclarationADefinition())
666 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
667 }
668
669 const Optional<bool> V = shouldVisitCursor(Cursor);
670 if (!V.hasValue())
671 return None;
672 if (!V.getValue())
673 return false;
674 if (Visit(Cursor, true))
675 return true;
676 return None;
677}
678
Guy Benyei11169dd2012-12-18 14:30:41 +0000679bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
680 llvm_unreachable("Translation units are visited directly by Visit()");
681}
682
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000683bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
684 if (VisitTemplateParameters(D->getTemplateParameters()))
685 return true;
686
687 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
688}
689
Guy Benyei11169dd2012-12-18 14:30:41 +0000690bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
691 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
692 return Visit(TSInfo->getTypeLoc());
693
694 return false;
695}
696
697bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
698 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
699 return Visit(TSInfo->getTypeLoc());
700
701 return false;
702}
703
704bool CursorVisitor::VisitTagDecl(TagDecl *D) {
705 return VisitDeclContext(D);
706}
707
708bool CursorVisitor::VisitClassTemplateSpecializationDecl(
709 ClassTemplateSpecializationDecl *D) {
710 bool ShouldVisitBody = false;
711 switch (D->getSpecializationKind()) {
712 case TSK_Undeclared:
713 case TSK_ImplicitInstantiation:
714 // Nothing to visit
715 return false;
716
717 case TSK_ExplicitInstantiationDeclaration:
718 case TSK_ExplicitInstantiationDefinition:
719 break;
720
721 case TSK_ExplicitSpecialization:
722 ShouldVisitBody = true;
723 break;
724 }
725
726 // Visit the template arguments used in the specialization.
727 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
728 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000729 if (TemplateSpecializationTypeLoc TSTLoc =
730 TL.getAs<TemplateSpecializationTypeLoc>()) {
731 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
732 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000733 return true;
734 }
735 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000736
737 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000738}
739
740bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
741 ClassTemplatePartialSpecializationDecl *D) {
742 // FIXME: Visit the "outer" template parameter lists on the TagDecl
743 // before visiting these template parameters.
744 if (VisitTemplateParameters(D->getTemplateParameters()))
745 return true;
746
747 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000748 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
749 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
750 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000751 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
752 return true;
753
754 return VisitCXXRecordDecl(D);
755}
756
757bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
758 // Visit the default argument.
759 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
760 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
761 if (Visit(DefArg->getTypeLoc()))
762 return true;
763
764 return false;
765}
766
767bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
768 if (Expr *Init = D->getInitExpr())
769 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
770 return false;
771}
772
773bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000774 unsigned NumParamList = DD->getNumTemplateParameterLists();
775 for (unsigned i = 0; i < NumParamList; i++) {
776 TemplateParameterList* Params = DD->getTemplateParameterList(i);
777 if (VisitTemplateParameters(Params))
778 return true;
779 }
780
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
782 if (Visit(TSInfo->getTypeLoc()))
783 return true;
784
785 // Visit the nested-name-specifier, if present.
786 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
787 if (VisitNestedNameSpecifierLoc(QualifierLoc))
788 return true;
789
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000790 return false;
791}
792
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000793static bool HasTrailingReturnType(FunctionDecl *ND) {
794 const QualType Ty = ND->getType();
795 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
796 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
797 return FT->hasTrailingReturn();
798 }
799
800 return false;
801}
802
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000803/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000804static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
805 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000806 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
807}
808
Guy Benyei11169dd2012-12-18 14:30:41 +0000809bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000810 unsigned NumParamList = ND->getNumTemplateParameterLists();
811 for (unsigned i = 0; i < NumParamList; i++) {
812 TemplateParameterList* Params = ND->getTemplateParameterList(i);
813 if (VisitTemplateParameters(Params))
814 return true;
815 }
816
Guy Benyei11169dd2012-12-18 14:30:41 +0000817 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
818 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000819 // written. This requires a bit of work.
820 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
821 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000822 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000823
824 // If we have a function declared directly (without the use of a typedef),
825 // visit just the return type. Otherwise, just visit the function's type
826 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000827 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
828 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000829 (!FTL && Visit(TL)))
830 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000831
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000832 // Visit the nested-name-specifier, if present.
833 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
834 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 return true;
836
837 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000838 if (!isa<CXXDestructorDecl>(ND))
839 if (VisitDeclarationNameInfo(ND->getNameInfo()))
840 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000841
842 // FIXME: Visit explicitly-specified template arguments!
843
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000844 // Visit the function parameters, if we have a function type.
845 if (FTL && VisitFunctionTypeLoc(FTL, true))
846 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000847
848 // Visit the function's trailing return type.
849 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
850 return true;
851
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000852 // FIXME: Attributes?
853 }
854
Guy Benyei11169dd2012-12-18 14:30:41 +0000855 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
856 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
857 // Find the initializers that were written in the source.
858 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000859 for (auto *I : Constructor->inits()) {
860 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000861 continue;
862
Aaron Ballman0ad78302014-03-13 17:34:31 +0000863 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 }
865
866 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000867 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
868 &CompareCXXCtorInitializers);
869
Guy Benyei11169dd2012-12-18 14:30:41 +0000870 // Visit the initializers in source order
871 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
872 CXXCtorInitializer *Init = WrittenInits[I];
873 if (Init->isAnyMemberInitializer()) {
874 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
875 Init->getMemberLocation(), TU)))
876 return true;
877 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
878 if (Visit(TInfo->getTypeLoc()))
879 return true;
880 }
881
882 // Visit the initializer value.
883 if (Expr *Initializer = Init->getInit())
884 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
885 return true;
886 }
887 }
888
889 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
890 return true;
891 }
892
893 return false;
894}
895
896bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
897 if (VisitDeclaratorDecl(D))
898 return true;
899
900 if (Expr *BitWidth = D->getBitWidth())
901 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
902
Benjamin Kramer99f97592017-11-15 12:20:41 +0000903 if (Expr *Init = D->getInClassInitializer())
904 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
905
Guy Benyei11169dd2012-12-18 14:30:41 +0000906 return false;
907}
908
909bool CursorVisitor::VisitVarDecl(VarDecl *D) {
910 if (VisitDeclaratorDecl(D))
911 return true;
912
913 if (Expr *Init = D->getInit())
914 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
915
916 return false;
917}
918
919bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
920 if (VisitDeclaratorDecl(D))
921 return true;
922
923 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
924 if (Expr *DefArg = D->getDefaultArgument())
925 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
926
927 return false;
928}
929
930bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
931 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
932 // before visiting these template parameters.
933 if (VisitTemplateParameters(D->getTemplateParameters()))
934 return true;
935
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000936 auto* FD = D->getTemplatedDecl();
937 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000938}
939
940bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
941 // FIXME: Visit the "outer" template parameter lists on the TagDecl
942 // before visiting these template parameters.
943 if (VisitTemplateParameters(D->getTemplateParameters()))
944 return true;
945
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000946 auto* CD = D->getTemplatedDecl();
947 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000948}
949
950bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
951 if (VisitTemplateParameters(D->getTemplateParameters()))
952 return true;
953
954 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
955 VisitTemplateArgumentLoc(D->getDefaultArgument()))
956 return true;
957
958 return false;
959}
960
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000961bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
962 // Visit the bound, if it's explicit.
963 if (D->hasExplicitBound()) {
964 if (auto TInfo = D->getTypeSourceInfo()) {
965 if (Visit(TInfo->getTypeLoc()))
966 return true;
967 }
968 }
969
970 return false;
971}
972
Guy Benyei11169dd2012-12-18 14:30:41 +0000973bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000974 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 if (Visit(TSInfo->getTypeLoc()))
976 return true;
977
David Majnemer59f77922016-06-24 04:05:48 +0000978 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000979 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000980 return true;
981 }
982
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000983 return ND->isThisDeclarationADefinition() &&
984 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000985}
986
987template <typename DeclIt>
988static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
989 SourceManager &SM, SourceLocation EndLoc,
990 SmallVectorImpl<Decl *> &Decls) {
991 DeclIt next = *DI_current;
992 while (++next != DE_current) {
993 Decl *D_next = *next;
994 if (!D_next)
995 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000996 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +0000997 if (!L.isValid())
998 break;
999 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1000 *DI_current = next;
1001 Decls.push_back(D_next);
1002 continue;
1003 }
1004 break;
1005 }
1006}
1007
Guy Benyei11169dd2012-12-18 14:30:41 +00001008bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1009 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1010 // an @implementation can lexically contain Decls that are not properly
1011 // nested in the AST. When we identify such cases, we need to retrofit
1012 // this nesting here.
1013 if (!DI_current && !FileDI_current)
1014 return VisitDeclContext(D);
1015
1016 // Scan the Decls that immediately come after the container
1017 // in the current DeclContext. If any fall within the
1018 // container's lexical region, stash them into a vector
1019 // for later processing.
1020 SmallVector<Decl *, 24> DeclsInContainer;
1021 SourceLocation EndLoc = D->getSourceRange().getEnd();
1022 SourceManager &SM = AU->getSourceManager();
1023 if (EndLoc.isValid()) {
1024 if (DI_current) {
1025 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1026 DeclsInContainer);
1027 } else {
1028 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1029 DeclsInContainer);
1030 }
1031 }
1032
1033 // The common case.
1034 if (DeclsInContainer.empty())
1035 return VisitDeclContext(D);
1036
1037 // Get all the Decls in the DeclContext, and sort them with the
1038 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001039 for (auto *SubDecl : D->decls()) {
1040 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001041 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001042 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001043 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 }
1045
1046 // Now sort the Decls so that they appear in lexical order.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001047 llvm::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1048 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001049 SourceLocation L_A = A->getBeginLoc();
1050 SourceLocation L_B = B->getBeginLoc();
1051 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001052 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1053 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001054 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001055
1056 // Now visit the decls.
1057 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1058 E = DeclsInContainer.end(); I != E; ++I) {
1059 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001060 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001061 if (!V.hasValue())
1062 continue;
1063 if (!V.getValue())
1064 return false;
1065 if (Visit(Cursor, true))
1066 return true;
1067 }
1068 return false;
1069}
1070
1071bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1072 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1073 TU)))
1074 return true;
1075
Douglas Gregore9d95f12015-07-07 03:57:35 +00001076 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1077 return true;
1078
Guy Benyei11169dd2012-12-18 14:30:41 +00001079 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1080 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1081 E = ND->protocol_end(); I != E; ++I, ++PL)
1082 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1083 return true;
1084
1085 return VisitObjCContainerDecl(ND);
1086}
1087
1088bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1089 if (!PID->isThisDeclarationADefinition())
1090 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1091
1092 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1093 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1094 E = PID->protocol_end(); I != E; ++I, ++PL)
1095 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1096 return true;
1097
1098 return VisitObjCContainerDecl(PID);
1099}
1100
1101bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1102 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1103 return true;
1104
1105 // FIXME: This implements a workaround with @property declarations also being
1106 // installed in the DeclContext for the @interface. Eventually this code
1107 // should be removed.
1108 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1109 if (!CDecl || !CDecl->IsClassExtension())
1110 return false;
1111
1112 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1113 if (!ID)
1114 return false;
1115
1116 IdentifierInfo *PropertyId = PD->getIdentifier();
1117 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001118 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1119 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001120
1121 if (!prevDecl)
1122 return false;
1123
1124 // Visit synthesized methods since they will be skipped when visiting
1125 // the @interface.
1126 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1127 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1128 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1129 return true;
1130
1131 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1132 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1133 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1134 return true;
1135
1136 return false;
1137}
1138
Douglas Gregore9d95f12015-07-07 03:57:35 +00001139bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1140 if (!typeParamList)
1141 return false;
1142
1143 for (auto *typeParam : *typeParamList) {
1144 // Visit the type parameter.
1145 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1146 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001147 }
1148
1149 return false;
1150}
1151
Guy Benyei11169dd2012-12-18 14:30:41 +00001152bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1153 if (!D->isThisDeclarationADefinition()) {
1154 // Forward declaration is treated like a reference.
1155 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1156 }
1157
Douglas Gregore9d95f12015-07-07 03:57:35 +00001158 // Objective-C type parameters.
1159 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1160 return true;
1161
Guy Benyei11169dd2012-12-18 14:30:41 +00001162 // Issue callbacks for super class.
1163 if (D->getSuperClass() &&
1164 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1165 D->getSuperClassLoc(),
1166 TU)))
1167 return true;
1168
Douglas Gregore9d95f12015-07-07 03:57:35 +00001169 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1170 if (Visit(SuperClassTInfo->getTypeLoc()))
1171 return true;
1172
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1174 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1175 E = D->protocol_end(); I != E; ++I, ++PL)
1176 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1177 return true;
1178
1179 return VisitObjCContainerDecl(D);
1180}
1181
1182bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1183 return VisitObjCContainerDecl(D);
1184}
1185
1186bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1187 // 'ID' could be null when dealing with invalid code.
1188 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1189 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1190 return true;
1191
1192 return VisitObjCImplDecl(D);
1193}
1194
1195bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1196#if 0
1197 // Issue callbacks for super class.
1198 // FIXME: No source location information!
1199 if (D->getSuperClass() &&
1200 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1201 D->getSuperClassLoc(),
1202 TU)))
1203 return true;
1204#endif
1205
1206 return VisitObjCImplDecl(D);
1207}
1208
1209bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1210 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1211 if (PD->isIvarNameSpecified())
1212 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1213
1214 return false;
1215}
1216
1217bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1218 return VisitDeclContext(D);
1219}
1220
1221bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1222 // Visit nested-name-specifier.
1223 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1224 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1225 return true;
1226
1227 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1228 D->getTargetNameLoc(), TU));
1229}
1230
1231bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1232 // Visit nested-name-specifier.
1233 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1234 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1235 return true;
1236 }
1237
1238 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1239 return true;
1240
1241 return VisitDeclarationNameInfo(D->getNameInfo());
1242}
1243
1244bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1245 // Visit nested-name-specifier.
1246 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1247 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1248 return true;
1249
1250 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1251 D->getIdentLocation(), TU));
1252}
1253
1254bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1255 // Visit nested-name-specifier.
1256 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1257 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1258 return true;
1259 }
1260
1261 return VisitDeclarationNameInfo(D->getNameInfo());
1262}
1263
1264bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1265 UnresolvedUsingTypenameDecl *D) {
1266 // Visit nested-name-specifier.
1267 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1268 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1269 return true;
1270
1271 return false;
1272}
1273
Olivier Goffart81978012016-06-09 16:15:55 +00001274bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1275 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1276 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001277 if (StringLiteral *Message = D->getMessage())
1278 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1279 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001280 return false;
1281}
1282
Olivier Goffartd211c642016-11-04 06:29:27 +00001283bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1284 if (NamedDecl *FriendD = D->getFriendDecl()) {
1285 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1286 return true;
1287 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1288 if (Visit(TI->getTypeLoc()))
1289 return true;
1290 }
1291 return false;
1292}
1293
Guy Benyei11169dd2012-12-18 14:30:41 +00001294bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1295 switch (Name.getName().getNameKind()) {
1296 case clang::DeclarationName::Identifier:
1297 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001298 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 case clang::DeclarationName::CXXOperatorName:
1300 case clang::DeclarationName::CXXUsingDirective:
1301 return false;
Richard Smith35845152017-02-07 01:37:30 +00001302
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 case clang::DeclarationName::CXXConstructorName:
1304 case clang::DeclarationName::CXXDestructorName:
1305 case clang::DeclarationName::CXXConversionFunctionName:
1306 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1307 return Visit(TSInfo->getTypeLoc());
1308 return false;
1309
1310 case clang::DeclarationName::ObjCZeroArgSelector:
1311 case clang::DeclarationName::ObjCOneArgSelector:
1312 case clang::DeclarationName::ObjCMultiArgSelector:
1313 // FIXME: Per-identifier location info?
1314 return false;
1315 }
1316
1317 llvm_unreachable("Invalid DeclarationName::Kind!");
1318}
1319
1320bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1321 SourceRange Range) {
1322 // FIXME: This whole routine is a hack to work around the lack of proper
1323 // source information in nested-name-specifiers (PR5791). Since we do have
1324 // a beginning source location, we can visit the first component of the
1325 // nested-name-specifier, if it's a single-token component.
1326 if (!NNS)
1327 return false;
1328
1329 // Get the first component in the nested-name-specifier.
1330 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1331 NNS = Prefix;
1332
1333 switch (NNS->getKind()) {
1334 case NestedNameSpecifier::Namespace:
1335 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1336 TU));
1337
1338 case NestedNameSpecifier::NamespaceAlias:
1339 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1340 Range.getBegin(), TU));
1341
1342 case NestedNameSpecifier::TypeSpec: {
1343 // If the type has a form where we know that the beginning of the source
1344 // range matches up with a reference cursor. Visit the appropriate reference
1345 // cursor.
1346 const Type *T = NNS->getAsType();
1347 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1348 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1349 if (const TagType *Tag = dyn_cast<TagType>(T))
1350 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1351 if (const TemplateSpecializationType *TST
1352 = dyn_cast<TemplateSpecializationType>(T))
1353 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1354 break;
1355 }
1356
1357 case NestedNameSpecifier::TypeSpecWithTemplate:
1358 case NestedNameSpecifier::Global:
1359 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001360 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001361 break;
1362 }
1363
1364 return false;
1365}
1366
1367bool
1368CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1369 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1370 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1371 Qualifiers.push_back(Qualifier);
1372
1373 while (!Qualifiers.empty()) {
1374 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1375 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1376 switch (NNS->getKind()) {
1377 case NestedNameSpecifier::Namespace:
1378 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1379 Q.getLocalBeginLoc(),
1380 TU)))
1381 return true;
1382
1383 break;
1384
1385 case NestedNameSpecifier::NamespaceAlias:
1386 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1387 Q.getLocalBeginLoc(),
1388 TU)))
1389 return true;
1390
1391 break;
1392
1393 case NestedNameSpecifier::TypeSpec:
1394 case NestedNameSpecifier::TypeSpecWithTemplate:
1395 if (Visit(Q.getTypeLoc()))
1396 return true;
1397
1398 break;
1399
1400 case NestedNameSpecifier::Global:
1401 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001402 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 break;
1404 }
1405 }
1406
1407 return false;
1408}
1409
1410bool CursorVisitor::VisitTemplateParameters(
1411 const TemplateParameterList *Params) {
1412 if (!Params)
1413 return false;
1414
1415 for (TemplateParameterList::const_iterator P = Params->begin(),
1416 PEnd = Params->end();
1417 P != PEnd; ++P) {
1418 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1419 return true;
1420 }
1421
1422 return false;
1423}
1424
1425bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1426 switch (Name.getKind()) {
1427 case TemplateName::Template:
1428 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1429
1430 case TemplateName::OverloadedTemplate:
1431 // Visit the overloaded template set.
1432 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1433 return true;
1434
1435 return false;
1436
1437 case TemplateName::DependentTemplate:
1438 // FIXME: Visit nested-name-specifier.
1439 return false;
1440
1441 case TemplateName::QualifiedTemplate:
1442 // FIXME: Visit nested-name-specifier.
1443 return Visit(MakeCursorTemplateRef(
1444 Name.getAsQualifiedTemplateName()->getDecl(),
1445 Loc, TU));
1446
1447 case TemplateName::SubstTemplateTemplateParm:
1448 return Visit(MakeCursorTemplateRef(
1449 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1450 Loc, TU));
1451
1452 case TemplateName::SubstTemplateTemplateParmPack:
1453 return Visit(MakeCursorTemplateRef(
1454 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1455 Loc, TU));
1456 }
1457
1458 llvm_unreachable("Invalid TemplateName::Kind!");
1459}
1460
1461bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1462 switch (TAL.getArgument().getKind()) {
1463 case TemplateArgument::Null:
1464 case TemplateArgument::Integral:
1465 case TemplateArgument::Pack:
1466 return false;
1467
1468 case TemplateArgument::Type:
1469 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1470 return Visit(TSInfo->getTypeLoc());
1471 return false;
1472
1473 case TemplateArgument::Declaration:
1474 if (Expr *E = TAL.getSourceDeclExpression())
1475 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1476 return false;
1477
1478 case TemplateArgument::NullPtr:
1479 if (Expr *E = TAL.getSourceNullPtrExpression())
1480 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1481 return false;
1482
1483 case TemplateArgument::Expression:
1484 if (Expr *E = TAL.getSourceExpression())
1485 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1486 return false;
1487
1488 case TemplateArgument::Template:
1489 case TemplateArgument::TemplateExpansion:
1490 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1491 return true;
1492
1493 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1494 TAL.getTemplateNameLoc());
1495 }
1496
1497 llvm_unreachable("Invalid TemplateArgument::Kind!");
1498}
1499
1500bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1501 return VisitDeclContext(D);
1502}
1503
1504bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1505 return Visit(TL.getUnqualifiedLoc());
1506}
1507
1508bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1509 ASTContext &Context = AU->getASTContext();
1510
1511 // Some builtin types (such as Objective-C's "id", "sel", and
1512 // "Class") have associated declarations. Create cursors for those.
1513 QualType VisitType;
1514 switch (TL.getTypePtr()->getKind()) {
1515
1516 case BuiltinType::Void:
1517 case BuiltinType::NullPtr:
1518 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001519#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1520 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001521#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001522 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001523 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001524 case BuiltinType::OCLClkEvent:
1525 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001526 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001527#define BUILTIN_TYPE(Id, SingletonId)
1528#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1529#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1530#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1531#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1532#include "clang/AST/BuiltinTypes.def"
1533 break;
1534
1535 case BuiltinType::ObjCId:
1536 VisitType = Context.getObjCIdType();
1537 break;
1538
1539 case BuiltinType::ObjCClass:
1540 VisitType = Context.getObjCClassType();
1541 break;
1542
1543 case BuiltinType::ObjCSel:
1544 VisitType = Context.getObjCSelType();
1545 break;
1546 }
1547
1548 if (!VisitType.isNull()) {
1549 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1550 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1551 TU));
1552 }
1553
1554 return false;
1555}
1556
1557bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1558 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1559}
1560
1561bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1562 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1563}
1564
1565bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1566 if (TL.isDefinition())
1567 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1568
1569 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1570}
1571
1572bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1573 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1574}
1575
1576bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001577 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001578}
1579
Manman Rene6be26c2016-09-13 17:25:08 +00001580bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001581 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001582 return true;
1583 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1584 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1585 TU)))
1586 return true;
1587 }
1588
1589 return false;
1590}
1591
Guy Benyei11169dd2012-12-18 14:30:41 +00001592bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1593 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1594 return true;
1595
Douglas Gregore9d95f12015-07-07 03:57:35 +00001596 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1597 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1598 return true;
1599 }
1600
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1602 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1603 TU)))
1604 return true;
1605 }
1606
1607 return false;
1608}
1609
1610bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1611 return Visit(TL.getPointeeLoc());
1612}
1613
1614bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1615 return Visit(TL.getInnerLoc());
1616}
1617
1618bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1619 return Visit(TL.getPointeeLoc());
1620}
1621
1622bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1623 return Visit(TL.getPointeeLoc());
1624}
1625
1626bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1627 return Visit(TL.getPointeeLoc());
1628}
1629
1630bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1631 return Visit(TL.getPointeeLoc());
1632}
1633
1634bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1635 return Visit(TL.getPointeeLoc());
1636}
1637
1638bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1639 return Visit(TL.getModifiedLoc());
1640}
1641
1642bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1643 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001644 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 return true;
1646
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001647 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1648 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1650 return true;
1651
1652 return false;
1653}
1654
1655bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1656 if (Visit(TL.getElementLoc()))
1657 return true;
1658
1659 if (Expr *Size = TL.getSizeExpr())
1660 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1661
1662 return false;
1663}
1664
Reid Kleckner8a365022013-06-24 17:51:48 +00001665bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1666 return Visit(TL.getOriginalLoc());
1667}
1668
Reid Kleckner0503a872013-12-05 01:23:43 +00001669bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1670 return Visit(TL.getOriginalLoc());
1671}
1672
Richard Smith600b5262017-01-26 20:40:47 +00001673bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1674 DeducedTemplateSpecializationTypeLoc TL) {
1675 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1676 TL.getTemplateNameLoc()))
1677 return true;
1678
1679 return false;
1680}
1681
Guy Benyei11169dd2012-12-18 14:30:41 +00001682bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1683 TemplateSpecializationTypeLoc TL) {
1684 // Visit the template name.
1685 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1686 TL.getTemplateNameLoc()))
1687 return true;
1688
1689 // Visit the template arguments.
1690 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1691 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1692 return true;
1693
1694 return false;
1695}
1696
1697bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1698 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1699}
1700
1701bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1702 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1703 return Visit(TSInfo->getTypeLoc());
1704
1705 return false;
1706}
1707
1708bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1709 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1710 return Visit(TSInfo->getTypeLoc());
1711
1712 return false;
1713}
1714
1715bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001716 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001717}
1718
1719bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1720 DependentTemplateSpecializationTypeLoc TL) {
1721 // Visit the nested-name-specifier, if there is one.
1722 if (TL.getQualifierLoc() &&
1723 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1724 return true;
1725
1726 // Visit the template arguments.
1727 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1728 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1729 return true;
1730
1731 return false;
1732}
1733
1734bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1735 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1736 return true;
1737
1738 return Visit(TL.getNamedTypeLoc());
1739}
1740
1741bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1742 return Visit(TL.getPatternLoc());
1743}
1744
1745bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1746 if (Expr *E = TL.getUnderlyingExpr())
1747 return Visit(MakeCXCursor(E, StmtParent, TU));
1748
1749 return false;
1750}
1751
1752bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1753 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1754}
1755
1756bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1757 return Visit(TL.getValueLoc());
1758}
1759
Xiuli Pan9c14e282016-01-09 12:53:17 +00001760bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1761 return Visit(TL.getValueLoc());
1762}
1763
Guy Benyei11169dd2012-12-18 14:30:41 +00001764#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1765bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1766 return Visit##PARENT##Loc(TL); \
1767}
1768
1769DEFAULT_TYPELOC_IMPL(Complex, Type)
1770DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1771DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1772DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1773DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001774DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001775DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001776DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1777DEFAULT_TYPELOC_IMPL(Vector, Type)
1778DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1779DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1780DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1781DEFAULT_TYPELOC_IMPL(Record, TagType)
1782DEFAULT_TYPELOC_IMPL(Enum, TagType)
1783DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1784DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1785DEFAULT_TYPELOC_IMPL(Auto, Type)
1786
1787bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1788 // Visit the nested-name-specifier, if present.
1789 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1790 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1791 return true;
1792
1793 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001794 for (const auto &I : D->bases()) {
1795 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 return true;
1797 }
1798 }
1799
1800 return VisitTagDecl(D);
1801}
1802
1803bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001804 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001805 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1806 !I->isImplicit()) &&
1807 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 return true;
1809
1810 return false;
1811}
1812
1813//===----------------------------------------------------------------------===//
1814// Data-recursive visitor methods.
1815//===----------------------------------------------------------------------===//
1816
1817namespace {
1818#define DEF_JOB(NAME, DATA, KIND)\
1819class NAME : public VisitorJob {\
1820public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001821 NAME(const DATA *d, CXCursor parent) : \
1822 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001824 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001825};
1826
1827DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1828DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1829DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1830DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001831DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1832DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1833DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1834#undef DEF_JOB
1835
James Y Knight04ec5bf2015-12-24 02:59:37 +00001836class ExplicitTemplateArgsVisit : public VisitorJob {
1837public:
1838 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1839 const TemplateArgumentLoc *End, CXCursor parent)
1840 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1841 End) {}
1842 static bool classof(const VisitorJob *VJ) {
1843 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1844 }
1845 const TemplateArgumentLoc *begin() const {
1846 return static_cast<const TemplateArgumentLoc *>(data[0]);
1847 }
1848 const TemplateArgumentLoc *end() {
1849 return static_cast<const TemplateArgumentLoc *>(data[1]);
1850 }
1851};
Guy Benyei11169dd2012-12-18 14:30:41 +00001852class DeclVisit : public VisitorJob {
1853public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001854 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001855 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001856 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001857 static bool classof(const VisitorJob *VJ) {
1858 return VJ->getKind() == DeclVisitKind;
1859 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001860 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001861 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001862};
1863class TypeLocVisit : public VisitorJob {
1864public:
1865 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1866 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1867 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1868
1869 static bool classof(const VisitorJob *VJ) {
1870 return VJ->getKind() == TypeLocVisitKind;
1871 }
1872
1873 TypeLoc get() const {
1874 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001875 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 }
1877};
1878
1879class LabelRefVisit : public VisitorJob {
1880public:
1881 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1882 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1883 labelLoc.getPtrEncoding()) {}
1884
1885 static bool classof(const VisitorJob *VJ) {
1886 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1887 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001888 const LabelDecl *get() const {
1889 return static_cast<const LabelDecl *>(data[0]);
1890 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 SourceLocation getLoc() const {
1892 return SourceLocation::getFromPtrEncoding(data[1]); }
1893};
1894
1895class NestedNameSpecifierLocVisit : public VisitorJob {
1896public:
1897 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1898 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1899 Qualifier.getNestedNameSpecifier(),
1900 Qualifier.getOpaqueData()) { }
1901
1902 static bool classof(const VisitorJob *VJ) {
1903 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1904 }
1905
1906 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001907 return NestedNameSpecifierLoc(
1908 const_cast<NestedNameSpecifier *>(
1909 static_cast<const NestedNameSpecifier *>(data[0])),
1910 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001911 }
1912};
1913
1914class DeclarationNameInfoVisit : public VisitorJob {
1915public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001916 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001917 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001918 static bool classof(const VisitorJob *VJ) {
1919 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1920 }
1921 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001922 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001923 switch (S->getStmtClass()) {
1924 default:
1925 llvm_unreachable("Unhandled Stmt");
1926 case clang::Stmt::MSDependentExistsStmtClass:
1927 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1928 case Stmt::CXXDependentScopeMemberExprClass:
1929 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1930 case Stmt::DependentScopeDeclRefExprClass:
1931 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001932 case Stmt::OMPCriticalDirectiveClass:
1933 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 }
1935 }
1936};
1937class MemberRefVisit : public VisitorJob {
1938public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001939 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1941 L.getPtrEncoding()) {}
1942 static bool classof(const VisitorJob *VJ) {
1943 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1944 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001945 const FieldDecl *get() const {
1946 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001947 }
1948 SourceLocation getLoc() const {
1949 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1950 }
1951};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001952class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001953 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 VisitorWorkList &WL;
1955 CXCursor Parent;
1956public:
1957 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1958 : WL(wl), Parent(parent) {}
1959
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001960 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1961 void VisitBlockExpr(const BlockExpr *B);
1962 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1963 void VisitCompoundStmt(const CompoundStmt *S);
1964 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1965 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1966 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1967 void VisitCXXNewExpr(const CXXNewExpr *E);
1968 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1969 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1970 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1971 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1972 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1973 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1974 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1975 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001976 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001977 void VisitDeclRefExpr(const DeclRefExpr *D);
1978 void VisitDeclStmt(const DeclStmt *S);
1979 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1980 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1981 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1982 void VisitForStmt(const ForStmt *FS);
1983 void VisitGotoStmt(const GotoStmt *GS);
1984 void VisitIfStmt(const IfStmt *If);
1985 void VisitInitListExpr(const InitListExpr *IE);
1986 void VisitMemberExpr(const MemberExpr *M);
1987 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1988 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1989 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1990 void VisitOverloadExpr(const OverloadExpr *E);
1991 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1992 void VisitStmt(const Stmt *S);
1993 void VisitSwitchStmt(const SwitchStmt *S);
1994 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001995 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1996 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1997 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1998 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1999 void VisitVAArgExpr(const VAArgExpr *E);
2000 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2001 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2002 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2003 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002004 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002005 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002006 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002007 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002008 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002009 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002010 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002011 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002012 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002013 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002014 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002015 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002016 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002017 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002018 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002019 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002020 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002021 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002022 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002023 void
2024 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002025 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002026 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002027 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002028 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002029 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002030 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002031 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002032 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002033 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002034 void
2035 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002036 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002037 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002038 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002039 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002040 void VisitOMPDistributeParallelForDirective(
2041 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002042 void VisitOMPDistributeParallelForSimdDirective(
2043 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002044 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002045 void VisitOMPTargetParallelForSimdDirective(
2046 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002047 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002048 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002049 void VisitOMPTeamsDistributeSimdDirective(
2050 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002051 void VisitOMPTeamsDistributeParallelForSimdDirective(
2052 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002053 void VisitOMPTeamsDistributeParallelForDirective(
2054 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002055 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002056 void VisitOMPTargetTeamsDistributeDirective(
2057 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002058 void VisitOMPTargetTeamsDistributeParallelForDirective(
2059 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002060 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2061 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002062 void VisitOMPTargetTeamsDistributeSimdDirective(
2063 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002064
Guy Benyei11169dd2012-12-18 14:30:41 +00002065private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002066 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002067 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002068 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2069 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002070 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2071 void AddStmt(const Stmt *S);
2072 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002073 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002074 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002075 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002076};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002077} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002078
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002079void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 // 'S' should always be non-null, since it comes from the
2081 // statement we are visiting.
2082 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2083}
2084
2085void
2086EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2087 if (Qualifier)
2088 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2089}
2090
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002091void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002092 if (S)
2093 WL.push_back(StmtVisit(S, Parent));
2094}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002095void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 if (D)
2097 WL.push_back(DeclVisit(D, Parent, isFirst));
2098}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002099void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2100 unsigned NumTemplateArgs) {
2101 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002102}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002103void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 if (D)
2105 WL.push_back(MemberRefVisit(D, L, Parent));
2106}
2107void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2108 if (TI)
2109 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2110 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002111void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002112 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002113 for (const Stmt *SubStmt : S->children()) {
2114 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 }
2116 if (size == WL.size())
2117 return;
2118 // Now reverse the entries we just added. This will match the DFS
2119 // ordering performed by the worklist.
2120 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2121 std::reverse(I, E);
2122}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002123namespace {
2124class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2125 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002126 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002127 template <typename T>
2128 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002129public:
2130 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2131#define OPENMP_CLAUSE(Name, Class) \
2132 void Visit##Class(const Class *C);
2133#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002134 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002135 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002136};
2137
Alexey Bataev3392d762016-02-16 11:18:12 +00002138void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2139 const OMPClauseWithPreInit *C) {
2140 Visitor->AddStmt(C->getPreInitStmt());
2141}
2142
Alexey Bataev005248a2016-02-25 05:25:57 +00002143void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2144 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002145 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002146 Visitor->AddStmt(C->getPostUpdateExpr());
2147}
2148
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002149void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002150 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002151 Visitor->AddStmt(C->getCondition());
2152}
2153
Alexey Bataev3778b602014-07-17 07:32:53 +00002154void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2155 Visitor->AddStmt(C->getCondition());
2156}
2157
Alexey Bataev568a8332014-03-06 06:15:19 +00002158void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002159 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002160 Visitor->AddStmt(C->getNumThreads());
2161}
2162
Alexey Bataev62c87d22014-03-21 04:51:18 +00002163void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2164 Visitor->AddStmt(C->getSafelen());
2165}
2166
Alexey Bataev66b15b52015-08-21 11:14:16 +00002167void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2168 Visitor->AddStmt(C->getSimdlen());
2169}
2170
Alexander Musman8bd31e62014-05-27 15:12:19 +00002171void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2172 Visitor->AddStmt(C->getNumForLoops());
2173}
2174
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002175void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002176
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002177void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2178
Alexey Bataev56dafe82014-06-20 07:16:17 +00002179void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002180 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002181 Visitor->AddStmt(C->getChunkSize());
2182}
2183
Alexey Bataev10e775f2015-07-30 11:36:16 +00002184void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2185 Visitor->AddStmt(C->getNumForLoops());
2186}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002187
Alexey Bataev236070f2014-06-20 11:19:47 +00002188void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2189
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002190void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2191
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002192void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2193
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002194void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2195
Alexey Bataevdea47612014-07-23 07:46:59 +00002196void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2197
Alexey Bataev67a4f222014-07-23 10:25:33 +00002198void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2199
Alexey Bataev459dec02014-07-24 06:46:57 +00002200void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2201
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002202void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2203
Alexey Bataev346265e2015-09-25 10:37:12 +00002204void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2205
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002206void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2207
Alexey Bataevb825de12015-12-07 10:51:44 +00002208void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2209
Kelvin Li1408f912018-09-26 04:28:39 +00002210void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2211 const OMPUnifiedAddressClause *) {}
2212
Michael Wonge710d542015-08-07 16:16:36 +00002213void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2214 Visitor->AddStmt(C->getDevice());
2215}
2216
Kelvin Li099bb8c2015-11-24 20:50:12 +00002217void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002218 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002219 Visitor->AddStmt(C->getNumTeams());
2220}
2221
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002222void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002223 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002224 Visitor->AddStmt(C->getThreadLimit());
2225}
2226
Alexey Bataeva0569352015-12-01 10:17:31 +00002227void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2228 Visitor->AddStmt(C->getPriority());
2229}
2230
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002231void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2232 Visitor->AddStmt(C->getGrainsize());
2233}
2234
Alexey Bataev382967a2015-12-08 12:06:20 +00002235void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2236 Visitor->AddStmt(C->getNumTasks());
2237}
2238
Alexey Bataev28c75412015-12-15 08:19:24 +00002239void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2240 Visitor->AddStmt(C->getHint());
2241}
2242
Alexey Bataev756c1962013-09-24 03:17:45 +00002243template<typename T>
2244void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002245 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002246 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002247 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002248}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002249
2250void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002251 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002252 for (const auto *E : C->private_copies()) {
2253 Visitor->AddStmt(E);
2254 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002255}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002256void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2257 const OMPFirstprivateClause *C) {
2258 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002259 VisitOMPClauseWithPreInit(C);
2260 for (const auto *E : C->private_copies()) {
2261 Visitor->AddStmt(E);
2262 }
2263 for (const auto *E : C->inits()) {
2264 Visitor->AddStmt(E);
2265 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002266}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002267void OMPClauseEnqueue::VisitOMPLastprivateClause(
2268 const OMPLastprivateClause *C) {
2269 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002270 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002271 for (auto *E : C->private_copies()) {
2272 Visitor->AddStmt(E);
2273 }
2274 for (auto *E : C->source_exprs()) {
2275 Visitor->AddStmt(E);
2276 }
2277 for (auto *E : C->destination_exprs()) {
2278 Visitor->AddStmt(E);
2279 }
2280 for (auto *E : C->assignment_ops()) {
2281 Visitor->AddStmt(E);
2282 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002283}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002284void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002285 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002286}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002287void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2288 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002289 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002290 for (auto *E : C->privates()) {
2291 Visitor->AddStmt(E);
2292 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002293 for (auto *E : C->lhs_exprs()) {
2294 Visitor->AddStmt(E);
2295 }
2296 for (auto *E : C->rhs_exprs()) {
2297 Visitor->AddStmt(E);
2298 }
2299 for (auto *E : C->reduction_ops()) {
2300 Visitor->AddStmt(E);
2301 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002302}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002303void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2304 const OMPTaskReductionClause *C) {
2305 VisitOMPClauseList(C);
2306 VisitOMPClauseWithPostUpdate(C);
2307 for (auto *E : C->privates()) {
2308 Visitor->AddStmt(E);
2309 }
2310 for (auto *E : C->lhs_exprs()) {
2311 Visitor->AddStmt(E);
2312 }
2313 for (auto *E : C->rhs_exprs()) {
2314 Visitor->AddStmt(E);
2315 }
2316 for (auto *E : C->reduction_ops()) {
2317 Visitor->AddStmt(E);
2318 }
2319}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002320void OMPClauseEnqueue::VisitOMPInReductionClause(
2321 const OMPInReductionClause *C) {
2322 VisitOMPClauseList(C);
2323 VisitOMPClauseWithPostUpdate(C);
2324 for (auto *E : C->privates()) {
2325 Visitor->AddStmt(E);
2326 }
2327 for (auto *E : C->lhs_exprs()) {
2328 Visitor->AddStmt(E);
2329 }
2330 for (auto *E : C->rhs_exprs()) {
2331 Visitor->AddStmt(E);
2332 }
2333 for (auto *E : C->reduction_ops()) {
2334 Visitor->AddStmt(E);
2335 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002336 for (auto *E : C->taskgroup_descriptors())
2337 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002338}
Alexander Musman8dba6642014-04-22 13:09:42 +00002339void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2340 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002341 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002342 for (const auto *E : C->privates()) {
2343 Visitor->AddStmt(E);
2344 }
Alexander Musman3276a272015-03-21 10:12:56 +00002345 for (const auto *E : C->inits()) {
2346 Visitor->AddStmt(E);
2347 }
2348 for (const auto *E : C->updates()) {
2349 Visitor->AddStmt(E);
2350 }
2351 for (const auto *E : C->finals()) {
2352 Visitor->AddStmt(E);
2353 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002354 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002355 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002356}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002357void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2358 VisitOMPClauseList(C);
2359 Visitor->AddStmt(C->getAlignment());
2360}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002361void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2362 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002363 for (auto *E : C->source_exprs()) {
2364 Visitor->AddStmt(E);
2365 }
2366 for (auto *E : C->destination_exprs()) {
2367 Visitor->AddStmt(E);
2368 }
2369 for (auto *E : C->assignment_ops()) {
2370 Visitor->AddStmt(E);
2371 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002372}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002373void
2374OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2375 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002376 for (auto *E : C->source_exprs()) {
2377 Visitor->AddStmt(E);
2378 }
2379 for (auto *E : C->destination_exprs()) {
2380 Visitor->AddStmt(E);
2381 }
2382 for (auto *E : C->assignment_ops()) {
2383 Visitor->AddStmt(E);
2384 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002385}
Alexey Bataev6125da92014-07-21 11:26:11 +00002386void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2387 VisitOMPClauseList(C);
2388}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002389void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2390 VisitOMPClauseList(C);
2391}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002392void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2393 VisitOMPClauseList(C);
2394}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002395void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2396 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002397 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002398 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002399}
Alexey Bataev3392d762016-02-16 11:18:12 +00002400void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2401 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002402void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2403 VisitOMPClauseList(C);
2404}
Samuel Antaoec172c62016-05-26 17:49:04 +00002405void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2406 VisitOMPClauseList(C);
2407}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002408void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2409 VisitOMPClauseList(C);
2410}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002411void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2412 VisitOMPClauseList(C);
2413}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002414}
Alexey Bataev756c1962013-09-24 03:17:45 +00002415
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002416void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2417 unsigned size = WL.size();
2418 OMPClauseEnqueue Visitor(this);
2419 Visitor.Visit(S);
2420 if (size == WL.size())
2421 return;
2422 // Now reverse the entries we just added. This will match the DFS
2423 // ordering performed by the worklist.
2424 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2425 std::reverse(I, E);
2426}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002427void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2429}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002430void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 AddDecl(B->getBlockDecl());
2432}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002433void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 EnqueueChildren(E);
2435 AddTypeLoc(E->getTypeSourceInfo());
2436}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002437void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002438 for (auto &I : llvm::reverse(S->body()))
2439 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002440}
2441void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002442VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 AddStmt(S->getSubStmt());
2444 AddDeclarationNameInfo(S);
2445 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2446 AddNestedNameSpecifierLoc(QualifierLoc);
2447}
2448
2449void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002450VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002451 if (E->hasExplicitTemplateArgs())
2452 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 AddDeclarationNameInfo(E);
2454 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2455 AddNestedNameSpecifierLoc(QualifierLoc);
2456 if (!E->isImplicitAccess())
2457 AddStmt(E->getBase());
2458}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002459void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 // Enqueue the initializer , if any.
2461 AddStmt(E->getInitializer());
2462 // Enqueue the array size, if any.
2463 AddStmt(E->getArraySize());
2464 // Enqueue the allocated type.
2465 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2466 // Enqueue the placement arguments.
2467 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2468 AddStmt(E->getPlacementArg(I-1));
2469}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002470void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2472 AddStmt(CE->getArg(I-1));
2473 AddStmt(CE->getCallee());
2474 AddStmt(CE->getArg(0));
2475}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002476void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2477 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 // Visit the name of the type being destroyed.
2479 AddTypeLoc(E->getDestroyedTypeInfo());
2480 // Visit the scope type that looks disturbingly like the nested-name-specifier
2481 // but isn't.
2482 AddTypeLoc(E->getScopeTypeInfo());
2483 // Visit the nested-name-specifier.
2484 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2485 AddNestedNameSpecifierLoc(QualifierLoc);
2486 // Visit base expression.
2487 AddStmt(E->getBase());
2488}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002489void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2490 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 AddTypeLoc(E->getTypeSourceInfo());
2492}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002493void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2494 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 EnqueueChildren(E);
2496 AddTypeLoc(E->getTypeSourceInfo());
2497}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002498void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 EnqueueChildren(E);
2500 if (E->isTypeOperand())
2501 AddTypeLoc(E->getTypeOperandSourceInfo());
2502}
2503
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002504void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2505 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 EnqueueChildren(E);
2507 AddTypeLoc(E->getTypeSourceInfo());
2508}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002509void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 EnqueueChildren(E);
2511 if (E->isTypeOperand())
2512 AddTypeLoc(E->getTypeOperandSourceInfo());
2513}
2514
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002515void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 EnqueueChildren(S);
2517 AddDecl(S->getExceptionDecl());
2518}
2519
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002520void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002521 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002522 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002523 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002524}
2525
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002526void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002527 if (DR->hasExplicitTemplateArgs())
2528 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 WL.push_back(DeclRefExprParts(DR, Parent));
2530}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002531void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2532 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002533 if (E->hasExplicitTemplateArgs())
2534 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 AddDeclarationNameInfo(E);
2536 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2537}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002538void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 unsigned size = WL.size();
2540 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002541 for (const auto *D : S->decls()) {
2542 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 isFirst = false;
2544 }
2545 if (size == WL.size())
2546 return;
2547 // Now reverse the entries we just added. This will match the DFS
2548 // ordering performed by the worklist.
2549 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2550 std::reverse(I, E);
2551}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002552void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002554 for (const DesignatedInitExpr::Designator &D :
2555 llvm::reverse(E->designators())) {
2556 if (D.isFieldDesignator()) {
2557 if (FieldDecl *Field = D.getField())
2558 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 continue;
2560 }
David Majnemerf7e36092016-06-23 00:15:04 +00002561 if (D.isArrayDesignator()) {
2562 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 continue;
2564 }
David Majnemerf7e36092016-06-23 00:15:04 +00002565 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2566 AddStmt(E->getArrayRangeEnd(D));
2567 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 }
2569}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002570void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 EnqueueChildren(E);
2572 AddTypeLoc(E->getTypeInfoAsWritten());
2573}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002574void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 AddStmt(FS->getBody());
2576 AddStmt(FS->getInc());
2577 AddStmt(FS->getCond());
2578 AddDecl(FS->getConditionVariable());
2579 AddStmt(FS->getInit());
2580}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002581void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2583}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002584void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 AddStmt(If->getElse());
2586 AddStmt(If->getThen());
2587 AddStmt(If->getCond());
2588 AddDecl(If->getConditionVariable());
2589}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002590void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 // We care about the syntactic form of the initializer list, only.
2592 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2593 IE = Syntactic;
2594 EnqueueChildren(IE);
2595}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002596void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 WL.push_back(MemberExprParts(M, Parent));
2598
2599 // If the base of the member access expression is an implicit 'this', don't
2600 // visit it.
2601 // FIXME: If we ever want to show these implicit accesses, this will be
2602 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002603 if (M->isImplicitAccess())
2604 return;
2605
2606 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002607 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002608 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2609 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2610 if (FD->isAnonymousStructOrUnion()) {
2611 AddStmt(SubME->getBase());
2612 return;
2613 }
2614 }
2615 }
2616
2617 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002618}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002619void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 AddTypeLoc(E->getEncodedTypeSourceInfo());
2621}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002622void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 EnqueueChildren(M);
2624 AddTypeLoc(M->getClassReceiverTypeInfo());
2625}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002626void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 // Visit the components of the offsetof expression.
2628 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 const OffsetOfNode &Node = E->getComponent(I-1);
2630 switch (Node.getKind()) {
2631 case OffsetOfNode::Array:
2632 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2633 break;
2634 case OffsetOfNode::Field:
2635 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2636 break;
2637 case OffsetOfNode::Identifier:
2638 case OffsetOfNode::Base:
2639 continue;
2640 }
2641 }
2642 // Visit the type into which we're computing the offset.
2643 AddTypeLoc(E->getTypeSourceInfo());
2644}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002645void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002646 if (E->hasExplicitTemplateArgs())
2647 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 WL.push_back(OverloadExprParts(E, Parent));
2649}
2650void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002651 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 EnqueueChildren(E);
2653 if (E->isArgumentType())
2654 AddTypeLoc(E->getArgumentTypeInfo());
2655}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002656void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 EnqueueChildren(S);
2658}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002659void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 AddStmt(S->getBody());
2661 AddStmt(S->getCond());
2662 AddDecl(S->getConditionVariable());
2663}
2664
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002665void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 AddStmt(W->getBody());
2667 AddStmt(W->getCond());
2668 AddDecl(W->getConditionVariable());
2669}
2670
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002671void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 for (unsigned I = E->getNumArgs(); I > 0; --I)
2673 AddTypeLoc(E->getArg(I-1));
2674}
2675
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002676void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002677 AddTypeLoc(E->getQueriedTypeSourceInfo());
2678}
2679
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002680void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 EnqueueChildren(E);
2682}
2683
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002684void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 VisitOverloadExpr(U);
2686 if (!U->isImplicitAccess())
2687 AddStmt(U->getBase());
2688}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002689void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 AddStmt(E->getSubExpr());
2691 AddTypeLoc(E->getWrittenTypeInfo());
2692}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002693void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 WL.push_back(SizeOfPackExprParts(E, Parent));
2695}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002696void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 // If the opaque value has a source expression, just transparently
2698 // visit that. This is useful for (e.g.) pseudo-object expressions.
2699 if (Expr *SourceExpr = E->getSourceExpr())
2700 return Visit(SourceExpr);
2701}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002702void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 AddStmt(E->getBody());
2704 WL.push_back(LambdaExprParts(E, Parent));
2705}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002706void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 // Treat the expression like its syntactic form.
2708 Visit(E->getSyntacticForm());
2709}
2710
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002711void EnqueueVisitor::VisitOMPExecutableDirective(
2712 const OMPExecutableDirective *D) {
2713 EnqueueChildren(D);
2714 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2715 E = D->clauses().end();
2716 I != E; ++I)
2717 EnqueueChildren(*I);
2718}
2719
Alexander Musman3aaab662014-08-19 11:27:13 +00002720void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2721 VisitOMPExecutableDirective(D);
2722}
2723
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002724void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2725 VisitOMPExecutableDirective(D);
2726}
2727
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002728void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002729 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002730}
2731
Alexey Bataevf29276e2014-06-18 04:14:57 +00002732void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002733 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002734}
2735
Alexander Musmanf82886e2014-09-18 05:12:34 +00002736void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2737 VisitOMPLoopDirective(D);
2738}
2739
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002740void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2741 VisitOMPExecutableDirective(D);
2742}
2743
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002744void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2745 VisitOMPExecutableDirective(D);
2746}
2747
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002748void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2749 VisitOMPExecutableDirective(D);
2750}
2751
Alexander Musman80c22892014-07-17 08:54:58 +00002752void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2753 VisitOMPExecutableDirective(D);
2754}
2755
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002756void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2757 VisitOMPExecutableDirective(D);
2758 AddDeclarationNameInfo(D);
2759}
2760
Alexey Bataev4acb8592014-07-07 13:01:15 +00002761void
2762EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002763 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002764}
2765
Alexander Musmane4e893b2014-09-23 09:33:00 +00002766void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2767 const OMPParallelForSimdDirective *D) {
2768 VisitOMPLoopDirective(D);
2769}
2770
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002771void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2772 const OMPParallelSectionsDirective *D) {
2773 VisitOMPExecutableDirective(D);
2774}
2775
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002776void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2777 VisitOMPExecutableDirective(D);
2778}
2779
Alexey Bataev68446b72014-07-18 07:47:19 +00002780void
2781EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2782 VisitOMPExecutableDirective(D);
2783}
2784
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002785void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2786 VisitOMPExecutableDirective(D);
2787}
2788
Alexey Bataev2df347a2014-07-18 10:17:07 +00002789void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2790 VisitOMPExecutableDirective(D);
2791}
2792
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002793void EnqueueVisitor::VisitOMPTaskgroupDirective(
2794 const OMPTaskgroupDirective *D) {
2795 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002796 if (const Expr *E = D->getReductionRef())
2797 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002798}
2799
Alexey Bataev6125da92014-07-21 11:26:11 +00002800void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2801 VisitOMPExecutableDirective(D);
2802}
2803
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002804void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2805 VisitOMPExecutableDirective(D);
2806}
2807
Alexey Bataev0162e452014-07-22 10:10:35 +00002808void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2809 VisitOMPExecutableDirective(D);
2810}
2811
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002812void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2813 VisitOMPExecutableDirective(D);
2814}
2815
Michael Wong65f367f2015-07-21 13:44:28 +00002816void EnqueueVisitor::VisitOMPTargetDataDirective(const
2817 OMPTargetDataDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819}
2820
Samuel Antaodf67fc42016-01-19 19:15:56 +00002821void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2822 const OMPTargetEnterDataDirective *D) {
2823 VisitOMPExecutableDirective(D);
2824}
2825
Samuel Antao72590762016-01-19 20:04:50 +00002826void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2827 const OMPTargetExitDataDirective *D) {
2828 VisitOMPExecutableDirective(D);
2829}
2830
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002831void EnqueueVisitor::VisitOMPTargetParallelDirective(
2832 const OMPTargetParallelDirective *D) {
2833 VisitOMPExecutableDirective(D);
2834}
2835
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002836void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2837 const OMPTargetParallelForDirective *D) {
2838 VisitOMPLoopDirective(D);
2839}
2840
Alexey Bataev13314bf2014-10-09 04:18:56 +00002841void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2842 VisitOMPExecutableDirective(D);
2843}
2844
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002845void EnqueueVisitor::VisitOMPCancellationPointDirective(
2846 const OMPCancellationPointDirective *D) {
2847 VisitOMPExecutableDirective(D);
2848}
2849
Alexey Bataev80909872015-07-02 11:25:17 +00002850void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2851 VisitOMPExecutableDirective(D);
2852}
2853
Alexey Bataev49f6e782015-12-01 04:18:41 +00002854void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2855 VisitOMPLoopDirective(D);
2856}
2857
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002858void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2859 const OMPTaskLoopSimdDirective *D) {
2860 VisitOMPLoopDirective(D);
2861}
2862
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002863void EnqueueVisitor::VisitOMPDistributeDirective(
2864 const OMPDistributeDirective *D) {
2865 VisitOMPLoopDirective(D);
2866}
2867
Carlo Bertolli9925f152016-06-27 14:55:37 +00002868void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2869 const OMPDistributeParallelForDirective *D) {
2870 VisitOMPLoopDirective(D);
2871}
2872
Kelvin Li4a39add2016-07-05 05:00:15 +00002873void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2874 const OMPDistributeParallelForSimdDirective *D) {
2875 VisitOMPLoopDirective(D);
2876}
2877
Kelvin Li787f3fc2016-07-06 04:45:38 +00002878void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2879 const OMPDistributeSimdDirective *D) {
2880 VisitOMPLoopDirective(D);
2881}
2882
Kelvin Lia579b912016-07-14 02:54:56 +00002883void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2884 const OMPTargetParallelForSimdDirective *D) {
2885 VisitOMPLoopDirective(D);
2886}
2887
Kelvin Li986330c2016-07-20 22:57:10 +00002888void EnqueueVisitor::VisitOMPTargetSimdDirective(
2889 const OMPTargetSimdDirective *D) {
2890 VisitOMPLoopDirective(D);
2891}
2892
Kelvin Li02532872016-08-05 14:37:37 +00002893void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2894 const OMPTeamsDistributeDirective *D) {
2895 VisitOMPLoopDirective(D);
2896}
2897
Kelvin Li4e325f72016-10-25 12:50:55 +00002898void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2899 const OMPTeamsDistributeSimdDirective *D) {
2900 VisitOMPLoopDirective(D);
2901}
2902
Kelvin Li579e41c2016-11-30 23:51:03 +00002903void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2904 const OMPTeamsDistributeParallelForSimdDirective *D) {
2905 VisitOMPLoopDirective(D);
2906}
2907
Kelvin Li7ade93f2016-12-09 03:24:30 +00002908void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2909 const OMPTeamsDistributeParallelForDirective *D) {
2910 VisitOMPLoopDirective(D);
2911}
2912
Kelvin Libf594a52016-12-17 05:48:59 +00002913void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2914 const OMPTargetTeamsDirective *D) {
2915 VisitOMPExecutableDirective(D);
2916}
2917
Kelvin Li83c451e2016-12-25 04:52:54 +00002918void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2919 const OMPTargetTeamsDistributeDirective *D) {
2920 VisitOMPLoopDirective(D);
2921}
2922
Kelvin Li80e8f562016-12-29 22:16:30 +00002923void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2924 const OMPTargetTeamsDistributeParallelForDirective *D) {
2925 VisitOMPLoopDirective(D);
2926}
2927
Kelvin Li1851df52017-01-03 05:23:48 +00002928void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2929 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2930 VisitOMPLoopDirective(D);
2931}
2932
Kelvin Lida681182017-01-10 18:08:18 +00002933void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2934 const OMPTargetTeamsDistributeSimdDirective *D) {
2935 VisitOMPLoopDirective(D);
2936}
2937
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002938void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2940}
2941
2942bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2943 if (RegionOfInterest.isValid()) {
2944 SourceRange Range = getRawCursorExtent(C);
2945 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2946 return false;
2947 }
2948 return true;
2949}
2950
2951bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2952 while (!WL.empty()) {
2953 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002954 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002955
2956 // Set the Parent field, then back to its old value once we're done.
2957 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2958
2959 switch (LI.getKind()) {
2960 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002961 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002962 if (!D)
2963 continue;
2964
2965 // For now, perform default visitation for Decls.
2966 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2967 cast<DeclVisit>(&LI)->isFirst())))
2968 return true;
2969
2970 continue;
2971 }
2972 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002973 for (const TemplateArgumentLoc &Arg :
2974 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2975 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 return true;
2977 }
2978 continue;
2979 }
2980 case VisitorJob::TypeLocVisitKind: {
2981 // Perform default visitation for TypeLocs.
2982 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2983 return true;
2984 continue;
2985 }
2986 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002987 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 if (LabelStmt *stmt = LS->getStmt()) {
2989 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2990 TU))) {
2991 return true;
2992 }
2993 }
2994 continue;
2995 }
2996
2997 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2998 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2999 if (VisitNestedNameSpecifierLoc(V->get()))
3000 return true;
3001 continue;
3002 }
3003
3004 case VisitorJob::DeclarationNameInfoVisitKind: {
3005 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3006 ->get()))
3007 return true;
3008 continue;
3009 }
3010 case VisitorJob::MemberRefVisitKind: {
3011 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3012 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3013 return true;
3014 continue;
3015 }
3016 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003017 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 if (!S)
3019 continue;
3020
3021 // Update the current cursor.
3022 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3023 if (!IsInRegionOfInterest(Cursor))
3024 continue;
3025 switch (Visitor(Cursor, Parent, ClientData)) {
3026 case CXChildVisit_Break: return true;
3027 case CXChildVisit_Continue: break;
3028 case CXChildVisit_Recurse:
3029 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003030 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 EnqueueWorkList(WL, S);
3032 break;
3033 }
3034 continue;
3035 }
3036 case VisitorJob::MemberExprPartsKind: {
3037 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003038 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003039
3040 // Visit the nested-name-specifier
3041 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3042 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3043 return true;
3044
3045 // Visit the declaration name.
3046 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3047 return true;
3048
3049 // Visit the explicitly-specified template arguments, if any.
3050 if (M->hasExplicitTemplateArgs()) {
3051 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3052 *ArgEnd = Arg + M->getNumTemplateArgs();
3053 Arg != ArgEnd; ++Arg) {
3054 if (VisitTemplateArgumentLoc(*Arg))
3055 return true;
3056 }
3057 }
3058 continue;
3059 }
3060 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003061 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 // Visit nested-name-specifier, if present.
3063 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3064 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3065 return true;
3066 // Visit declaration name.
3067 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3068 return true;
3069 continue;
3070 }
3071 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003072 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003073 // Visit the nested-name-specifier.
3074 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3075 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3076 return true;
3077 // Visit the declaration name.
3078 if (VisitDeclarationNameInfo(O->getNameInfo()))
3079 return true;
3080 // Visit the overloaded declaration reference.
3081 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3082 return true;
3083 continue;
3084 }
3085 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003086 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 NamedDecl *Pack = E->getPack();
3088 if (isa<TemplateTypeParmDecl>(Pack)) {
3089 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3090 E->getPackLoc(), TU)))
3091 return true;
3092
3093 continue;
3094 }
3095
3096 if (isa<TemplateTemplateParmDecl>(Pack)) {
3097 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3098 E->getPackLoc(), TU)))
3099 return true;
3100
3101 continue;
3102 }
3103
3104 // Non-type template parameter packs and function parameter packs are
3105 // treated like DeclRefExpr cursors.
3106 continue;
3107 }
3108
3109 case VisitorJob::LambdaExprPartsKind: {
3110 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003111 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003112 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3113 CEnd = E->explicit_capture_end();
3114 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003115 // FIXME: Lambda init-captures.
3116 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003118
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3120 C->getLocation(),
3121 TU)))
3122 return true;
3123 }
3124
3125 // Visit parameters and return type, if present.
3126 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3127 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3128 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3129 // Visit the whole type.
3130 if (Visit(TL))
3131 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003132 } else if (FunctionProtoTypeLoc Proto =
3133 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 if (E->hasExplicitParameters()) {
3135 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003136 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3137 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 return true;
3139 } else {
3140 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003141 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 return true;
3143 }
3144 }
3145 }
3146 break;
3147 }
3148
3149 case VisitorJob::PostChildrenVisitKind:
3150 if (PostChildrenVisitor(Parent, ClientData))
3151 return true;
3152 break;
3153 }
3154 }
3155 return false;
3156}
3157
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003158bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003159 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003160 if (!WorkListFreeList.empty()) {
3161 WL = WorkListFreeList.back();
3162 WL->clear();
3163 WorkListFreeList.pop_back();
3164 }
3165 else {
3166 WL = new VisitorWorkList();
3167 WorkListCache.push_back(WL);
3168 }
3169 EnqueueWorkList(*WL, S);
3170 bool result = RunVisitorWorkList(*WL);
3171 WorkListFreeList.push_back(WL);
3172 return result;
3173}
3174
3175namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003176typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003177RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3178 const DeclarationNameInfo &NI, SourceRange QLoc,
3179 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003180 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3181 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3182 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3183
3184 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3185
3186 RefNamePieces Pieces;
3187
3188 if (WantQualifier && QLoc.isValid())
3189 Pieces.push_back(QLoc);
3190
3191 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3192 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003193
3194 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3195 Pieces.push_back(*TemplateArgsLoc);
3196
Guy Benyei11169dd2012-12-18 14:30:41 +00003197 if (Kind == DeclarationName::CXXOperatorName) {
3198 Pieces.push_back(SourceLocation::getFromRawEncoding(
3199 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3200 Pieces.push_back(SourceLocation::getFromRawEncoding(
3201 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3202 }
3203
3204 if (WantSinglePiece) {
3205 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3206 Pieces.clear();
3207 Pieces.push_back(R);
3208 }
3209
3210 return Pieces;
3211}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003212}
Guy Benyei11169dd2012-12-18 14:30:41 +00003213
3214//===----------------------------------------------------------------------===//
3215// Misc. API hooks.
3216//===----------------------------------------------------------------------===//
3217
Chad Rosier05c71aa2013-03-27 18:28:23 +00003218static void fatal_error_handler(void *user_data, const std::string& reason,
3219 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003220 // Write the result out to stderr avoiding errs() because raw_ostreams can
3221 // call report_fatal_error.
3222 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3223 ::abort();
3224}
3225
Chandler Carruth66660742014-06-27 16:37:27 +00003226namespace {
3227struct RegisterFatalErrorHandler {
3228 RegisterFatalErrorHandler() {
3229 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3230 }
3231};
3232}
3233
3234static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3235
Guy Benyei11169dd2012-12-18 14:30:41 +00003236CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3237 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 // We use crash recovery to make some of our APIs more reliable, implicitly
3239 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003240 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3241 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003242
Chandler Carruth66660742014-06-27 16:37:27 +00003243 // Look through the managed static to trigger construction of the managed
3244 // static which registers our fatal error handler. This ensures it is only
3245 // registered once.
3246 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003247
Adrian Prantlbc068582015-07-08 01:00:30 +00003248 // Initialize targets for clang module support.
3249 llvm::InitializeAllTargets();
3250 llvm::InitializeAllTargetMCs();
3251 llvm::InitializeAllAsmPrinters();
3252 llvm::InitializeAllAsmParsers();
3253
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003254 CIndexer *CIdxr = new CIndexer();
3255
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 if (excludeDeclarationsFromPCH)
3257 CIdxr->setOnlyLocalDecls();
3258 if (displayDiagnostics)
3259 CIdxr->setDisplayDiagnostics();
3260
3261 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3262 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3263 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3264 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3265 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3266 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3267
3268 return CIdxr;
3269}
3270
3271void clang_disposeIndex(CXIndex CIdx) {
3272 if (CIdx)
3273 delete static_cast<CIndexer *>(CIdx);
3274}
3275
3276void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3277 if (CIdx)
3278 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3279}
3280
3281unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3282 if (CIdx)
3283 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3284 return 0;
3285}
3286
Alex Lorenz08615792017-12-04 21:56:36 +00003287void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3288 const char *Path) {
3289 if (CIdx)
3290 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3291}
3292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293void clang_toggleCrashRecovery(unsigned isEnabled) {
3294 if (isEnabled)
3295 llvm::CrashRecoveryContext::Enable();
3296 else
3297 llvm::CrashRecoveryContext::Disable();
3298}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003299
Guy Benyei11169dd2012-12-18 14:30:41 +00003300CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3301 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003302 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003303 enum CXErrorCode Result =
3304 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003305 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003306 assert((TU && Result == CXError_Success) ||
3307 (!TU && Result != CXError_Success));
3308 return TU;
3309}
3310
3311enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3312 const char *ast_filename,
3313 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003314 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003315 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003316
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003317 if (!CIdx || !ast_filename || !out_TU)
3318 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003319
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003320 LOG_FUNC_SECTION {
3321 *Log << ast_filename;
3322 }
3323
Guy Benyei11169dd2012-12-18 14:30:41 +00003324 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3325 FileSystemOptions FileSystemOpts;
3326
Justin Bognerd512c1e2014-10-15 00:33:06 +00003327 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3328 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003329 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003330 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3331 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003332 FileSystemOpts, /*UseDebugInfo=*/false,
3333 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003334 /*CaptureDiagnostics=*/true,
3335 /*AllowPCHWithCompilerErrors=*/true,
3336 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003337 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003338 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003339}
3340
3341unsigned clang_defaultEditingTranslationUnitOptions() {
3342 return CXTranslationUnit_PrecompiledPreamble |
3343 CXTranslationUnit_CacheCompletionResults;
3344}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003345
Guy Benyei11169dd2012-12-18 14:30:41 +00003346CXTranslationUnit
3347clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3348 const char *source_filename,
3349 int num_command_line_args,
3350 const char * const *command_line_args,
3351 unsigned num_unsaved_files,
3352 struct CXUnsavedFile *unsaved_files) {
3353 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3354 return clang_parseTranslationUnit(CIdx, source_filename,
3355 command_line_args, num_command_line_args,
3356 unsaved_files, num_unsaved_files,
3357 Options);
3358}
3359
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003360static CXErrorCode
3361clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3362 const char *const *command_line_args,
3363 int num_command_line_args,
3364 ArrayRef<CXUnsavedFile> unsaved_files,
3365 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003366 // Set up the initial return values.
3367 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003368 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003369
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003370 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003371 if (!CIdx || !out_TU)
3372 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003373
Guy Benyei11169dd2012-12-18 14:30:41 +00003374 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3375
3376 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3377 setThreadBackgroundPriority();
3378
3379 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003380 bool CreatePreambleOnFirstParse =
3381 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003382 // FIXME: Add a flag for modules.
3383 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003384 = (options & (CXTranslationUnit_Incomplete |
3385 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003386 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003387 = options & CXTranslationUnit_CacheCompletionResults;
3388 bool IncludeBriefCommentsInCodeCompletion
3389 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003390 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3391 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003392 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3393 if (options & CXTranslationUnit_SkipFunctionBodies) {
3394 SkipFunctionBodies =
3395 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3396 ? SkipFunctionBodiesScope::Preamble
3397 : SkipFunctionBodiesScope::PreambleAndMainFile;
3398 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003399
3400 // Configure the diagnostics.
3401 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003402 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003403
Manuel Klimek016c0242016-03-01 10:56:19 +00003404 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003405 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003406
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 // Recover resources if we crash before exiting this function.
3408 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3409 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003410 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003411
Ahmed Charlesb8984322014-03-07 20:03:18 +00003412 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3413 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003414
3415 // Recover resources if we crash before exiting this function.
3416 llvm::CrashRecoveryContextCleanupRegistrar<
3417 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3418
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003419 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003420 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003421 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003422 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003423 }
3424
Ahmed Charlesb8984322014-03-07 20:03:18 +00003425 std::unique_ptr<std::vector<const char *>> Args(
3426 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003427
3428 // Recover resources if we crash before exiting this method.
3429 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3430 ArgsCleanup(Args.get());
3431
3432 // Since the Clang C library is primarily used by batch tools dealing with
3433 // (often very broken) source code, where spell-checking can have a
3434 // significant negative impact on performance (particularly when
3435 // precompiled headers are involved), we disable it by default.
3436 // Only do this if we haven't found a spell-checking-related argument.
3437 bool FoundSpellCheckingArgument = false;
3438 for (int I = 0; I != num_command_line_args; ++I) {
3439 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3440 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3441 FoundSpellCheckingArgument = true;
3442 break;
3443 }
3444 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 Args->insert(Args->end(), command_line_args,
3446 command_line_args + num_command_line_args);
3447
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003448 if (!FoundSpellCheckingArgument)
3449 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3450
Guy Benyei11169dd2012-12-18 14:30:41 +00003451 // The 'source_filename' argument is optional. If the caller does not
3452 // specify it then it is assumed that the source file is specified
3453 // in the actual argument list.
3454 // Put the source file after command_line_args otherwise if '-x' flag is
3455 // present it will be unused.
3456 if (source_filename)
3457 Args->push_back(source_filename);
3458
3459 // Do we need the detailed preprocessing record?
3460 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3461 Args->push_back("-Xclang");
3462 Args->push_back("-detailed-preprocessing-record");
3463 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003464
3465 // Suppress any editor placeholder diagnostics.
3466 Args->push_back("-fallow-editor-placeholders");
3467
Guy Benyei11169dd2012-12-18 14:30:41 +00003468 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003469 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003470 // Unless the user specified that they want the preamble on the first parse
3471 // set it up to be created on the first reparse. This makes the first parse
3472 // faster, trading for a slower (first) reparse.
3473 unsigned PrecompilePreambleAfterNParses =
3474 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003475
Alex Lorenz08615792017-12-04 21:56:36 +00003476 LibclangInvocationReporter InvocationReporter(
3477 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003478 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3479 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003480 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003481 Args->data(), Args->data() + Args->size(),
3482 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003483 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3484 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003485 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3486 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003487 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003488 /*UserFilesAreVolatile=*/true, ForSerialization,
3489 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3490 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003491
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003492 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003493 if (!Unit && !ErrUnit)
3494 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003495
Guy Benyei11169dd2012-12-18 14:30:41 +00003496 if (NumErrors != Diags->getClient()->getNumErrors()) {
3497 // Make sure to check that 'Unit' is non-NULL.
3498 if (CXXIdx->getDisplayDiagnostics())
3499 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3500 }
3501
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003502 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3503 return CXError_ASTReadError;
3504
David Blaikieea4395e2017-01-06 19:49:01 +00003505 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003506 if (CXTranslationUnitImpl *TU = *out_TU) {
3507 TU->ParsingOptions = options;
3508 TU->Arguments.reserve(Args->size());
3509 for (const char *Arg : *Args)
3510 TU->Arguments.push_back(Arg);
3511 return CXError_Success;
3512 }
3513 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003514}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003515
3516CXTranslationUnit
3517clang_parseTranslationUnit(CXIndex CIdx,
3518 const char *source_filename,
3519 const char *const *command_line_args,
3520 int num_command_line_args,
3521 struct CXUnsavedFile *unsaved_files,
3522 unsigned num_unsaved_files,
3523 unsigned options) {
3524 CXTranslationUnit TU;
3525 enum CXErrorCode Result = clang_parseTranslationUnit2(
3526 CIdx, source_filename, command_line_args, num_command_line_args,
3527 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003528 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003529 assert((TU && Result == CXError_Success) ||
3530 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003531 return TU;
3532}
3533
3534enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003535 CXIndex CIdx, const char *source_filename,
3536 const char *const *command_line_args, int num_command_line_args,
3537 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3538 unsigned options, CXTranslationUnit *out_TU) {
3539 SmallVector<const char *, 4> Args;
3540 Args.push_back("clang");
3541 Args.append(command_line_args, command_line_args + num_command_line_args);
3542 return clang_parseTranslationUnit2FullArgv(
3543 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3544 num_unsaved_files, options, out_TU);
3545}
3546
3547enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3548 CXIndex CIdx, const char *source_filename,
3549 const char *const *command_line_args, int num_command_line_args,
3550 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3551 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003552 LOG_FUNC_SECTION {
3553 *Log << source_filename << ": ";
3554 for (int i = 0; i != num_command_line_args; ++i)
3555 *Log << command_line_args[i] << " ";
3556 }
3557
Alp Toker9d85b182014-07-07 01:23:14 +00003558 if (num_unsaved_files && !unsaved_files)
3559 return CXError_InvalidArguments;
3560
Alp Toker5c532982014-07-07 22:42:03 +00003561 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003562 auto ParseTranslationUnitImpl = [=, &result] {
3563 result = clang_parseTranslationUnit_Impl(
3564 CIdx, source_filename, command_line_args, num_command_line_args,
3565 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3566 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003567
Guy Benyei11169dd2012-12-18 14:30:41 +00003568 llvm::CrashRecoveryContext CRC;
3569
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003570 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003571 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3572 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3573 fprintf(stderr, " 'command_line_args' : [");
3574 for (int i = 0; i != num_command_line_args; ++i) {
3575 if (i)
3576 fprintf(stderr, ", ");
3577 fprintf(stderr, "'%s'", command_line_args[i]);
3578 }
3579 fprintf(stderr, "],\n");
3580 fprintf(stderr, " 'unsaved_files' : [");
3581 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3582 if (i)
3583 fprintf(stderr, ", ");
3584 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3585 unsaved_files[i].Length);
3586 }
3587 fprintf(stderr, "],\n");
3588 fprintf(stderr, " 'options' : %d,\n", options);
3589 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003590
3591 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003592 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003593 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003594 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 }
Alp Toker5c532982014-07-07 22:42:03 +00003596
3597 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003598}
3599
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003600CXString clang_Type_getObjCEncoding(CXType CT) {
3601 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3602 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3603 std::string encoding;
3604 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3605 encoding);
3606
3607 return cxstring::createDup(encoding);
3608}
3609
3610static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3611 if (C.kind == CXCursor_MacroDefinition) {
3612 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3613 return MDR->getName();
3614 } else if (C.kind == CXCursor_MacroExpansion) {
3615 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3616 return ME.getName();
3617 }
3618 return nullptr;
3619}
3620
3621unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3622 const IdentifierInfo *II = getMacroIdentifier(C);
3623 if (!II) {
3624 return false;
3625 }
3626 ASTUnit *ASTU = getCursorASTUnit(C);
3627 Preprocessor &PP = ASTU->getPreprocessor();
3628 if (const MacroInfo *MI = PP.getMacroInfo(II))
3629 return MI->isFunctionLike();
3630 return false;
3631}
3632
3633unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3634 const IdentifierInfo *II = getMacroIdentifier(C);
3635 if (!II) {
3636 return false;
3637 }
3638 ASTUnit *ASTU = getCursorASTUnit(C);
3639 Preprocessor &PP = ASTU->getPreprocessor();
3640 if (const MacroInfo *MI = PP.getMacroInfo(II))
3641 return MI->isBuiltinMacro();
3642 return false;
3643}
3644
3645unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3646 const Decl *D = getCursorDecl(C);
3647 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3648 if (!FD) {
3649 return false;
3650 }
3651 return FD->isInlined();
3652}
3653
3654static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3655 if (callExpr->getNumArgs() != 1) {
3656 return nullptr;
3657 }
3658
3659 StringLiteral *S = nullptr;
3660 auto *arg = callExpr->getArg(0);
3661 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3662 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3663 auto *subExpr = I->getSubExprAsWritten();
3664
3665 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3666 return nullptr;
3667 }
3668
3669 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3670 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3671 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3672 } else {
3673 return nullptr;
3674 }
3675 return S;
3676}
3677
David Blaikie59272572016-04-13 18:23:33 +00003678struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003679 CXEvalResultKind EvalType;
3680 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003681 unsigned long long unsignedVal;
3682 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003683 double floatVal;
3684 char *stringVal;
3685 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003686 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003687 ~ExprEvalResult() {
3688 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3689 EvalType != CXEval_Int) {
3690 delete EvalData.stringVal;
3691 }
3692 }
3693};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003694
3695void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003696 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003697}
3698
3699CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3700 if (!E) {
3701 return CXEval_UnExposed;
3702 }
3703 return ((ExprEvalResult *)E)->EvalType;
3704}
3705
3706int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003707 return clang_EvalResult_getAsLongLong(E);
3708}
3709
3710long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003711 if (!E) {
3712 return 0;
3713 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003714 ExprEvalResult *Result = (ExprEvalResult*)E;
3715 if (Result->IsUnsignedInt)
3716 return Result->EvalData.unsignedVal;
3717 return Result->EvalData.intVal;
3718}
3719
3720unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3721 return ((ExprEvalResult *)E)->IsUnsignedInt;
3722}
3723
3724unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3725 if (!E) {
3726 return 0;
3727 }
3728
3729 ExprEvalResult *Result = (ExprEvalResult*)E;
3730 if (Result->IsUnsignedInt)
3731 return Result->EvalData.unsignedVal;
3732 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003733}
3734
3735double clang_EvalResult_getAsDouble(CXEvalResult E) {
3736 if (!E) {
3737 return 0;
3738 }
3739 return ((ExprEvalResult *)E)->EvalData.floatVal;
3740}
3741
3742const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3743 if (!E) {
3744 return nullptr;
3745 }
3746 return ((ExprEvalResult *)E)->EvalData.stringVal;
3747}
3748
3749static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3750 Expr::EvalResult ER;
3751 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003752 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003753 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003754
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003755 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003756 if (!expr->EvaluateAsRValue(ER, ctx))
3757 return nullptr;
3758
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003759 QualType rettype;
3760 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003761 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003762 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003763 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003764
David Blaikiebbc00882016-04-13 18:36:19 +00003765 if (ER.Val.isInt()) {
3766 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003767
3768 auto& val = ER.Val.getInt();
3769 if (val.isUnsigned()) {
3770 result->IsUnsignedInt = true;
3771 result->EvalData.unsignedVal = val.getZExtValue();
3772 } else {
3773 result->EvalData.intVal = val.getExtValue();
3774 }
3775
David Blaikiebbc00882016-04-13 18:36:19 +00003776 return result.release();
3777 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003778
David Blaikiebbc00882016-04-13 18:36:19 +00003779 if (ER.Val.isFloat()) {
3780 llvm::SmallVector<char, 100> Buffer;
3781 ER.Val.getFloat().toString(Buffer);
3782 std::string floatStr(Buffer.data(), Buffer.size());
3783 result->EvalType = CXEval_Float;
3784 bool ignored;
3785 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003786 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003787 llvm::APFloat::rmNearestTiesToEven, &ignored);
3788 result->EvalData.floatVal = apFloat.convertToDouble();
3789 return result.release();
3790 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003791
David Blaikiebbc00882016-04-13 18:36:19 +00003792 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3793 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3794 auto *subExpr = I->getSubExprAsWritten();
3795 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3796 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003797 const StringLiteral *StrE = nullptr;
3798 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003799 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003800
3801 if (ObjCExpr) {
3802 StrE = ObjCExpr->getString();
3803 result->EvalType = CXEval_ObjCStrLiteral;
3804 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003805 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003806 result->EvalType = CXEval_StrLiteral;
3807 }
3808
3809 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003810 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003811 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3812 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003813 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003814 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003815 }
3816 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3817 expr->getStmtClass() == Stmt::StringLiteralClass) {
3818 const StringLiteral *StrE = nullptr;
3819 const ObjCStringLiteral *ObjCExpr;
3820 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003821
David Blaikiebbc00882016-04-13 18:36:19 +00003822 if (ObjCExpr) {
3823 StrE = ObjCExpr->getString();
3824 result->EvalType = CXEval_ObjCStrLiteral;
3825 } else {
3826 StrE = cast<StringLiteral>(expr);
3827 result->EvalType = CXEval_StrLiteral;
3828 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003829
David Blaikiebbc00882016-04-13 18:36:19 +00003830 std::string strRef(StrE->getString().str());
3831 result->EvalData.stringVal = new char[strRef.size() + 1];
3832 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3833 result->EvalData.stringVal[strRef.size()] = '\0';
3834 return result.release();
3835 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003836
David Blaikiebbc00882016-04-13 18:36:19 +00003837 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3838 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003839
David Blaikiebbc00882016-04-13 18:36:19 +00003840 rettype = CC->getType();
3841 if (rettype.getAsString() == "CFStringRef" &&
3842 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003843
David Blaikiebbc00882016-04-13 18:36:19 +00003844 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3845 StringLiteral *S = getCFSTR_value(callExpr);
3846 if (S) {
3847 std::string strLiteral(S->getString().str());
3848 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003849
David Blaikiebbc00882016-04-13 18:36:19 +00003850 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3851 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3852 strLiteral.size());
3853 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003854 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003855 }
3856 }
3857
David Blaikiebbc00882016-04-13 18:36:19 +00003858 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3859 callExpr = static_cast<CallExpr *>(expr);
3860 rettype = callExpr->getCallReturnType(ctx);
3861
3862 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3863 return nullptr;
3864
3865 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3866 if (callExpr->getNumArgs() == 1 &&
3867 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3868 return nullptr;
3869 } else if (rettype.getAsString() == "CFStringRef") {
3870
3871 StringLiteral *S = getCFSTR_value(callExpr);
3872 if (S) {
3873 std::string strLiteral(S->getString().str());
3874 result->EvalType = CXEval_CFStr;
3875 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3876 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3877 strLiteral.size());
3878 result->EvalData.stringVal[strLiteral.size()] = '\0';
3879 return result.release();
3880 }
3881 }
3882 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3883 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3884 ValueDecl *V = D->getDecl();
3885 if (V->getKind() == Decl::Function) {
3886 std::string strName = V->getNameAsString();
3887 result->EvalType = CXEval_Other;
3888 result->EvalData.stringVal = new char[strName.size() + 1];
3889 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3890 result->EvalData.stringVal[strName.size()] = '\0';
3891 return result.release();
3892 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003893 }
3894
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003895 return nullptr;
3896}
3897
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003898CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003899 const Decl *D = getCursorDecl(C);
3900 if (D) {
3901 const Expr *expr = nullptr;
3902 if (auto *Var = dyn_cast<VarDecl>(D)) {
3903 expr = Var->getInit();
3904 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3905 expr = Field->getInClassInitializer();
3906 }
3907 if (expr)
3908 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3909 evaluateExpr(const_cast<Expr *>(expr), C)));
3910 return nullptr;
3911 }
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003912
3913 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3914 if (compoundStmt) {
3915 Expr *expr = nullptr;
3916 for (auto *bodyIterator : compoundStmt->body()) {
3917 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3918 break;
3919 }
3920 }
3921 if (expr)
3922 return const_cast<CXEvalResult>(
3923 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
3924 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003925 return nullptr;
3926}
3927
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003928unsigned clang_Cursor_hasAttrs(CXCursor C) {
3929 const Decl *D = getCursorDecl(C);
3930 if (!D) {
3931 return 0;
3932 }
3933
3934 if (D->hasAttrs()) {
3935 return 1;
3936 }
3937
3938 return 0;
3939}
Guy Benyei11169dd2012-12-18 14:30:41 +00003940unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3941 return CXSaveTranslationUnit_None;
3942}
3943
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003944static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3945 const char *FileName,
3946 unsigned options) {
3947 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003948 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3949 setThreadBackgroundPriority();
3950
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003951 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3952 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003953}
3954
3955int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3956 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003957 LOG_FUNC_SECTION {
3958 *Log << TU << ' ' << FileName;
3959 }
3960
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003961 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003962 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003964 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003965
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003966 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3968 if (!CXXUnit->hasSema())
3969 return CXSaveError_InvalidTU;
3970
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003971 CXSaveError result;
3972 auto SaveTranslationUnitImpl = [=, &result]() {
3973 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3974 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003975
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003976 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003977 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003978
3979 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3980 PrintLibclangResourceUsage(TU);
3981
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003982 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003983 }
3984
3985 // We have an AST that has invalid nodes due to compiler errors.
3986 // Use a crash recovery thread for protection.
3987
3988 llvm::CrashRecoveryContext CRC;
3989
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003990 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3992 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3993 fprintf(stderr, " 'options' : %d,\n", options);
3994 fprintf(stderr, "}\n");
3995
3996 return CXSaveError_Unknown;
3997
3998 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3999 PrintLibclangResourceUsage(TU);
4000 }
4001
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004002 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004003}
4004
4005void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4006 if (CTUnit) {
4007 // If the translation unit has been marked as unsafe to free, just discard
4008 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004009 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4010 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 return;
4012
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004013 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004014 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4016 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004017 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 delete CTUnit;
4019 }
4020}
4021
Erik Verbruggen346066b2017-05-30 14:25:54 +00004022unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4023 if (CTUnit) {
4024 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4025
4026 if (Unit && Unit->isUnsafeToFree())
4027 return false;
4028
4029 Unit->ResetForParse();
4030 return true;
4031 }
4032
4033 return false;
4034}
4035
Guy Benyei11169dd2012-12-18 14:30:41 +00004036unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4037 return CXReparse_None;
4038}
4039
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004040static CXErrorCode
4041clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4042 ArrayRef<CXUnsavedFile> unsaved_files,
4043 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004044 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004045 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004046 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004047 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004048 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004049
4050 // Reset the associated diagnostics.
4051 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004052 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004053
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004054 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004055 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4056 setThreadBackgroundPriority();
4057
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004058 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004060
4061 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4062 new std::vector<ASTUnit::RemappedFile>());
4063
Guy Benyei11169dd2012-12-18 14:30:41 +00004064 // Recover resources if we crash before exiting this function.
4065 llvm::CrashRecoveryContextCleanupRegistrar<
4066 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004067
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004068 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004069 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004070 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004071 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004073
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004074 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4075 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004076 return CXError_Success;
4077 if (isASTReadError(CXXUnit))
4078 return CXError_ASTReadError;
4079 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004080}
4081
4082int clang_reparseTranslationUnit(CXTranslationUnit TU,
4083 unsigned num_unsaved_files,
4084 struct CXUnsavedFile *unsaved_files,
4085 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004086 LOG_FUNC_SECTION {
4087 *Log << TU;
4088 }
4089
Alp Toker9d85b182014-07-07 01:23:14 +00004090 if (num_unsaved_files && !unsaved_files)
4091 return CXError_InvalidArguments;
4092
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004093 CXErrorCode result;
4094 auto ReparseTranslationUnitImpl = [=, &result]() {
4095 result = clang_reparseTranslationUnit_Impl(
4096 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4097 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004098
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 llvm::CrashRecoveryContext CRC;
4100
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004101 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004102 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004103 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004104 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4106 PrintLibclangResourceUsage(TU);
4107
Alp Toker5c532982014-07-07 22:42:03 +00004108 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004109}
4110
4111
4112CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004113 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004114 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004115 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004116 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004117
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004118 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004119 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004120}
4121
4122CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004123 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004124 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004125 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004126 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004127
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004128 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4130}
4131
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004132CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4133 if (isNotUsableTU(CTUnit)) {
4134 LOG_BAD_TU(CTUnit);
4135 return nullptr;
4136 }
4137
4138 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4139 impl->TranslationUnit = CTUnit;
4140 return impl;
4141}
4142
4143CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4144 if (!TargetInfo)
4145 return cxstring::createEmpty();
4146
4147 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4148 assert(!isNotUsableTU(CTUnit) &&
4149 "Unexpected unusable translation unit in TargetInfo");
4150
4151 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4152 std::string Triple =
4153 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4154 return cxstring::createDup(Triple);
4155}
4156
4157int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4158 if (!TargetInfo)
4159 return -1;
4160
4161 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4162 assert(!isNotUsableTU(CTUnit) &&
4163 "Unexpected unusable translation unit in TargetInfo");
4164
4165 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4166 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4167}
4168
4169void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4170 if (!TargetInfo)
4171 return;
4172
4173 delete TargetInfo;
4174}
4175
Guy Benyei11169dd2012-12-18 14:30:41 +00004176//===----------------------------------------------------------------------===//
4177// CXFile Operations.
4178//===----------------------------------------------------------------------===//
4179
Guy Benyei11169dd2012-12-18 14:30:41 +00004180CXString clang_getFileName(CXFile SFile) {
4181 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004182 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004183
4184 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004185 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004186}
4187
4188time_t clang_getFileTime(CXFile SFile) {
4189 if (!SFile)
4190 return 0;
4191
4192 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4193 return FEnt->getModificationTime();
4194}
4195
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004196CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004197 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004198 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004199 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004200 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004201
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004202 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004203
4204 FileManager &FMgr = CXXUnit->getFileManager();
4205 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4206}
4207
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004208const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4209 size_t *size) {
4210 if (isNotUsableTU(TU)) {
4211 LOG_BAD_TU(TU);
4212 return nullptr;
4213 }
4214
4215 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4216 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4217 bool Invalid = true;
4218 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4219 if (Invalid) {
4220 if (size)
4221 *size = 0;
4222 return nullptr;
4223 }
4224 if (size)
4225 *size = buf->getBufferSize();
4226 return buf->getBufferStart();
4227}
4228
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004229unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4230 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004231 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004232 LOG_BAD_TU(TU);
4233 return 0;
4234 }
4235
4236 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004237 return 0;
4238
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004239 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 FileEntry *FEnt = static_cast<FileEntry *>(file);
4241 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4242 .isFileMultipleIncludeGuarded(FEnt);
4243}
4244
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004245int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4246 if (!file || !outID)
4247 return 1;
4248
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004249 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004250 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4251 outID->data[0] = ID.getDevice();
4252 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004253 outID->data[2] = FEnt->getModificationTime();
4254 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004255}
4256
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004257int clang_File_isEqual(CXFile file1, CXFile file2) {
4258 if (file1 == file2)
4259 return true;
4260
4261 if (!file1 || !file2)
4262 return false;
4263
4264 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4265 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4266 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4267}
4268
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004269CXString clang_File_tryGetRealPathName(CXFile SFile) {
4270 if (!SFile)
4271 return cxstring::createNull();
4272
4273 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4274 return cxstring::createRef(FEnt->tryGetRealPathName());
4275}
4276
Guy Benyei11169dd2012-12-18 14:30:41 +00004277//===----------------------------------------------------------------------===//
4278// CXCursor Operations.
4279//===----------------------------------------------------------------------===//
4280
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004281static const Decl *getDeclFromExpr(const Stmt *E) {
4282 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 return getDeclFromExpr(CE->getSubExpr());
4284
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004285 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004287 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004289 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004291 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 if (PRE->isExplicitProperty())
4293 return PRE->getExplicitProperty();
4294 // It could be messaging both getter and setter as in:
4295 // ++myobj.myprop;
4296 // in which case prefer to associate the setter since it is less obvious
4297 // from inspecting the source that the setter is going to get called.
4298 if (PRE->isMessagingSetter())
4299 return PRE->getImplicitPropertySetter();
4300 return PRE->getImplicitPropertyGetter();
4301 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004302 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004304 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 if (Expr *Src = OVE->getSourceExpr())
4306 return getDeclFromExpr(Src);
4307
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004308 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004310 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 if (!CE->isElidable())
4312 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004313 if (const CXXInheritedCtorInitExpr *CE =
4314 dyn_cast<CXXInheritedCtorInitExpr>(E))
4315 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004316 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 return OME->getMethodDecl();
4318
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004319 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004321 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4323 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004324 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004325 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4326 isa<ParmVarDecl>(SizeOfPack->getPack()))
4327 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004328
4329 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004330}
4331
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004332static SourceLocation getLocationFromExpr(const Expr *E) {
4333 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 return getLocationFromExpr(CE->getSubExpr());
4335
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004336 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004338 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004340 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004342 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004344 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004346 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004348
4349 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004350}
4351
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004352extern "C" {
4353
Guy Benyei11169dd2012-12-18 14:30:41 +00004354unsigned clang_visitChildren(CXCursor parent,
4355 CXCursorVisitor visitor,
4356 CXClientData client_data) {
4357 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4358 /*VisitPreprocessorLast=*/false);
4359 return CursorVis.VisitChildren(parent);
4360}
4361
4362#ifndef __has_feature
4363#define __has_feature(x) 0
4364#endif
4365#if __has_feature(blocks)
4366typedef enum CXChildVisitResult
4367 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4368
4369static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4370 CXClientData client_data) {
4371 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4372 return block(cursor, parent);
4373}
4374#else
4375// If we are compiled with a compiler that doesn't have native blocks support,
4376// define and call the block manually, so the
4377typedef struct _CXChildVisitResult
4378{
4379 void *isa;
4380 int flags;
4381 int reserved;
4382 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4383 CXCursor);
4384} *CXCursorVisitorBlock;
4385
4386static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4387 CXClientData client_data) {
4388 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4389 return block->invoke(block, cursor, parent);
4390}
4391#endif
4392
4393
4394unsigned clang_visitChildrenWithBlock(CXCursor parent,
4395 CXCursorVisitorBlock block) {
4396 return clang_visitChildren(parent, visitWithBlock, block);
4397}
4398
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004399static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004401 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004402
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004403 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004405 if (const ObjCPropertyImplDecl *PropImpl =
4406 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004408 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004409
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004410 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004412 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004413
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004414 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 }
4416
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004417 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004418 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004419
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004420 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4422 // and returns different names. NamedDecl returns the class name and
4423 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004424 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004425
4426 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004427 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004428
4429 SmallString<1024> S;
4430 llvm::raw_svector_ostream os(S);
4431 ND->printName(os);
4432
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004433 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004434}
4435
4436CXString clang_getCursorSpelling(CXCursor C) {
4437 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004438 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004439
4440 if (clang_isReference(C.kind)) {
4441 switch (C.kind) {
4442 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004443 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004444 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 }
4446 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004447 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004448 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 }
4450 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004451 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004453 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 }
4455 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004456 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004457 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 }
4459 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004460 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 assert(Type && "Missing type decl");
4462
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004463 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 getAsString());
4465 }
4466 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004467 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 assert(Template && "Missing template decl");
4469
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004470 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 }
4472
4473 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004474 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 assert(NS && "Missing namespace decl");
4476
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004477 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 }
4479
4480 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004481 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 assert(Field && "Missing member decl");
4483
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004484 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 }
4486
4487 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004488 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 assert(Label && "Missing label");
4490
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004491 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 }
4493
4494 case CXCursor_OverloadedDeclRef: {
4495 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004496 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4497 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004498 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004499 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004501 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004502 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 OverloadedTemplateStorage *Ovl
4504 = Storage.get<OverloadedTemplateStorage*>();
4505 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004506 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004507 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 }
4509
4510 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004511 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 assert(Var && "Missing variable decl");
4513
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004514 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 }
4516
4517 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004518 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 }
4520 }
4521
4522 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004523 const Expr *E = getCursorExpr(C);
4524
4525 if (C.kind == CXCursor_ObjCStringLiteral ||
4526 C.kind == CXCursor_StringLiteral) {
4527 const StringLiteral *SLit;
4528 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4529 SLit = OSL->getString();
4530 } else {
4531 SLit = cast<StringLiteral>(E);
4532 }
4533 SmallString<256> Buf;
4534 llvm::raw_svector_ostream OS(Buf);
4535 SLit->outputString(OS);
4536 return cxstring::createDup(OS.str());
4537 }
4538
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004539 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 if (D)
4541 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004542 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 }
4544
4545 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004546 const Stmt *S = getCursorStmt(C);
4547 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004548 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004549
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004550 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 }
4552
4553 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004554 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 ->getNameStart());
4556
4557 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004558 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 ->getNameStart());
4560
4561 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004562 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004563
4564 if (clang_isDeclaration(C.kind))
4565 return getDeclSpelling(getCursorDecl(C));
4566
4567 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004568 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004569 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 }
4571
4572 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004573 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004574 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 }
4576
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004577 if (C.kind == CXCursor_PackedAttr) {
4578 return cxstring::createRef("packed");
4579 }
4580
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004581 if (C.kind == CXCursor_VisibilityAttr) {
4582 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4583 switch (AA->getVisibility()) {
4584 case VisibilityAttr::VisibilityType::Default:
4585 return cxstring::createRef("default");
4586 case VisibilityAttr::VisibilityType::Hidden:
4587 return cxstring::createRef("hidden");
4588 case VisibilityAttr::VisibilityType::Protected:
4589 return cxstring::createRef("protected");
4590 }
4591 llvm_unreachable("unknown visibility type");
4592 }
4593
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004594 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004595}
4596
4597CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4598 unsigned pieceIndex,
4599 unsigned options) {
4600 if (clang_Cursor_isNull(C))
4601 return clang_getNullRange();
4602
4603 ASTContext &Ctx = getCursorContext(C);
4604
4605 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004606 const Stmt *S = getCursorStmt(C);
4607 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 if (pieceIndex > 0)
4609 return clang_getNullRange();
4610 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4611 }
4612
4613 return clang_getNullRange();
4614 }
4615
4616 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004617 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4619 if (pieceIndex >= ME->getNumSelectorLocs())
4620 return clang_getNullRange();
4621 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4622 }
4623 }
4624
4625 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4626 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004627 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4629 if (pieceIndex >= MD->getNumSelectorLocs())
4630 return clang_getNullRange();
4631 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4632 }
4633 }
4634
4635 if (C.kind == CXCursor_ObjCCategoryDecl ||
4636 C.kind == CXCursor_ObjCCategoryImplDecl) {
4637 if (pieceIndex > 0)
4638 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004639 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4641 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004642 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4644 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4645 }
4646
4647 if (C.kind == CXCursor_ModuleImportDecl) {
4648 if (pieceIndex > 0)
4649 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004650 if (const ImportDecl *ImportD =
4651 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4653 if (!Locs.empty())
4654 return cxloc::translateSourceRange(Ctx,
4655 SourceRange(Locs.front(), Locs.back()));
4656 }
4657 return clang_getNullRange();
4658 }
4659
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004660 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004661 C.kind == CXCursor_ConversionFunction ||
4662 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004663 if (pieceIndex > 0)
4664 return clang_getNullRange();
4665 if (const FunctionDecl *FD =
4666 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4667 DeclarationNameInfo FunctionName = FD->getNameInfo();
4668 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4669 }
4670 return clang_getNullRange();
4671 }
4672
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 // FIXME: A CXCursor_InclusionDirective should give the location of the
4674 // filename, but we don't keep track of this.
4675
4676 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4677 // but we don't keep track of this.
4678
4679 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4680 // but we don't keep track of this.
4681
4682 // Default handling, give the location of the cursor.
4683
4684 if (pieceIndex > 0)
4685 return clang_getNullRange();
4686
4687 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4688 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4689 return cxloc::translateSourceRange(Ctx, Loc);
4690}
4691
Eli Bendersky44a206f2014-07-31 18:04:56 +00004692CXString clang_Cursor_getMangling(CXCursor C) {
4693 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4694 return cxstring::createEmpty();
4695
Eli Bendersky44a206f2014-07-31 18:04:56 +00004696 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004697 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004698 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4699 return cxstring::createEmpty();
4700
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004701 ASTContext &Ctx = D->getASTContext();
4702 index::CodegenNameGenerator CGNameGen(Ctx);
4703 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004704}
4705
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004706CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4707 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4708 return nullptr;
4709
4710 const Decl *D = getCursorDecl(C);
4711 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4712 return nullptr;
4713
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004714 ASTContext &Ctx = D->getASTContext();
4715 index::CodegenNameGenerator CGNameGen(Ctx);
4716 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004717 return cxstring::createSet(Manglings);
4718}
4719
Dave Lee1a532c92017-09-22 16:58:57 +00004720CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4721 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4722 return nullptr;
4723
4724 const Decl *D = getCursorDecl(C);
4725 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4726 return nullptr;
4727
4728 ASTContext &Ctx = D->getASTContext();
4729 index::CodegenNameGenerator CGNameGen(Ctx);
4730 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4731 return cxstring::createSet(Manglings);
4732}
4733
Jonathan Coe45ef5032018-01-16 10:19:56 +00004734CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4735 if (clang_Cursor_isNull(C))
4736 return 0;
4737 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4738}
4739
4740void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4741 if (Policy)
4742 delete static_cast<PrintingPolicy *>(Policy);
4743}
4744
4745unsigned
4746clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4747 enum CXPrintingPolicyProperty Property) {
4748 if (!Policy)
4749 return 0;
4750
4751 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4752 switch (Property) {
4753 case CXPrintingPolicy_Indentation:
4754 return P->Indentation;
4755 case CXPrintingPolicy_SuppressSpecifiers:
4756 return P->SuppressSpecifiers;
4757 case CXPrintingPolicy_SuppressTagKeyword:
4758 return P->SuppressTagKeyword;
4759 case CXPrintingPolicy_IncludeTagDefinition:
4760 return P->IncludeTagDefinition;
4761 case CXPrintingPolicy_SuppressScope:
4762 return P->SuppressScope;
4763 case CXPrintingPolicy_SuppressUnwrittenScope:
4764 return P->SuppressUnwrittenScope;
4765 case CXPrintingPolicy_SuppressInitializers:
4766 return P->SuppressInitializers;
4767 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4768 return P->ConstantArraySizeAsWritten;
4769 case CXPrintingPolicy_AnonymousTagLocations:
4770 return P->AnonymousTagLocations;
4771 case CXPrintingPolicy_SuppressStrongLifetime:
4772 return P->SuppressStrongLifetime;
4773 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4774 return P->SuppressLifetimeQualifiers;
4775 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4776 return P->SuppressTemplateArgsInCXXConstructors;
4777 case CXPrintingPolicy_Bool:
4778 return P->Bool;
4779 case CXPrintingPolicy_Restrict:
4780 return P->Restrict;
4781 case CXPrintingPolicy_Alignof:
4782 return P->Alignof;
4783 case CXPrintingPolicy_UnderscoreAlignof:
4784 return P->UnderscoreAlignof;
4785 case CXPrintingPolicy_UseVoidForZeroParams:
4786 return P->UseVoidForZeroParams;
4787 case CXPrintingPolicy_TerseOutput:
4788 return P->TerseOutput;
4789 case CXPrintingPolicy_PolishForDeclaration:
4790 return P->PolishForDeclaration;
4791 case CXPrintingPolicy_Half:
4792 return P->Half;
4793 case CXPrintingPolicy_MSWChar:
4794 return P->MSWChar;
4795 case CXPrintingPolicy_IncludeNewlines:
4796 return P->IncludeNewlines;
4797 case CXPrintingPolicy_MSVCFormatting:
4798 return P->MSVCFormatting;
4799 case CXPrintingPolicy_ConstantsAsWritten:
4800 return P->ConstantsAsWritten;
4801 case CXPrintingPolicy_SuppressImplicitBase:
4802 return P->SuppressImplicitBase;
4803 case CXPrintingPolicy_FullyQualifiedName:
4804 return P->FullyQualifiedName;
4805 }
4806
4807 assert(false && "Invalid CXPrintingPolicyProperty");
4808 return 0;
4809}
4810
4811void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4812 enum CXPrintingPolicyProperty Property,
4813 unsigned Value) {
4814 if (!Policy)
4815 return;
4816
4817 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4818 switch (Property) {
4819 case CXPrintingPolicy_Indentation:
4820 P->Indentation = Value;
4821 return;
4822 case CXPrintingPolicy_SuppressSpecifiers:
4823 P->SuppressSpecifiers = Value;
4824 return;
4825 case CXPrintingPolicy_SuppressTagKeyword:
4826 P->SuppressTagKeyword = Value;
4827 return;
4828 case CXPrintingPolicy_IncludeTagDefinition:
4829 P->IncludeTagDefinition = Value;
4830 return;
4831 case CXPrintingPolicy_SuppressScope:
4832 P->SuppressScope = Value;
4833 return;
4834 case CXPrintingPolicy_SuppressUnwrittenScope:
4835 P->SuppressUnwrittenScope = Value;
4836 return;
4837 case CXPrintingPolicy_SuppressInitializers:
4838 P->SuppressInitializers = Value;
4839 return;
4840 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4841 P->ConstantArraySizeAsWritten = Value;
4842 return;
4843 case CXPrintingPolicy_AnonymousTagLocations:
4844 P->AnonymousTagLocations = Value;
4845 return;
4846 case CXPrintingPolicy_SuppressStrongLifetime:
4847 P->SuppressStrongLifetime = Value;
4848 return;
4849 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4850 P->SuppressLifetimeQualifiers = Value;
4851 return;
4852 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4853 P->SuppressTemplateArgsInCXXConstructors = Value;
4854 return;
4855 case CXPrintingPolicy_Bool:
4856 P->Bool = Value;
4857 return;
4858 case CXPrintingPolicy_Restrict:
4859 P->Restrict = Value;
4860 return;
4861 case CXPrintingPolicy_Alignof:
4862 P->Alignof = Value;
4863 return;
4864 case CXPrintingPolicy_UnderscoreAlignof:
4865 P->UnderscoreAlignof = Value;
4866 return;
4867 case CXPrintingPolicy_UseVoidForZeroParams:
4868 P->UseVoidForZeroParams = Value;
4869 return;
4870 case CXPrintingPolicy_TerseOutput:
4871 P->TerseOutput = Value;
4872 return;
4873 case CXPrintingPolicy_PolishForDeclaration:
4874 P->PolishForDeclaration = Value;
4875 return;
4876 case CXPrintingPolicy_Half:
4877 P->Half = Value;
4878 return;
4879 case CXPrintingPolicy_MSWChar:
4880 P->MSWChar = Value;
4881 return;
4882 case CXPrintingPolicy_IncludeNewlines:
4883 P->IncludeNewlines = Value;
4884 return;
4885 case CXPrintingPolicy_MSVCFormatting:
4886 P->MSVCFormatting = Value;
4887 return;
4888 case CXPrintingPolicy_ConstantsAsWritten:
4889 P->ConstantsAsWritten = Value;
4890 return;
4891 case CXPrintingPolicy_SuppressImplicitBase:
4892 P->SuppressImplicitBase = Value;
4893 return;
4894 case CXPrintingPolicy_FullyQualifiedName:
4895 P->FullyQualifiedName = Value;
4896 return;
4897 }
4898
4899 assert(false && "Invalid CXPrintingPolicyProperty");
4900}
4901
4902CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4903 if (clang_Cursor_isNull(C))
4904 return cxstring::createEmpty();
4905
4906 if (clang_isDeclaration(C.kind)) {
4907 const Decl *D = getCursorDecl(C);
4908 if (!D)
4909 return cxstring::createEmpty();
4910
4911 SmallString<128> Str;
4912 llvm::raw_svector_ostream OS(Str);
4913 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4914 D->print(OS, UserPolicy ? *UserPolicy
4915 : getCursorContext(C).getPrintingPolicy());
4916
4917 return cxstring::createDup(OS.str());
4918 }
4919
4920 return cxstring::createEmpty();
4921}
4922
Guy Benyei11169dd2012-12-18 14:30:41 +00004923CXString clang_getCursorDisplayName(CXCursor C) {
4924 if (!clang_isDeclaration(C.kind))
4925 return clang_getCursorSpelling(C);
4926
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004927 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004929 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004930
4931 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004932 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 D = FunTmpl->getTemplatedDecl();
4934
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004935 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 SmallString<64> Str;
4937 llvm::raw_svector_ostream OS(Str);
4938 OS << *Function;
4939 if (Function->getPrimaryTemplate())
4940 OS << "<>";
4941 OS << "(";
4942 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4943 if (I)
4944 OS << ", ";
4945 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4946 }
4947
4948 if (Function->isVariadic()) {
4949 if (Function->getNumParams())
4950 OS << ", ";
4951 OS << "...";
4952 }
4953 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004954 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 }
4956
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004957 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004958 SmallString<64> Str;
4959 llvm::raw_svector_ostream OS(Str);
4960 OS << *ClassTemplate;
4961 OS << "<";
4962 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4963 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4964 if (I)
4965 OS << ", ";
4966
4967 NamedDecl *Param = Params->getParam(I);
4968 if (Param->getIdentifier()) {
4969 OS << Param->getIdentifier()->getName();
4970 continue;
4971 }
4972
4973 // There is no parameter name, which makes this tricky. Try to come up
4974 // with something useful that isn't too long.
4975 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4976 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4977 else if (NonTypeTemplateParmDecl *NTTP
4978 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4979 OS << NTTP->getType().getAsString(Policy);
4980 else
4981 OS << "template<...> class";
4982 }
4983
4984 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004985 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 }
4987
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004988 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004989 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4990 // If the type was explicitly written, use that.
4991 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004992 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004993
Benjamin Kramer9170e912013-02-22 15:46:01 +00004994 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 llvm::raw_svector_ostream OS(Str);
4996 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00004997 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
4998 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004999 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005000 }
5001
5002 return clang_getCursorSpelling(C);
5003}
5004
5005CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5006 switch (Kind) {
5007 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005008 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005010 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005012 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005014 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005016 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005018 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005020 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005022 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005024 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005026 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005028 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005030 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005032 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005034 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005036 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005038 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005040 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005042 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005071 case CXCursor_FixedPointLiteral:
5072 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005087 case CXCursor_OMPArraySectionExpr:
5088 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005094 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005139 case CXCursor_ObjCAvailabilityCheckExpr:
5140 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005141 case CXCursor_ObjCSelfExpr:
5142 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005231 case CXCursor_SEHLeaveStmt:
5232 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005261 case CXCursor_PackedAttr:
5262 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005263 case CXCursor_PureAttr:
5264 return cxstring::createRef("attribute(pure)");
5265 case CXCursor_ConstAttr:
5266 return cxstring::createRef("attribute(const)");
5267 case CXCursor_NoDuplicateAttr:
5268 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005269 case CXCursor_CUDAConstantAttr:
5270 return cxstring::createRef("attribute(constant)");
5271 case CXCursor_CUDADeviceAttr:
5272 return cxstring::createRef("attribute(device)");
5273 case CXCursor_CUDAGlobalAttr:
5274 return cxstring::createRef("attribute(global)");
5275 case CXCursor_CUDAHostAttr:
5276 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005277 case CXCursor_CUDASharedAttr:
5278 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005279 case CXCursor_VisibilityAttr:
5280 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005281 case CXCursor_DLLExport:
5282 return cxstring::createRef("attribute(dllexport)");
5283 case CXCursor_DLLImport:
5284 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005285 case CXCursor_NSReturnsRetained:
5286 return cxstring::createRef("attribute(ns_returns_retained)");
5287 case CXCursor_NSReturnsNotRetained:
5288 return cxstring::createRef("attribute(ns_returns_not_retained)");
5289 case CXCursor_NSReturnsAutoreleased:
5290 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5291 case CXCursor_NSConsumesSelf:
5292 return cxstring::createRef("attribute(ns_consumes_self)");
5293 case CXCursor_NSConsumed:
5294 return cxstring::createRef("attribute(ns_consumed)");
5295 case CXCursor_ObjCException:
5296 return cxstring::createRef("attribute(objc_exception)");
5297 case CXCursor_ObjCNSObject:
5298 return cxstring::createRef("attribute(NSObject)");
5299 case CXCursor_ObjCIndependentClass:
5300 return cxstring::createRef("attribute(objc_independent_class)");
5301 case CXCursor_ObjCPreciseLifetime:
5302 return cxstring::createRef("attribute(objc_precise_lifetime)");
5303 case CXCursor_ObjCReturnsInnerPointer:
5304 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5305 case CXCursor_ObjCRequiresSuper:
5306 return cxstring::createRef("attribute(objc_requires_super)");
5307 case CXCursor_ObjCRootClass:
5308 return cxstring::createRef("attribute(objc_root_class)");
5309 case CXCursor_ObjCSubclassingRestricted:
5310 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5311 case CXCursor_ObjCExplicitProtocolImpl:
5312 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5313 case CXCursor_ObjCDesignatedInitializer:
5314 return cxstring::createRef("attribute(objc_designated_initializer)");
5315 case CXCursor_ObjCRuntimeVisible:
5316 return cxstring::createRef("attribute(objc_runtime_visible)");
5317 case CXCursor_ObjCBoxable:
5318 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005319 case CXCursor_FlagEnum:
5320 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005321 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005322 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005323 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005324 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005325 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005326 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005327 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005328 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005329 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005330 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005332 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005334 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005336 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005338 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005340 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005342 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005344 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005346 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005348 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005350 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005354 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005355 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005356 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005358 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005360 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005362 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005364 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005365 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005366 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005368 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005369 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005370 return cxstring::createRef("OMPParallelDirective");
5371 case CXCursor_OMPSimdDirective:
5372 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005373 case CXCursor_OMPForDirective:
5374 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005375 case CXCursor_OMPForSimdDirective:
5376 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005377 case CXCursor_OMPSectionsDirective:
5378 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005379 case CXCursor_OMPSectionDirective:
5380 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005381 case CXCursor_OMPSingleDirective:
5382 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005383 case CXCursor_OMPMasterDirective:
5384 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005385 case CXCursor_OMPCriticalDirective:
5386 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005387 case CXCursor_OMPParallelForDirective:
5388 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005389 case CXCursor_OMPParallelForSimdDirective:
5390 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005391 case CXCursor_OMPParallelSectionsDirective:
5392 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005393 case CXCursor_OMPTaskDirective:
5394 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005395 case CXCursor_OMPTaskyieldDirective:
5396 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005397 case CXCursor_OMPBarrierDirective:
5398 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005399 case CXCursor_OMPTaskwaitDirective:
5400 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005401 case CXCursor_OMPTaskgroupDirective:
5402 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005403 case CXCursor_OMPFlushDirective:
5404 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005405 case CXCursor_OMPOrderedDirective:
5406 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005407 case CXCursor_OMPAtomicDirective:
5408 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005409 case CXCursor_OMPTargetDirective:
5410 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005411 case CXCursor_OMPTargetDataDirective:
5412 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005413 case CXCursor_OMPTargetEnterDataDirective:
5414 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005415 case CXCursor_OMPTargetExitDataDirective:
5416 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005417 case CXCursor_OMPTargetParallelDirective:
5418 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005419 case CXCursor_OMPTargetParallelForDirective:
5420 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005421 case CXCursor_OMPTargetUpdateDirective:
5422 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005423 case CXCursor_OMPTeamsDirective:
5424 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005425 case CXCursor_OMPCancellationPointDirective:
5426 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005427 case CXCursor_OMPCancelDirective:
5428 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005429 case CXCursor_OMPTaskLoopDirective:
5430 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005431 case CXCursor_OMPTaskLoopSimdDirective:
5432 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005433 case CXCursor_OMPDistributeDirective:
5434 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005435 case CXCursor_OMPDistributeParallelForDirective:
5436 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005437 case CXCursor_OMPDistributeParallelForSimdDirective:
5438 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005439 case CXCursor_OMPDistributeSimdDirective:
5440 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005441 case CXCursor_OMPTargetParallelForSimdDirective:
5442 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005443 case CXCursor_OMPTargetSimdDirective:
5444 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005445 case CXCursor_OMPTeamsDistributeDirective:
5446 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005447 case CXCursor_OMPTeamsDistributeSimdDirective:
5448 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005449 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5450 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005451 case CXCursor_OMPTeamsDistributeParallelForDirective:
5452 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005453 case CXCursor_OMPTargetTeamsDirective:
5454 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005455 case CXCursor_OMPTargetTeamsDistributeDirective:
5456 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005457 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5458 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005459 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5460 return cxstring::createRef(
5461 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005462 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5463 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005464 case CXCursor_OverloadCandidate:
5465 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005466 case CXCursor_TypeAliasTemplateDecl:
5467 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005468 case CXCursor_StaticAssert:
5469 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005470 case CXCursor_FriendDecl:
5471 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005472 }
5473
5474 llvm_unreachable("Unhandled CXCursorKind");
5475}
5476
5477struct GetCursorData {
5478 SourceLocation TokenBeginLoc;
5479 bool PointsAtMacroArgExpansion;
5480 bool VisitedObjCPropertyImplDecl;
5481 SourceLocation VisitedDeclaratorDeclStartLoc;
5482 CXCursor &BestCursor;
5483
5484 GetCursorData(SourceManager &SM,
5485 SourceLocation tokenBegin, CXCursor &outputCursor)
5486 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5487 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5488 VisitedObjCPropertyImplDecl = false;
5489 }
5490};
5491
5492static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5493 CXCursor parent,
5494 CXClientData client_data) {
5495 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5496 CXCursor *BestCursor = &Data->BestCursor;
5497
5498 // If we point inside a macro argument we should provide info of what the
5499 // token is so use the actual cursor, don't replace it with a macro expansion
5500 // cursor.
5501 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5502 return CXChildVisit_Recurse;
5503
5504 if (clang_isDeclaration(cursor.kind)) {
5505 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005506 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005507 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5508 if (MD->isImplicit())
5509 return CXChildVisit_Break;
5510
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005511 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005512 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5513 // Check that when we have multiple @class references in the same line,
5514 // that later ones do not override the previous ones.
5515 // If we have:
5516 // @class Foo, Bar;
5517 // source ranges for both start at '@', so 'Bar' will end up overriding
5518 // 'Foo' even though the cursor location was at 'Foo'.
5519 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5520 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005521 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005522 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5523 if (PrevID != ID &&
5524 !PrevID->isThisDeclarationADefinition() &&
5525 !ID->isThisDeclarationADefinition())
5526 return CXChildVisit_Break;
5527 }
5528
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005529 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005530 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5531 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5532 // Check that when we have multiple declarators in the same line,
5533 // that later ones do not override the previous ones.
5534 // If we have:
5535 // int Foo, Bar;
5536 // source ranges for both start at 'int', so 'Bar' will end up overriding
5537 // 'Foo' even though the cursor location was at 'Foo'.
5538 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5539 return CXChildVisit_Break;
5540 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5541
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005542 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005543 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5544 (void)PropImp;
5545 // Check that when we have multiple @synthesize in the same line,
5546 // that later ones do not override the previous ones.
5547 // If we have:
5548 // @synthesize Foo, Bar;
5549 // source ranges for both start at '@', so 'Bar' will end up overriding
5550 // 'Foo' even though the cursor location was at 'Foo'.
5551 if (Data->VisitedObjCPropertyImplDecl)
5552 return CXChildVisit_Break;
5553 Data->VisitedObjCPropertyImplDecl = true;
5554 }
5555 }
5556
5557 if (clang_isExpression(cursor.kind) &&
5558 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005559 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005560 // Avoid having the cursor of an expression replace the declaration cursor
5561 // when the expression source range overlaps the declaration range.
5562 // This can happen for C++ constructor expressions whose range generally
5563 // include the variable declaration, e.g.:
5564 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5565 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5566 D->getLocation() == Data->TokenBeginLoc)
5567 return CXChildVisit_Break;
5568 }
5569 }
5570
5571 // If our current best cursor is the construction of a temporary object,
5572 // don't replace that cursor with a type reference, because we want
5573 // clang_getCursor() to point at the constructor.
5574 if (clang_isExpression(BestCursor->kind) &&
5575 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5576 cursor.kind == CXCursor_TypeRef) {
5577 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5578 // as having the actual point on the type reference.
5579 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5580 return CXChildVisit_Recurse;
5581 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005582
5583 // If we already have an Objective-C superclass reference, don't
5584 // update it further.
5585 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5586 return CXChildVisit_Break;
5587
Guy Benyei11169dd2012-12-18 14:30:41 +00005588 *BestCursor = cursor;
5589 return CXChildVisit_Recurse;
5590}
5591
5592CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005593 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005594 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005595 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005596 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005597
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005598 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005599 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5600
5601 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5602 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5603
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005604 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005605 CXFile SearchFile;
5606 unsigned SearchLine, SearchColumn;
5607 CXFile ResultFile;
5608 unsigned ResultLine, ResultColumn;
5609 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5610 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5611 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005612
5613 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5614 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005615 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005616 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005617 SearchFileName = clang_getFileName(SearchFile);
5618 ResultFileName = clang_getFileName(ResultFile);
5619 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5620 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005621 *Log << llvm::format("(%s:%d:%d) = %s",
5622 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5623 clang_getCString(KindSpelling))
5624 << llvm::format("(%s:%d:%d):%s%s",
5625 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5626 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005627 clang_disposeString(SearchFileName);
5628 clang_disposeString(ResultFileName);
5629 clang_disposeString(KindSpelling);
5630 clang_disposeString(USR);
5631
5632 CXCursor Definition = clang_getCursorDefinition(Result);
5633 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5634 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5635 CXString DefinitionKindSpelling
5636 = clang_getCursorKindSpelling(Definition.kind);
5637 CXFile DefinitionFile;
5638 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005639 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005640 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005641 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005642 *Log << llvm::format(" -> %s(%s:%d:%d)",
5643 clang_getCString(DefinitionKindSpelling),
5644 clang_getCString(DefinitionFileName),
5645 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005646 clang_disposeString(DefinitionFileName);
5647 clang_disposeString(DefinitionKindSpelling);
5648 }
5649 }
5650
5651 return Result;
5652}
5653
5654CXCursor clang_getNullCursor(void) {
5655 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5656}
5657
5658unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005659 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5660 // can't set consistently. For example, when visiting a DeclStmt we will set
5661 // it but we don't set it on the result of clang_getCursorDefinition for
5662 // a reference of the same declaration.
5663 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5664 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5665 // to provide that kind of info.
5666 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005667 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005668 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005669 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005670
Guy Benyei11169dd2012-12-18 14:30:41 +00005671 return X == Y;
5672}
5673
5674unsigned clang_hashCursor(CXCursor C) {
5675 unsigned Index = 0;
5676 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5677 Index = 1;
5678
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005679 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005680 std::make_pair(C.kind, C.data[Index]));
5681}
5682
5683unsigned clang_isInvalid(enum CXCursorKind K) {
5684 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5685}
5686
5687unsigned clang_isDeclaration(enum CXCursorKind K) {
5688 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005689 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5690}
5691
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005692unsigned clang_isInvalidDeclaration(CXCursor C) {
5693 if (clang_isDeclaration(C.kind)) {
5694 if (const Decl *D = getCursorDecl(C))
5695 return D->isInvalidDecl();
5696 }
5697
5698 return 0;
5699}
5700
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005701unsigned clang_isReference(enum CXCursorKind K) {
5702 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5703}
Guy Benyei11169dd2012-12-18 14:30:41 +00005704
5705unsigned clang_isExpression(enum CXCursorKind K) {
5706 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5707}
5708
5709unsigned clang_isStatement(enum CXCursorKind K) {
5710 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5711}
5712
5713unsigned clang_isAttribute(enum CXCursorKind K) {
5714 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5715}
5716
5717unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5718 return K == CXCursor_TranslationUnit;
5719}
5720
5721unsigned clang_isPreprocessing(enum CXCursorKind K) {
5722 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5723}
5724
5725unsigned clang_isUnexposed(enum CXCursorKind K) {
5726 switch (K) {
5727 case CXCursor_UnexposedDecl:
5728 case CXCursor_UnexposedExpr:
5729 case CXCursor_UnexposedStmt:
5730 case CXCursor_UnexposedAttr:
5731 return true;
5732 default:
5733 return false;
5734 }
5735}
5736
5737CXCursorKind clang_getCursorKind(CXCursor C) {
5738 return C.kind;
5739}
5740
5741CXSourceLocation clang_getCursorLocation(CXCursor C) {
5742 if (clang_isReference(C.kind)) {
5743 switch (C.kind) {
5744 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005745 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005746 = getCursorObjCSuperClassRef(C);
5747 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5748 }
5749
5750 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005751 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005752 = getCursorObjCProtocolRef(C);
5753 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5754 }
5755
5756 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005757 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005758 = getCursorObjCClassRef(C);
5759 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5760 }
5761
5762 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005763 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5765 }
5766
5767 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005768 std::pair<const TemplateDecl *, SourceLocation> P =
5769 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005770 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5771 }
5772
5773 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005774 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005775 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5776 }
5777
5778 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005779 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005780 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5781 }
5782
5783 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005784 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005785 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5786 }
5787
5788 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005789 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005790 if (!BaseSpec)
5791 return clang_getNullLocation();
5792
5793 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5794 return cxloc::translateSourceLocation(getCursorContext(C),
5795 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005796
Guy Benyei11169dd2012-12-18 14:30:41 +00005797 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005798 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005799 }
5800
5801 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005802 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005803 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5804 }
5805
5806 case CXCursor_OverloadedDeclRef:
5807 return cxloc::translateSourceLocation(getCursorContext(C),
5808 getCursorOverloadedDeclRef(C).second);
5809
5810 default:
5811 // FIXME: Need a way to enumerate all non-reference cases.
5812 llvm_unreachable("Missed a reference kind");
5813 }
5814 }
5815
5816 if (clang_isExpression(C.kind))
5817 return cxloc::translateSourceLocation(getCursorContext(C),
5818 getLocationFromExpr(getCursorExpr(C)));
5819
5820 if (clang_isStatement(C.kind))
5821 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005822 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005823
5824 if (C.kind == CXCursor_PreprocessingDirective) {
5825 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5826 return cxloc::translateSourceLocation(getCursorContext(C), L);
5827 }
5828
5829 if (C.kind == CXCursor_MacroExpansion) {
5830 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005831 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005832 return cxloc::translateSourceLocation(getCursorContext(C), L);
5833 }
5834
5835 if (C.kind == CXCursor_MacroDefinition) {
5836 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5837 return cxloc::translateSourceLocation(getCursorContext(C), L);
5838 }
5839
5840 if (C.kind == CXCursor_InclusionDirective) {
5841 SourceLocation L
5842 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5843 return cxloc::translateSourceLocation(getCursorContext(C), L);
5844 }
5845
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005846 if (clang_isAttribute(C.kind)) {
5847 SourceLocation L
5848 = cxcursor::getCursorAttr(C)->getLocation();
5849 return cxloc::translateSourceLocation(getCursorContext(C), L);
5850 }
5851
Guy Benyei11169dd2012-12-18 14:30:41 +00005852 if (!clang_isDeclaration(C.kind))
5853 return clang_getNullLocation();
5854
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005855 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005856 if (!D)
5857 return clang_getNullLocation();
5858
5859 SourceLocation Loc = D->getLocation();
5860 // FIXME: Multiple variables declared in a single declaration
5861 // currently lack the information needed to correctly determine their
5862 // ranges when accounting for the type-specifier. We use context
5863 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5864 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005865 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005866 if (!cxcursor::isFirstInDeclGroup(C))
5867 Loc = VD->getLocation();
5868 }
5869
5870 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005871 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005872 Loc = MD->getSelectorStartLoc();
5873
5874 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5875}
5876
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005877} // end extern "C"
5878
Guy Benyei11169dd2012-12-18 14:30:41 +00005879CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5880 assert(TU);
5881
5882 // Guard against an invalid SourceLocation, or we may assert in one
5883 // of the following calls.
5884 if (SLoc.isInvalid())
5885 return clang_getNullCursor();
5886
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005887 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005888
5889 // Translate the given source location to make it point at the beginning of
5890 // the token under the cursor.
5891 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5892 CXXUnit->getASTContext().getLangOpts());
5893
5894 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5895 if (SLoc.isValid()) {
5896 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5897 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5898 /*VisitPreprocessorLast=*/true,
5899 /*VisitIncludedEntities=*/false,
5900 SourceLocation(SLoc));
5901 CursorVis.visitFileRegion();
5902 }
5903
5904 return Result;
5905}
5906
5907static SourceRange getRawCursorExtent(CXCursor C) {
5908 if (clang_isReference(C.kind)) {
5909 switch (C.kind) {
5910 case CXCursor_ObjCSuperClassRef:
5911 return getCursorObjCSuperClassRef(C).second;
5912
5913 case CXCursor_ObjCProtocolRef:
5914 return getCursorObjCProtocolRef(C).second;
5915
5916 case CXCursor_ObjCClassRef:
5917 return getCursorObjCClassRef(C).second;
5918
5919 case CXCursor_TypeRef:
5920 return getCursorTypeRef(C).second;
5921
5922 case CXCursor_TemplateRef:
5923 return getCursorTemplateRef(C).second;
5924
5925 case CXCursor_NamespaceRef:
5926 return getCursorNamespaceRef(C).second;
5927
5928 case CXCursor_MemberRef:
5929 return getCursorMemberRef(C).second;
5930
5931 case CXCursor_CXXBaseSpecifier:
5932 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5933
5934 case CXCursor_LabelRef:
5935 return getCursorLabelRef(C).second;
5936
5937 case CXCursor_OverloadedDeclRef:
5938 return getCursorOverloadedDeclRef(C).second;
5939
5940 case CXCursor_VariableRef:
5941 return getCursorVariableRef(C).second;
5942
5943 default:
5944 // FIXME: Need a way to enumerate all non-reference cases.
5945 llvm_unreachable("Missed a reference kind");
5946 }
5947 }
5948
5949 if (clang_isExpression(C.kind))
5950 return getCursorExpr(C)->getSourceRange();
5951
5952 if (clang_isStatement(C.kind))
5953 return getCursorStmt(C)->getSourceRange();
5954
5955 if (clang_isAttribute(C.kind))
5956 return getCursorAttr(C)->getRange();
5957
5958 if (C.kind == CXCursor_PreprocessingDirective)
5959 return cxcursor::getCursorPreprocessingDirective(C);
5960
5961 if (C.kind == CXCursor_MacroExpansion) {
5962 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005963 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005964 return TU->mapRangeFromPreamble(Range);
5965 }
5966
5967 if (C.kind == CXCursor_MacroDefinition) {
5968 ASTUnit *TU = getCursorASTUnit(C);
5969 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5970 return TU->mapRangeFromPreamble(Range);
5971 }
5972
5973 if (C.kind == CXCursor_InclusionDirective) {
5974 ASTUnit *TU = getCursorASTUnit(C);
5975 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5976 return TU->mapRangeFromPreamble(Range);
5977 }
5978
5979 if (C.kind == CXCursor_TranslationUnit) {
5980 ASTUnit *TU = getCursorASTUnit(C);
5981 FileID MainID = TU->getSourceManager().getMainFileID();
5982 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5983 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5984 return SourceRange(Start, End);
5985 }
5986
5987 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005988 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 if (!D)
5990 return SourceRange();
5991
5992 SourceRange R = D->getSourceRange();
5993 // FIXME: Multiple variables declared in a single declaration
5994 // currently lack the information needed to correctly determine their
5995 // ranges when accounting for the type-specifier. We use context
5996 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5997 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005998 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005999 if (!cxcursor::isFirstInDeclGroup(C))
6000 R.setBegin(VD->getLocation());
6001 }
6002 return R;
6003 }
6004 return SourceRange();
6005}
6006
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006007/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006008/// the decl-specifier-seq for declarations.
6009static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6010 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006011 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006012 if (!D)
6013 return SourceRange();
6014
6015 SourceRange R = D->getSourceRange();
6016
6017 // Adjust the start of the location for declarations preceded by
6018 // declaration specifiers.
6019 SourceLocation StartLoc;
6020 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6021 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006022 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006023 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006024 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006025 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006026 }
6027
6028 if (StartLoc.isValid() && R.getBegin().isValid() &&
6029 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6030 R.setBegin(StartLoc);
6031
6032 // FIXME: Multiple variables declared in a single declaration
6033 // currently lack the information needed to correctly determine their
6034 // ranges when accounting for the type-specifier. We use context
6035 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6036 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006037 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006038 if (!cxcursor::isFirstInDeclGroup(C))
6039 R.setBegin(VD->getLocation());
6040 }
6041
6042 return R;
6043 }
6044
6045 return getRawCursorExtent(C);
6046}
6047
Guy Benyei11169dd2012-12-18 14:30:41 +00006048CXSourceRange clang_getCursorExtent(CXCursor C) {
6049 SourceRange R = getRawCursorExtent(C);
6050 if (R.isInvalid())
6051 return clang_getNullRange();
6052
6053 return cxloc::translateSourceRange(getCursorContext(C), R);
6054}
6055
6056CXCursor clang_getCursorReferenced(CXCursor C) {
6057 if (clang_isInvalid(C.kind))
6058 return clang_getNullCursor();
6059
6060 CXTranslationUnit tu = getCursorTU(C);
6061 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006062 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006063 if (!D)
6064 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006065 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006066 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006067 if (const ObjCPropertyImplDecl *PropImpl =
6068 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006069 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6070 return MakeCXCursor(Property, tu);
6071
6072 return C;
6073 }
6074
6075 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006076 const Expr *E = getCursorExpr(C);
6077 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006078 if (D) {
6079 CXCursor declCursor = MakeCXCursor(D, tu);
6080 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6081 declCursor);
6082 return declCursor;
6083 }
6084
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006085 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006086 return MakeCursorOverloadedDeclRef(Ovl, tu);
6087
6088 return clang_getNullCursor();
6089 }
6090
6091 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006092 const Stmt *S = getCursorStmt(C);
6093 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006094 if (LabelDecl *label = Goto->getLabel())
6095 if (LabelStmt *labelS = label->getStmt())
6096 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6097
6098 return clang_getNullCursor();
6099 }
Richard Smith66a81862015-05-04 02:25:31 +00006100
Guy Benyei11169dd2012-12-18 14:30:41 +00006101 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006102 if (const MacroDefinitionRecord *Def =
6103 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 return MakeMacroDefinitionCursor(Def, tu);
6105 }
6106
6107 if (!clang_isReference(C.kind))
6108 return clang_getNullCursor();
6109
6110 switch (C.kind) {
6111 case CXCursor_ObjCSuperClassRef:
6112 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6113
6114 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006115 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6116 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006117 return MakeCXCursor(Def, tu);
6118
6119 return MakeCXCursor(Prot, tu);
6120 }
6121
6122 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006123 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6124 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006125 return MakeCXCursor(Def, tu);
6126
6127 return MakeCXCursor(Class, tu);
6128 }
6129
6130 case CXCursor_TypeRef:
6131 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6132
6133 case CXCursor_TemplateRef:
6134 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6135
6136 case CXCursor_NamespaceRef:
6137 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6138
6139 case CXCursor_MemberRef:
6140 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6141
6142 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006143 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6145 tu ));
6146 }
6147
6148 case CXCursor_LabelRef:
6149 // FIXME: We end up faking the "parent" declaration here because we
6150 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006151 return MakeCXCursor(getCursorLabelRef(C).first,
6152 cxtu::getASTUnit(tu)->getASTContext()
6153 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006154 tu);
6155
6156 case CXCursor_OverloadedDeclRef:
6157 return C;
6158
6159 case CXCursor_VariableRef:
6160 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6161
6162 default:
6163 // We would prefer to enumerate all non-reference cursor kinds here.
6164 llvm_unreachable("Unhandled reference cursor kind");
6165 }
6166}
6167
6168CXCursor clang_getCursorDefinition(CXCursor C) {
6169 if (clang_isInvalid(C.kind))
6170 return clang_getNullCursor();
6171
6172 CXTranslationUnit TU = getCursorTU(C);
6173
6174 bool WasReference = false;
6175 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6176 C = clang_getCursorReferenced(C);
6177 WasReference = true;
6178 }
6179
6180 if (C.kind == CXCursor_MacroExpansion)
6181 return clang_getCursorReferenced(C);
6182
6183 if (!clang_isDeclaration(C.kind))
6184 return clang_getNullCursor();
6185
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006186 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006187 if (!D)
6188 return clang_getNullCursor();
6189
6190 switch (D->getKind()) {
6191 // Declaration kinds that don't really separate the notions of
6192 // declaration and definition.
6193 case Decl::Namespace:
6194 case Decl::Typedef:
6195 case Decl::TypeAlias:
6196 case Decl::TypeAliasTemplate:
6197 case Decl::TemplateTypeParm:
6198 case Decl::EnumConstant:
6199 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006200 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006201 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006202 case Decl::IndirectField:
6203 case Decl::ObjCIvar:
6204 case Decl::ObjCAtDefsField:
6205 case Decl::ImplicitParam:
6206 case Decl::ParmVar:
6207 case Decl::NonTypeTemplateParm:
6208 case Decl::TemplateTemplateParm:
6209 case Decl::ObjCCategoryImpl:
6210 case Decl::ObjCImplementation:
6211 case Decl::AccessSpec:
6212 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006213 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 case Decl::ObjCPropertyImpl:
6215 case Decl::FileScopeAsm:
6216 case Decl::StaticAssert:
6217 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006218 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006219 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006220 case Decl::Label: // FIXME: Is this right??
6221 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006222 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006223 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006224 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006225 case Decl::OMPDeclareReduction:
Kelvin Li1408f912018-09-26 04:28:39 +00006226 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006227 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006228 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006229 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006230 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006231 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 return C;
6233
6234 // Declaration kinds that don't make any sense here, but are
6235 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006236 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006237 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006238 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006239 break;
6240
6241 // Declaration kinds for which the definition is not resolvable.
6242 case Decl::UnresolvedUsingTypename:
6243 case Decl::UnresolvedUsingValue:
6244 break;
6245
6246 case Decl::UsingDirective:
6247 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6248 TU);
6249
6250 case Decl::NamespaceAlias:
6251 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6252
6253 case Decl::Enum:
6254 case Decl::Record:
6255 case Decl::CXXRecord:
6256 case Decl::ClassTemplateSpecialization:
6257 case Decl::ClassTemplatePartialSpecialization:
6258 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6259 return MakeCXCursor(Def, TU);
6260 return clang_getNullCursor();
6261
6262 case Decl::Function:
6263 case Decl::CXXMethod:
6264 case Decl::CXXConstructor:
6265 case Decl::CXXDestructor:
6266 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006267 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006268 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006269 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006270 return clang_getNullCursor();
6271 }
6272
Larisse Voufo39a1e502013-08-06 01:03:05 +00006273 case Decl::Var:
6274 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006275 case Decl::VarTemplatePartialSpecialization:
6276 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006278 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006279 return MakeCXCursor(Def, TU);
6280 return clang_getNullCursor();
6281 }
6282
6283 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006284 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006285 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6286 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6287 return clang_getNullCursor();
6288 }
6289
6290 case Decl::ClassTemplate: {
6291 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6292 ->getDefinition())
6293 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6294 TU);
6295 return clang_getNullCursor();
6296 }
6297
Larisse Voufo39a1e502013-08-06 01:03:05 +00006298 case Decl::VarTemplate: {
6299 if (VarDecl *Def =
6300 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6301 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6302 return clang_getNullCursor();
6303 }
6304
Guy Benyei11169dd2012-12-18 14:30:41 +00006305 case Decl::Using:
6306 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6307 D->getLocation(), TU);
6308
6309 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006310 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006311 return clang_getCursorDefinition(
6312 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6313 TU));
6314
6315 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006316 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006317 if (Method->isThisDeclarationADefinition())
6318 return C;
6319
6320 // Dig out the method definition in the associated
6321 // @implementation, if we have it.
6322 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006323 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006324 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6325 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6326 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6327 Method->isInstanceMethod()))
6328 if (Def->isThisDeclarationADefinition())
6329 return MakeCXCursor(Def, TU);
6330
6331 return clang_getNullCursor();
6332 }
6333
6334 case Decl::ObjCCategory:
6335 if (ObjCCategoryImplDecl *Impl
6336 = cast<ObjCCategoryDecl>(D)->getImplementation())
6337 return MakeCXCursor(Impl, TU);
6338 return clang_getNullCursor();
6339
6340 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006341 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006342 return MakeCXCursor(Def, TU);
6343 return clang_getNullCursor();
6344
6345 case Decl::ObjCInterface: {
6346 // There are two notions of a "definition" for an Objective-C
6347 // class: the interface and its implementation. When we resolved a
6348 // reference to an Objective-C class, produce the @interface as
6349 // the definition; when we were provided with the interface,
6350 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006351 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006353 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006354 return MakeCXCursor(Def, TU);
6355 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6356 return MakeCXCursor(Impl, TU);
6357 return clang_getNullCursor();
6358 }
6359
6360 case Decl::ObjCProperty:
6361 // FIXME: We don't really know where to find the
6362 // ObjCPropertyImplDecls that implement this property.
6363 return clang_getNullCursor();
6364
6365 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006366 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006367 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006368 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006369 return MakeCXCursor(Def, TU);
6370
6371 return clang_getNullCursor();
6372
6373 case Decl::Friend:
6374 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6375 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6376 return clang_getNullCursor();
6377
6378 case Decl::FriendTemplate:
6379 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6380 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6381 return clang_getNullCursor();
6382 }
6383
6384 return clang_getNullCursor();
6385}
6386
6387unsigned clang_isCursorDefinition(CXCursor C) {
6388 if (!clang_isDeclaration(C.kind))
6389 return 0;
6390
6391 return clang_getCursorDefinition(C) == C;
6392}
6393
6394CXCursor clang_getCanonicalCursor(CXCursor C) {
6395 if (!clang_isDeclaration(C.kind))
6396 return C;
6397
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006398 if (const Decl *D = getCursorDecl(C)) {
6399 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006400 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6401 return MakeCXCursor(CatD, getCursorTU(C));
6402
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006403 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6404 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006405 return MakeCXCursor(IFD, getCursorTU(C));
6406
6407 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6408 }
6409
6410 return C;
6411}
6412
6413int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6414 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6415}
6416
6417unsigned clang_getNumOverloadedDecls(CXCursor C) {
6418 if (C.kind != CXCursor_OverloadedDeclRef)
6419 return 0;
6420
6421 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006422 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006423 return E->getNumDecls();
6424
6425 if (OverloadedTemplateStorage *S
6426 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6427 return S->size();
6428
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006429 const Decl *D = Storage.get<const Decl *>();
6430 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006431 return Using->shadow_size();
6432
6433 return 0;
6434}
6435
6436CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6437 if (cursor.kind != CXCursor_OverloadedDeclRef)
6438 return clang_getNullCursor();
6439
6440 if (index >= clang_getNumOverloadedDecls(cursor))
6441 return clang_getNullCursor();
6442
6443 CXTranslationUnit TU = getCursorTU(cursor);
6444 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006445 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006446 return MakeCXCursor(E->decls_begin()[index], TU);
6447
6448 if (OverloadedTemplateStorage *S
6449 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6450 return MakeCXCursor(S->begin()[index], TU);
6451
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006452 const Decl *D = Storage.get<const Decl *>();
6453 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006454 // FIXME: This is, unfortunately, linear time.
6455 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6456 std::advance(Pos, index);
6457 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6458 }
6459
6460 return clang_getNullCursor();
6461}
6462
6463void clang_getDefinitionSpellingAndExtent(CXCursor C,
6464 const char **startBuf,
6465 const char **endBuf,
6466 unsigned *startLine,
6467 unsigned *startColumn,
6468 unsigned *endLine,
6469 unsigned *endColumn) {
6470 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006471 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6473
6474 SourceManager &SM = FD->getASTContext().getSourceManager();
6475 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6476 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6477 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6478 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6479 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6480 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6481}
6482
6483
6484CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6485 unsigned PieceIndex) {
6486 RefNamePieces Pieces;
6487
6488 switch (C.kind) {
6489 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006490 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6492 E->getQualifierLoc().getSourceRange());
6493 break;
6494
6495 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006496 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6497 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6498 Pieces =
6499 buildPieces(NameFlags, false, E->getNameInfo(),
6500 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6501 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 break;
6503
6504 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006505 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006506 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006507 const Expr *Callee = OCE->getCallee();
6508 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006509 Callee = ICE->getSubExpr();
6510
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006511 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006512 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6513 DRE->getQualifierLoc().getSourceRange());
6514 }
6515 break;
6516
6517 default:
6518 break;
6519 }
6520
6521 if (Pieces.empty()) {
6522 if (PieceIndex == 0)
6523 return clang_getCursorExtent(C);
6524 } else if (PieceIndex < Pieces.size()) {
6525 SourceRange R = Pieces[PieceIndex];
6526 if (R.isValid())
6527 return cxloc::translateSourceRange(getCursorContext(C), R);
6528 }
6529
6530 return clang_getNullRange();
6531}
6532
6533void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006534 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6535 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006536}
6537
6538void clang_executeOnThread(void (*fn)(void*), void *user_data,
6539 unsigned stack_size) {
6540 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6541}
6542
Guy Benyei11169dd2012-12-18 14:30:41 +00006543//===----------------------------------------------------------------------===//
6544// Token-based Operations.
6545//===----------------------------------------------------------------------===//
6546
6547/* CXToken layout:
6548 * int_data[0]: a CXTokenKind
6549 * int_data[1]: starting token location
6550 * int_data[2]: token length
6551 * int_data[3]: reserved
6552 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6553 * otherwise unused.
6554 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006555CXTokenKind clang_getTokenKind(CXToken CXTok) {
6556 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6557}
6558
6559CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6560 switch (clang_getTokenKind(CXTok)) {
6561 case CXToken_Identifier:
6562 case CXToken_Keyword:
6563 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006564 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006565 ->getNameStart());
6566
6567 case CXToken_Literal: {
6568 // We have stashed the starting pointer in the ptr_data field. Use it.
6569 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006570 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006571 }
6572
6573 case CXToken_Punctuation:
6574 case CXToken_Comment:
6575 break;
6576 }
6577
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006578 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006579 LOG_BAD_TU(TU);
6580 return cxstring::createEmpty();
6581 }
6582
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 // We have to find the starting buffer pointer the hard way, by
6584 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006585 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006586 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006587 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006588
6589 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6590 std::pair<FileID, unsigned> LocInfo
6591 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6592 bool Invalid = false;
6593 StringRef Buffer
6594 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6595 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006596 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006597
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006598 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006599}
6600
6601CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006602 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006603 LOG_BAD_TU(TU);
6604 return clang_getNullLocation();
6605 }
6606
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006607 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006608 if (!CXXUnit)
6609 return clang_getNullLocation();
6610
6611 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6612 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6613}
6614
6615CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006616 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006617 LOG_BAD_TU(TU);
6618 return clang_getNullRange();
6619 }
6620
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006621 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006622 if (!CXXUnit)
6623 return clang_getNullRange();
6624
6625 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6626 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6627}
6628
6629static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6630 SmallVectorImpl<CXToken> &CXTokens) {
6631 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6632 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006633 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006634 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006635 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006636
6637 // Cannot tokenize across files.
6638 if (BeginLocInfo.first != EndLocInfo.first)
6639 return;
6640
6641 // Create a lexer
6642 bool Invalid = false;
6643 StringRef Buffer
6644 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6645 if (Invalid)
6646 return;
6647
6648 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6649 CXXUnit->getASTContext().getLangOpts(),
6650 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6651 Lex.SetCommentRetentionState(true);
6652
6653 // Lex tokens until we hit the end of the range.
6654 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6655 Token Tok;
6656 bool previousWasAt = false;
6657 do {
6658 // Lex the next token
6659 Lex.LexFromRawLexer(Tok);
6660 if (Tok.is(tok::eof))
6661 break;
6662
6663 // Initialize the CXToken.
6664 CXToken CXTok;
6665
6666 // - Common fields
6667 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6668 CXTok.int_data[2] = Tok.getLength();
6669 CXTok.int_data[3] = 0;
6670
6671 // - Kind-specific fields
6672 if (Tok.isLiteral()) {
6673 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006674 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006675 } else if (Tok.is(tok::raw_identifier)) {
6676 // Lookup the identifier to determine whether we have a keyword.
6677 IdentifierInfo *II
6678 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6679
6680 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6681 CXTok.int_data[0] = CXToken_Keyword;
6682 }
6683 else {
6684 CXTok.int_data[0] = Tok.is(tok::identifier)
6685 ? CXToken_Identifier
6686 : CXToken_Keyword;
6687 }
6688 CXTok.ptr_data = II;
6689 } else if (Tok.is(tok::comment)) {
6690 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006691 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006692 } else {
6693 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006694 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006695 }
6696 CXTokens.push_back(CXTok);
6697 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006698 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006699}
6700
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006701CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6702 LOG_FUNC_SECTION {
6703 *Log << TU << ' ' << Location;
6704 }
6705
6706 if (isNotUsableTU(TU)) {
6707 LOG_BAD_TU(TU);
6708 return NULL;
6709 }
6710
6711 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6712 if (!CXXUnit)
6713 return NULL;
6714
6715 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6716 if (Begin.isInvalid())
6717 return NULL;
6718 SourceManager &SM = CXXUnit->getSourceManager();
6719 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6720 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6721
6722 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6723
6724 SmallVector<CXToken, 32> CXTokens;
6725 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6726
6727 if (CXTokens.empty())
6728 return NULL;
6729
6730 CXTokens.resize(1);
6731 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6732
6733 memmove(Token, CXTokens.data(), sizeof(CXToken));
6734 return Token;
6735}
6736
Guy Benyei11169dd2012-12-18 14:30:41 +00006737void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6738 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006739 LOG_FUNC_SECTION {
6740 *Log << TU << ' ' << Range;
6741 }
6742
Guy Benyei11169dd2012-12-18 14:30:41 +00006743 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006744 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006745 if (NumTokens)
6746 *NumTokens = 0;
6747
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006748 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006749 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006750 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006751 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006752
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006753 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006754 if (!CXXUnit || !Tokens || !NumTokens)
6755 return;
6756
6757 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6758
6759 SourceRange R = cxloc::translateCXSourceRange(Range);
6760 if (R.isInvalid())
6761 return;
6762
6763 SmallVector<CXToken, 32> CXTokens;
6764 getTokens(CXXUnit, R, CXTokens);
6765
6766 if (CXTokens.empty())
6767 return;
6768
Serge Pavlov52525732018-02-21 02:02:39 +00006769 *Tokens = static_cast<CXToken *>(
6770 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006771 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6772 *NumTokens = CXTokens.size();
6773}
6774
6775void clang_disposeTokens(CXTranslationUnit TU,
6776 CXToken *Tokens, unsigned NumTokens) {
6777 free(Tokens);
6778}
6779
Guy Benyei11169dd2012-12-18 14:30:41 +00006780//===----------------------------------------------------------------------===//
6781// Token annotation APIs.
6782//===----------------------------------------------------------------------===//
6783
Guy Benyei11169dd2012-12-18 14:30:41 +00006784static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6785 CXCursor parent,
6786 CXClientData client_data);
6787static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6788 CXClientData client_data);
6789
6790namespace {
6791class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006792 CXToken *Tokens;
6793 CXCursor *Cursors;
6794 unsigned NumTokens;
6795 unsigned TokIdx;
6796 unsigned PreprocessingTokIdx;
6797 CursorVisitor AnnotateVis;
6798 SourceManager &SrcMgr;
6799 bool HasContextSensitiveKeywords;
6800
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006801 struct PostChildrenAction {
6802 CXCursor cursor;
6803 enum Action { Invalid, Ignore, Postpone } action;
6804 };
6805 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6806
Guy Benyei11169dd2012-12-18 14:30:41 +00006807 struct PostChildrenInfo {
6808 CXCursor Cursor;
6809 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006810 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006811 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006812 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006813 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006814 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006815
6816 CXToken &getTok(unsigned Idx) {
6817 assert(Idx < NumTokens);
6818 return Tokens[Idx];
6819 }
6820 const CXToken &getTok(unsigned Idx) const {
6821 assert(Idx < NumTokens);
6822 return Tokens[Idx];
6823 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006824 bool MoreTokens() const { return TokIdx < NumTokens; }
6825 unsigned NextToken() const { return TokIdx; }
6826 void AdvanceToken() { ++TokIdx; }
6827 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006828 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006829 }
6830 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006831 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006832 }
6833 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006834 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006835 }
6836
6837 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006838 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006839 SourceRange);
6840
6841public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006842 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006843 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006844 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006845 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006846 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006847 AnnotateTokensVisitor, this,
6848 /*VisitPreprocessorLast=*/true,
6849 /*VisitIncludedEntities=*/false,
6850 RegionOfInterest,
6851 /*VisitDeclsOnly=*/false,
6852 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006853 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006854 HasContextSensitiveKeywords(false) { }
6855
6856 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6857 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006858 bool IsIgnoredChildCursor(CXCursor cursor) const;
6859 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6860
Guy Benyei11169dd2012-12-18 14:30:41 +00006861 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006862 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6863 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6864
Guy Benyei11169dd2012-12-18 14:30:41 +00006865 void AnnotateTokens();
6866
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006867 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006868 /// context-sensitive keywords.
6869 bool hasContextSensitiveKeywords() const {
6870 return HasContextSensitiveKeywords;
6871 }
6872
6873 ~AnnotateTokensWorker() {
6874 assert(PostChildrenInfos.empty());
6875 }
6876};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006877}
Guy Benyei11169dd2012-12-18 14:30:41 +00006878
6879void AnnotateTokensWorker::AnnotateTokens() {
6880 // Walk the AST within the region of interest, annotating tokens
6881 // along the way.
6882 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006883}
Guy Benyei11169dd2012-12-18 14:30:41 +00006884
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006885bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6886 if (PostChildrenInfos.empty())
6887 return false;
6888
6889 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6890 if (ChildAction.cursor == cursor &&
6891 ChildAction.action == PostChildrenAction::Ignore) {
6892 return true;
6893 }
6894 }
6895
6896 return false;
6897}
6898
6899const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6900 if (!clang_isExpression(Cursor.kind))
6901 return nullptr;
6902
6903 const Expr *E = getCursorExpr(Cursor);
6904 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6905 const OverloadedOperatorKind Kind = OCE->getOperator();
6906 if (Kind == OO_Call || Kind == OO_Subscript)
6907 return OCE;
6908 }
6909
6910 return nullptr;
6911}
6912
6913AnnotateTokensWorker::PostChildrenActions
6914AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6915 PostChildrenActions actions;
6916
6917 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6918 // visited before the arguments to the operator call. For the Call and
6919 // Subscript operator the range of this DeclRefExpr includes the whole call
6920 // expression, so that all tokens in that range would be mapped to the
6921 // operator function, including the tokens of the arguments. To avoid that,
6922 // ensure to visit this DeclRefExpr as last node.
6923 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6924 const Expr *Callee = OCE->getCallee();
6925 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6926 const Expr *SubExpr = ICE->getSubExpr();
6927 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6928 const Decl *parentDecl = getCursorParentDecl(Cursor);
6929 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6930
6931 // Visit the DeclRefExpr as last.
6932 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6933 actions.push_back({cxChild, PostChildrenAction::Postpone});
6934
6935 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6936 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6937 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6938 actions.push_back({cxChild, PostChildrenAction::Ignore});
6939 }
6940 }
6941 }
6942
6943 return actions;
6944}
6945
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006946static inline void updateCursorAnnotation(CXCursor &Cursor,
6947 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006948 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006950 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006951}
6952
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006953/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006954//// between the cursor location and the source range is the same as
6955/// \arg compResult.
6956///
6957/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6958/// Pass RangeOverlap to annotate tokens inside a range.
6959void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6960 RangeComparisonResult compResult,
6961 SourceRange range) {
6962 while (MoreTokens()) {
6963 const unsigned I = NextToken();
6964 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006965 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6966 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006967
6968 SourceLocation TokLoc = GetTokenLoc(I);
6969 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006970 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006971 AdvanceToken();
6972 continue;
6973 }
6974 break;
6975 }
6976}
6977
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006978/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006979/// \returns true if it advanced beyond all macro tokens, false otherwise.
6980bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 CXCursor updateC,
6982 RangeComparisonResult compResult,
6983 SourceRange range) {
6984 assert(MoreTokens());
6985 assert(isFunctionMacroToken(NextToken()) &&
6986 "Should be called only for macro arg tokens");
6987
6988 // This works differently than annotateAndAdvanceTokens; because expanded
6989 // macro arguments can have arbitrary translation-unit source order, we do not
6990 // advance the token index one by one until a token fails the range test.
6991 // We only advance once past all of the macro arg tokens if all of them
6992 // pass the range test. If one of them fails we keep the token index pointing
6993 // at the start of the macro arg tokens so that the failing token will be
6994 // annotated by a subsequent annotation try.
6995
6996 bool atLeastOneCompFail = false;
6997
6998 unsigned I = NextToken();
6999 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7000 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7001 if (TokLoc.isFileID())
7002 continue; // not macro arg token, it's parens or comma.
7003 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7004 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7005 Cursors[I] = updateC;
7006 } else
7007 atLeastOneCompFail = true;
7008 }
7009
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007010 if (atLeastOneCompFail)
7011 return false;
7012
7013 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7014 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007015}
7016
7017enum CXChildVisitResult
7018AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007019 SourceRange cursorRange = getRawCursorExtent(cursor);
7020 if (cursorRange.isInvalid())
7021 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007022
7023 if (IsIgnoredChildCursor(cursor))
7024 return CXChildVisit_Continue;
7025
Guy Benyei11169dd2012-12-18 14:30:41 +00007026 if (!HasContextSensitiveKeywords) {
7027 // Objective-C properties can have context-sensitive keywords.
7028 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007029 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7031 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7032 }
7033 // Objective-C methods can have context-sensitive keywords.
7034 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7035 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007036 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007037 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7038 if (Method->getObjCDeclQualifier())
7039 HasContextSensitiveKeywords = true;
7040 else {
David Majnemer59f77922016-06-24 04:05:48 +00007041 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007042 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007043 HasContextSensitiveKeywords = true;
7044 break;
7045 }
7046 }
7047 }
7048 }
7049 }
7050 // C++ methods can have context-sensitive keywords.
7051 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007052 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007053 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7054 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7055 HasContextSensitiveKeywords = true;
7056 }
7057 }
7058 // C++ classes can have context-sensitive keywords.
7059 else if (cursor.kind == CXCursor_StructDecl ||
7060 cursor.kind == CXCursor_ClassDecl ||
7061 cursor.kind == CXCursor_ClassTemplate ||
7062 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007063 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007064 if (D->hasAttr<FinalAttr>())
7065 HasContextSensitiveKeywords = true;
7066 }
7067 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007068
7069 // Don't override a property annotation with its getter/setter method.
7070 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7071 parent.kind == CXCursor_ObjCPropertyDecl)
7072 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007073
7074 if (clang_isPreprocessing(cursor.kind)) {
7075 // Items in the preprocessing record are kept separate from items in
7076 // declarations, so we keep a separate token index.
7077 unsigned SavedTokIdx = TokIdx;
7078 TokIdx = PreprocessingTokIdx;
7079
7080 // Skip tokens up until we catch up to the beginning of the preprocessing
7081 // entry.
7082 while (MoreTokens()) {
7083 const unsigned I = NextToken();
7084 SourceLocation TokLoc = GetTokenLoc(I);
7085 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7086 case RangeBefore:
7087 AdvanceToken();
7088 continue;
7089 case RangeAfter:
7090 case RangeOverlap:
7091 break;
7092 }
7093 break;
7094 }
7095
7096 // Look at all of the tokens within this range.
7097 while (MoreTokens()) {
7098 const unsigned I = NextToken();
7099 SourceLocation TokLoc = GetTokenLoc(I);
7100 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7101 case RangeBefore:
7102 llvm_unreachable("Infeasible");
7103 case RangeAfter:
7104 break;
7105 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007106 // For macro expansions, just note where the beginning of the macro
7107 // expansion occurs.
7108 if (cursor.kind == CXCursor_MacroExpansion) {
7109 if (TokLoc == cursorRange.getBegin())
7110 Cursors[I] = cursor;
7111 AdvanceToken();
7112 break;
7113 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007114 // We may have already annotated macro names inside macro definitions.
7115 if (Cursors[I].kind != CXCursor_MacroExpansion)
7116 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007117 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007118 continue;
7119 }
7120 break;
7121 }
7122
7123 // Save the preprocessing token index; restore the non-preprocessing
7124 // token index.
7125 PreprocessingTokIdx = TokIdx;
7126 TokIdx = SavedTokIdx;
7127 return CXChildVisit_Recurse;
7128 }
7129
7130 if (cursorRange.isInvalid())
7131 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007132
7133 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007134 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007135 const enum CXCursorKind K = clang_getCursorKind(parent);
7136 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007137 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7138 // Attributes are annotated out-of-order, skip tokens until we reach it.
7139 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007140 ? clang_getNullCursor() : parent;
7141
7142 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7143
7144 // Avoid having the cursor of an expression "overwrite" the annotation of the
7145 // variable declaration that it belongs to.
7146 // This can happen for C++ constructor expressions whose range generally
7147 // include the variable declaration, e.g.:
7148 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007149 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007150 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00007151 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007152 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007153 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7154 E->getBeginLoc() == D->getLocation() &&
7155 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007156 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 AdvanceToken();
7158 }
7159 }
7160 }
7161
7162 // Before recursing into the children keep some state that we are going
7163 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7164 // extra work after the child nodes are visited.
7165 // Note that we don't call VisitChildren here to avoid traversing statements
7166 // code-recursively which can blow the stack.
7167
7168 PostChildrenInfo Info;
7169 Info.Cursor = cursor;
7170 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007171 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007172 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007173 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 PostChildrenInfos.push_back(Info);
7175
7176 return CXChildVisit_Recurse;
7177}
7178
7179bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7180 if (PostChildrenInfos.empty())
7181 return false;
7182 const PostChildrenInfo &Info = PostChildrenInfos.back();
7183 if (!clang_equalCursors(Info.Cursor, cursor))
7184 return false;
7185
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007186 HandlePostPonedChildCursors(Info);
7187
Guy Benyei11169dd2012-12-18 14:30:41 +00007188 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7189 const unsigned AfterChildren = NextToken();
7190 SourceRange cursorRange = Info.CursorRange;
7191
7192 // Scan the tokens that are at the end of the cursor, but are not captured
7193 // but the child cursors.
7194 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7195
7196 // Scan the tokens that are at the beginning of the cursor, but are not
7197 // capture by the child cursors.
7198 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7199 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7200 break;
7201
7202 Cursors[I] = cursor;
7203 }
7204
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007205 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7206 // encountered the attribute cursor.
7207 if (clang_isAttribute(cursor.kind))
7208 TokIdx = Info.BeforeReachingCursorIdx;
7209
Guy Benyei11169dd2012-12-18 14:30:41 +00007210 PostChildrenInfos.pop_back();
7211 return false;
7212}
7213
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007214void AnnotateTokensWorker::HandlePostPonedChildCursors(
7215 const PostChildrenInfo &Info) {
7216 for (const auto &ChildAction : Info.ChildActions) {
7217 if (ChildAction.action == PostChildrenAction::Postpone) {
7218 HandlePostPonedChildCursor(ChildAction.cursor,
7219 Info.BeforeChildrenTokenIdx);
7220 }
7221 }
7222}
7223
7224void AnnotateTokensWorker::HandlePostPonedChildCursor(
7225 CXCursor Cursor, unsigned StartTokenIndex) {
7226 const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier;
7227 unsigned I = StartTokenIndex;
7228
7229 // The bracket tokens of a Call or Subscript operator are mapped to
7230 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7231 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7232 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
7233 const CXSourceRange CXRefNameRange =
7234 clang_getCursorReferenceNameRange(Cursor, flags, RefNameRangeNr);
7235 if (clang_Range_isNull(CXRefNameRange))
7236 break; // All ranges handled.
7237
7238 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7239 while (I < NumTokens) {
7240 const SourceLocation TokenLocation = GetTokenLoc(I);
7241 if (!TokenLocation.isValid())
7242 break;
7243
7244 // Adapt the end range, because LocationCompare() reports
7245 // RangeOverlap even for the not-inclusive end location.
7246 const SourceLocation fixedEnd =
7247 RefNameRange.getEnd().getLocWithOffset(-1);
7248 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7249
7250 const RangeComparisonResult ComparisonResult =
7251 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7252
7253 if (ComparisonResult == RangeOverlap) {
7254 Cursors[I++] = Cursor;
7255 } else if (ComparisonResult == RangeBefore) {
7256 ++I; // Not relevant token, check next one.
7257 } else if (ComparisonResult == RangeAfter) {
7258 break; // All tokens updated for current range, check next.
7259 }
7260 }
7261 }
7262}
7263
Guy Benyei11169dd2012-12-18 14:30:41 +00007264static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7265 CXCursor parent,
7266 CXClientData client_data) {
7267 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7268}
7269
7270static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7271 CXClientData client_data) {
7272 return static_cast<AnnotateTokensWorker*>(client_data)->
7273 postVisitChildren(cursor);
7274}
7275
7276namespace {
7277
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007278/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007279/// and mark tokens that are macro arguments. This info is used by the
7280/// AnnotateTokensWorker.
7281class MarkMacroArgTokensVisitor {
7282 SourceManager &SM;
7283 CXToken *Tokens;
7284 unsigned NumTokens;
7285 unsigned CurIdx;
7286
7287public:
7288 MarkMacroArgTokensVisitor(SourceManager &SM,
7289 CXToken *tokens, unsigned numTokens)
7290 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7291
7292 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7293 if (cursor.kind != CXCursor_MacroExpansion)
7294 return CXChildVisit_Continue;
7295
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007296 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007297 if (macroRange.getBegin() == macroRange.getEnd())
7298 return CXChildVisit_Continue; // it's not a function macro.
7299
7300 for (; CurIdx < NumTokens; ++CurIdx) {
7301 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7302 macroRange.getBegin()))
7303 break;
7304 }
7305
7306 if (CurIdx == NumTokens)
7307 return CXChildVisit_Break;
7308
7309 for (; CurIdx < NumTokens; ++CurIdx) {
7310 SourceLocation tokLoc = getTokenLoc(CurIdx);
7311 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7312 break;
7313
7314 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7315 }
7316
7317 if (CurIdx == NumTokens)
7318 return CXChildVisit_Break;
7319
7320 return CXChildVisit_Continue;
7321 }
7322
7323private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007324 CXToken &getTok(unsigned Idx) {
7325 assert(Idx < NumTokens);
7326 return Tokens[Idx];
7327 }
7328 const CXToken &getTok(unsigned Idx) const {
7329 assert(Idx < NumTokens);
7330 return Tokens[Idx];
7331 }
7332
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007334 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007335 }
7336
7337 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7338 // The third field is reserved and currently not used. Use it here
7339 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007340 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007341 }
7342};
7343
7344} // end anonymous namespace
7345
7346static CXChildVisitResult
7347MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7348 CXClientData client_data) {
7349 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7350 parent);
7351}
7352
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007353/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007354/// \returns true if lexing was finished, false otherwise.
7355static bool lexNext(Lexer &Lex, Token &Tok,
7356 unsigned &NextIdx, unsigned NumTokens) {
7357 if (NextIdx >= NumTokens)
7358 return true;
7359
7360 ++NextIdx;
7361 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007362 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007363}
7364
Guy Benyei11169dd2012-12-18 14:30:41 +00007365static void annotatePreprocessorTokens(CXTranslationUnit TU,
7366 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007367 CXCursor *Cursors,
7368 CXToken *Tokens,
7369 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007370 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007371
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007372 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007373 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7374 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007375 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007376 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007377 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007378
7379 if (BeginLocInfo.first != EndLocInfo.first)
7380 return;
7381
7382 StringRef Buffer;
7383 bool Invalid = false;
7384 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7385 if (Buffer.empty() || Invalid)
7386 return;
7387
7388 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7389 CXXUnit->getASTContext().getLangOpts(),
7390 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7391 Buffer.end());
7392 Lex.SetCommentRetentionState(true);
7393
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007394 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007395 // Lex tokens in raw mode until we hit the end of the range, to avoid
7396 // entering #includes or expanding macros.
7397 while (true) {
7398 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007399 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7400 break;
7401 unsigned TokIdx = NextIdx-1;
7402 assert(Tok.getLocation() ==
7403 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007404
7405 reprocess:
7406 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007407 // We have found a preprocessing directive. Annotate the tokens
7408 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007409 //
7410 // FIXME: Some simple tests here could identify macro definitions and
7411 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007412
7413 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007414 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7415 break;
7416
Craig Topper69186e72014-06-08 08:38:04 +00007417 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007418 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007419 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7420 break;
7421
7422 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007423 IdentifierInfo &II =
7424 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007425 SourceLocation MappedTokLoc =
7426 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7427 MI = getMacroInfo(II, MappedTokLoc, TU);
7428 }
7429 }
7430
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007431 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007432 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007433 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7434 finished = true;
7435 break;
7436 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007437 // If we are in a macro definition, check if the token was ever a
7438 // macro name and annotate it if that's the case.
7439 if (MI) {
7440 SourceLocation SaveLoc = Tok.getLocation();
7441 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007442 MacroDefinitionRecord *MacroDef =
7443 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007444 Tok.setLocation(SaveLoc);
7445 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007446 Cursors[NextIdx - 1] =
7447 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007448 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007449 } while (!Tok.isAtStartOfLine());
7450
7451 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7452 assert(TokIdx <= LastIdx);
7453 SourceLocation EndLoc =
7454 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7455 CXCursor Cursor =
7456 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7457
7458 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007459 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007460
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007461 if (finished)
7462 break;
7463 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007464 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007465 }
7466}
7467
7468// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007469static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7470 CXToken *Tokens, unsigned NumTokens,
7471 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007472 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007473 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7474 setThreadBackgroundPriority();
7475
7476 // Determine the region of interest, which contains all of the tokens.
7477 SourceRange RegionOfInterest;
7478 RegionOfInterest.setBegin(
7479 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7480 RegionOfInterest.setEnd(
7481 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7482 Tokens[NumTokens-1])));
7483
Guy Benyei11169dd2012-12-18 14:30:41 +00007484 // Relex the tokens within the source range to look for preprocessing
7485 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007486 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007487
7488 // If begin location points inside a macro argument, set it to the expansion
7489 // location so we can have the full context when annotating semantically.
7490 {
7491 SourceManager &SM = CXXUnit->getSourceManager();
7492 SourceLocation Loc =
7493 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7494 if (Loc.isMacroID())
7495 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7496 }
7497
Guy Benyei11169dd2012-12-18 14:30:41 +00007498 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7499 // Search and mark tokens that are macro argument expansions.
7500 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7501 Tokens, NumTokens);
7502 CursorVisitor MacroArgMarker(TU,
7503 MarkMacroArgTokensVisitorDelegate, &Visitor,
7504 /*VisitPreprocessorLast=*/true,
7505 /*VisitIncludedEntities=*/false,
7506 RegionOfInterest);
7507 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7508 }
7509
7510 // Annotate all of the source locations in the region of interest that map to
7511 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007512 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007513
7514 // FIXME: We use a ridiculous stack size here because the data-recursion
7515 // algorithm uses a large stack frame than the non-data recursive version,
7516 // and AnnotationTokensWorker currently transforms the data-recursion
7517 // algorithm back into a traditional recursion by explicitly calling
7518 // VisitChildren(). We will need to remove this explicit recursive call.
7519 W.AnnotateTokens();
7520
7521 // If we ran into any entities that involve context-sensitive keywords,
7522 // take another pass through the tokens to mark them as such.
7523 if (W.hasContextSensitiveKeywords()) {
7524 for (unsigned I = 0; I != NumTokens; ++I) {
7525 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7526 continue;
7527
7528 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7529 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007530 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007531 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7532 if (Property->getPropertyAttributesAsWritten() != 0 &&
7533 llvm::StringSwitch<bool>(II->getName())
7534 .Case("readonly", true)
7535 .Case("assign", true)
7536 .Case("unsafe_unretained", true)
7537 .Case("readwrite", true)
7538 .Case("retain", true)
7539 .Case("copy", true)
7540 .Case("nonatomic", true)
7541 .Case("atomic", true)
7542 .Case("getter", true)
7543 .Case("setter", true)
7544 .Case("strong", true)
7545 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007546 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007547 .Default(false))
7548 Tokens[I].int_data[0] = CXToken_Keyword;
7549 }
7550 continue;
7551 }
7552
7553 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7554 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7555 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7556 if (llvm::StringSwitch<bool>(II->getName())
7557 .Case("in", true)
7558 .Case("out", true)
7559 .Case("inout", true)
7560 .Case("oneway", true)
7561 .Case("bycopy", true)
7562 .Case("byref", true)
7563 .Default(false))
7564 Tokens[I].int_data[0] = CXToken_Keyword;
7565 continue;
7566 }
7567
7568 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7569 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7570 Tokens[I].int_data[0] = CXToken_Keyword;
7571 continue;
7572 }
7573 }
7574 }
7575}
7576
Guy Benyei11169dd2012-12-18 14:30:41 +00007577void clang_annotateTokens(CXTranslationUnit TU,
7578 CXToken *Tokens, unsigned NumTokens,
7579 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007580 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007581 LOG_BAD_TU(TU);
7582 return;
7583 }
7584 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007585 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007586 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007587 }
7588
7589 LOG_FUNC_SECTION {
7590 *Log << TU << ' ';
7591 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7592 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7593 *Log << clang_getRange(bloc, eloc);
7594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007595
7596 // Any token we don't specifically annotate will have a NULL cursor.
7597 CXCursor C = clang_getNullCursor();
7598 for (unsigned I = 0; I != NumTokens; ++I)
7599 Cursors[I] = C;
7600
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007601 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007602 if (!CXXUnit)
7603 return;
7604
7605 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007606
7607 auto AnnotateTokensImpl = [=]() {
7608 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7609 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007610 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007611 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007612 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7613 }
7614}
7615
Guy Benyei11169dd2012-12-18 14:30:41 +00007616//===----------------------------------------------------------------------===//
7617// Operations for querying linkage of a cursor.
7618//===----------------------------------------------------------------------===//
7619
Guy Benyei11169dd2012-12-18 14:30:41 +00007620CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7621 if (!clang_isDeclaration(cursor.kind))
7622 return CXLinkage_Invalid;
7623
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007624 const Decl *D = cxcursor::getCursorDecl(cursor);
7625 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007626 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007627 case NoLinkage:
7628 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007629 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007630 case InternalLinkage: return CXLinkage_Internal;
7631 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007632 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007633 case ExternalLinkage: return CXLinkage_External;
7634 };
7635
7636 return CXLinkage_Invalid;
7637}
Guy Benyei11169dd2012-12-18 14:30:41 +00007638
7639//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007640// Operations for querying visibility of a cursor.
7641//===----------------------------------------------------------------------===//
7642
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007643CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7644 if (!clang_isDeclaration(cursor.kind))
7645 return CXVisibility_Invalid;
7646
7647 const Decl *D = cxcursor::getCursorDecl(cursor);
7648 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7649 switch (ND->getVisibility()) {
7650 case HiddenVisibility: return CXVisibility_Hidden;
7651 case ProtectedVisibility: return CXVisibility_Protected;
7652 case DefaultVisibility: return CXVisibility_Default;
7653 };
7654
7655 return CXVisibility_Invalid;
7656}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007657
7658//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007659// Operations for querying language of a cursor.
7660//===----------------------------------------------------------------------===//
7661
7662static CXLanguageKind getDeclLanguage(const Decl *D) {
7663 if (!D)
7664 return CXLanguage_C;
7665
7666 switch (D->getKind()) {
7667 default:
7668 break;
7669 case Decl::ImplicitParam:
7670 case Decl::ObjCAtDefsField:
7671 case Decl::ObjCCategory:
7672 case Decl::ObjCCategoryImpl:
7673 case Decl::ObjCCompatibleAlias:
7674 case Decl::ObjCImplementation:
7675 case Decl::ObjCInterface:
7676 case Decl::ObjCIvar:
7677 case Decl::ObjCMethod:
7678 case Decl::ObjCProperty:
7679 case Decl::ObjCPropertyImpl:
7680 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007681 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007682 return CXLanguage_ObjC;
7683 case Decl::CXXConstructor:
7684 case Decl::CXXConversion:
7685 case Decl::CXXDestructor:
7686 case Decl::CXXMethod:
7687 case Decl::CXXRecord:
7688 case Decl::ClassTemplate:
7689 case Decl::ClassTemplatePartialSpecialization:
7690 case Decl::ClassTemplateSpecialization:
7691 case Decl::Friend:
7692 case Decl::FriendTemplate:
7693 case Decl::FunctionTemplate:
7694 case Decl::LinkageSpec:
7695 case Decl::Namespace:
7696 case Decl::NamespaceAlias:
7697 case Decl::NonTypeTemplateParm:
7698 case Decl::StaticAssert:
7699 case Decl::TemplateTemplateParm:
7700 case Decl::TemplateTypeParm:
7701 case Decl::UnresolvedUsingTypename:
7702 case Decl::UnresolvedUsingValue:
7703 case Decl::Using:
7704 case Decl::UsingDirective:
7705 case Decl::UsingShadow:
7706 return CXLanguage_CPlusPlus;
7707 }
7708
7709 return CXLanguage_C;
7710}
7711
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007712static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7713 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007714 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007715
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007716 switch (D->getAvailability()) {
7717 case AR_Available:
7718 case AR_NotYetIntroduced:
7719 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007720 return getCursorAvailabilityForDecl(
7721 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007722 return CXAvailability_Available;
7723
7724 case AR_Deprecated:
7725 return CXAvailability_Deprecated;
7726
7727 case AR_Unavailable:
7728 return CXAvailability_NotAvailable;
7729 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007730
7731 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007732}
7733
Guy Benyei11169dd2012-12-18 14:30:41 +00007734enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7735 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007736 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7737 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007738
7739 return CXAvailability_Available;
7740}
7741
7742static CXVersion convertVersion(VersionTuple In) {
7743 CXVersion Out = { -1, -1, -1 };
7744 if (In.empty())
7745 return Out;
7746
7747 Out.Major = In.getMajor();
7748
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007749 Optional<unsigned> Minor = In.getMinor();
7750 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007751 Out.Minor = *Minor;
7752 else
7753 return Out;
7754
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007755 Optional<unsigned> Subminor = In.getSubminor();
7756 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 Out.Subminor = *Subminor;
7758
7759 return Out;
7760}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007761
Alex Lorenz1345ea22017-06-12 19:06:30 +00007762static void getCursorPlatformAvailabilityForDecl(
7763 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7764 int *always_unavailable, CXString *unavailable_message,
7765 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007766 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007767 for (auto A : D->attrs()) {
7768 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007769 HadAvailAttr = true;
7770 if (always_deprecated)
7771 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007772 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007773 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007774 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007775 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007776 continue;
7777 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007778
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007779 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007780 HadAvailAttr = true;
7781 if (always_unavailable)
7782 *always_unavailable = 1;
7783 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007784 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007785 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7786 }
7787 continue;
7788 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007789
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007790 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007791 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007792 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007793 }
7794 }
7795
7796 if (!HadAvailAttr)
7797 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7798 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007799 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7800 deprecated_message, always_unavailable, unavailable_message,
7801 AvailabilityAttrs);
7802
7803 if (AvailabilityAttrs.empty())
7804 return;
7805
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007806 llvm::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7807 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7808 return LHS->getPlatform()->getName() <
7809 RHS->getPlatform()->getName();
Alex Lorenz1345ea22017-06-12 19:06:30 +00007810 });
7811 ASTContext &Ctx = D->getASTContext();
7812 auto It = std::unique(
7813 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7814 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7815 if (LHS->getPlatform() != RHS->getPlatform())
7816 return false;
7817
7818 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7819 LHS->getDeprecated() == RHS->getDeprecated() &&
7820 LHS->getObsoleted() == RHS->getObsoleted() &&
7821 LHS->getMessage() == RHS->getMessage() &&
7822 LHS->getReplacement() == RHS->getReplacement())
7823 return true;
7824
7825 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7826 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7827 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7828 return false;
7829
7830 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7831 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7832
7833 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7834 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7835 if (LHS->getMessage().empty())
7836 LHS->setMessage(Ctx, RHS->getMessage());
7837 if (LHS->getReplacement().empty())
7838 LHS->setReplacement(Ctx, RHS->getReplacement());
7839 }
7840
7841 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7842 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7843 if (LHS->getMessage().empty())
7844 LHS->setMessage(Ctx, RHS->getMessage());
7845 if (LHS->getReplacement().empty())
7846 LHS->setReplacement(Ctx, RHS->getReplacement());
7847 }
7848
7849 return true;
7850 });
7851 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007852}
7853
Alex Lorenz1345ea22017-06-12 19:06:30 +00007854int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007855 CXString *deprecated_message,
7856 int *always_unavailable,
7857 CXString *unavailable_message,
7858 CXPlatformAvailability *availability,
7859 int availability_size) {
7860 if (always_deprecated)
7861 *always_deprecated = 0;
7862 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007863 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007864 if (always_unavailable)
7865 *always_unavailable = 0;
7866 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007867 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007868
Guy Benyei11169dd2012-12-18 14:30:41 +00007869 if (!clang_isDeclaration(cursor.kind))
7870 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007871
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007872 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007873 if (!D)
7874 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007875
Alex Lorenz1345ea22017-06-12 19:06:30 +00007876 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7877 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7878 always_unavailable, unavailable_message,
7879 AvailabilityAttrs);
7880 for (const auto &Avail :
7881 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7882 .take_front(availability_size))) {
7883 availability[Avail.index()].Platform =
7884 cxstring::createDup(Avail.value()->getPlatform()->getName());
7885 availability[Avail.index()].Introduced =
7886 convertVersion(Avail.value()->getIntroduced());
7887 availability[Avail.index()].Deprecated =
7888 convertVersion(Avail.value()->getDeprecated());
7889 availability[Avail.index()].Obsoleted =
7890 convertVersion(Avail.value()->getObsoleted());
7891 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7892 availability[Avail.index()].Message =
7893 cxstring::createDup(Avail.value()->getMessage());
7894 }
7895
7896 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007897}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007898
Guy Benyei11169dd2012-12-18 14:30:41 +00007899void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7900 clang_disposeString(availability->Platform);
7901 clang_disposeString(availability->Message);
7902}
7903
7904CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7905 if (clang_isDeclaration(cursor.kind))
7906 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7907
7908 return CXLanguage_Invalid;
7909}
7910
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007911CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7912 const Decl *D = cxcursor::getCursorDecl(cursor);
7913 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7914 switch (VD->getTLSKind()) {
7915 case VarDecl::TLS_None:
7916 return CXTLS_None;
7917 case VarDecl::TLS_Dynamic:
7918 return CXTLS_Dynamic;
7919 case VarDecl::TLS_Static:
7920 return CXTLS_Static;
7921 }
7922 }
7923
7924 return CXTLS_None;
7925}
7926
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007927 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007928 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007929 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007930static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007931 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007932 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007933
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007934 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007935 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7936 return FunTmpl;
7937
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007938 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007939 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7940 return ClassTmpl;
7941
7942 return D;
7943}
7944
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007945
7946enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7947 StorageClass sc = SC_None;
7948 const Decl *D = getCursorDecl(C);
7949 if (D) {
7950 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7951 sc = FD->getStorageClass();
7952 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7953 sc = VD->getStorageClass();
7954 } else {
7955 return CX_SC_Invalid;
7956 }
7957 } else {
7958 return CX_SC_Invalid;
7959 }
7960 switch (sc) {
7961 case SC_None:
7962 return CX_SC_None;
7963 case SC_Extern:
7964 return CX_SC_Extern;
7965 case SC_Static:
7966 return CX_SC_Static;
7967 case SC_PrivateExtern:
7968 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007969 case SC_Auto:
7970 return CX_SC_Auto;
7971 case SC_Register:
7972 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007973 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007974 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007975}
7976
Guy Benyei11169dd2012-12-18 14:30:41 +00007977CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7978 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007979 if (const Decl *D = getCursorDecl(cursor)) {
7980 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 if (!DC)
7982 return clang_getNullCursor();
7983
7984 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7985 getCursorTU(cursor));
7986 }
7987 }
7988
7989 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007990 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007991 return MakeCXCursor(D, getCursorTU(cursor));
7992 }
7993
7994 return clang_getNullCursor();
7995}
7996
7997CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7998 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007999 if (const Decl *D = getCursorDecl(cursor)) {
8000 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 if (!DC)
8002 return clang_getNullCursor();
8003
8004 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8005 getCursorTU(cursor));
8006 }
8007 }
8008
8009 // FIXME: Note that we can't easily compute the lexical context of a
8010 // statement or expression, so we return nothing.
8011 return clang_getNullCursor();
8012}
8013
8014CXFile clang_getIncludedFile(CXCursor cursor) {
8015 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008016 return nullptr;
8017
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008018 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008019 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008020}
8021
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008022unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8023 if (C.kind != CXCursor_ObjCPropertyDecl)
8024 return CXObjCPropertyAttr_noattr;
8025
8026 unsigned Result = CXObjCPropertyAttr_noattr;
8027 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8028 ObjCPropertyDecl::PropertyAttributeKind Attr =
8029 PD->getPropertyAttributesAsWritten();
8030
8031#define SET_CXOBJCPROP_ATTR(A) \
8032 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8033 Result |= CXObjCPropertyAttr_##A
8034 SET_CXOBJCPROP_ATTR(readonly);
8035 SET_CXOBJCPROP_ATTR(getter);
8036 SET_CXOBJCPROP_ATTR(assign);
8037 SET_CXOBJCPROP_ATTR(readwrite);
8038 SET_CXOBJCPROP_ATTR(retain);
8039 SET_CXOBJCPROP_ATTR(copy);
8040 SET_CXOBJCPROP_ATTR(nonatomic);
8041 SET_CXOBJCPROP_ATTR(setter);
8042 SET_CXOBJCPROP_ATTR(atomic);
8043 SET_CXOBJCPROP_ATTR(weak);
8044 SET_CXOBJCPROP_ATTR(strong);
8045 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008046 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008047#undef SET_CXOBJCPROP_ATTR
8048
8049 return Result;
8050}
8051
Michael Wu6e88f532018-08-03 05:38:29 +00008052CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8053 if (C.kind != CXCursor_ObjCPropertyDecl)
8054 return cxstring::createNull();
8055
8056 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8057 Selector sel = PD->getGetterName();
8058 if (sel.isNull())
8059 return cxstring::createNull();
8060
8061 return cxstring::createDup(sel.getAsString());
8062}
8063
8064CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8065 if (C.kind != CXCursor_ObjCPropertyDecl)
8066 return cxstring::createNull();
8067
8068 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8069 Selector sel = PD->getSetterName();
8070 if (sel.isNull())
8071 return cxstring::createNull();
8072
8073 return cxstring::createDup(sel.getAsString());
8074}
8075
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008076unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8077 if (!clang_isDeclaration(C.kind))
8078 return CXObjCDeclQualifier_None;
8079
8080 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8081 const Decl *D = getCursorDecl(C);
8082 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8083 QT = MD->getObjCDeclQualifier();
8084 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8085 QT = PD->getObjCDeclQualifier();
8086 if (QT == Decl::OBJC_TQ_None)
8087 return CXObjCDeclQualifier_None;
8088
8089 unsigned Result = CXObjCDeclQualifier_None;
8090 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8091 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8092 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8093 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8094 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8095 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8096
8097 return Result;
8098}
8099
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008100unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8101 if (!clang_isDeclaration(C.kind))
8102 return 0;
8103
8104 const Decl *D = getCursorDecl(C);
8105 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8106 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8107 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8108 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8109
8110 return 0;
8111}
8112
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008113unsigned clang_Cursor_isVariadic(CXCursor C) {
8114 if (!clang_isDeclaration(C.kind))
8115 return 0;
8116
8117 const Decl *D = getCursorDecl(C);
8118 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8119 return FD->isVariadic();
8120 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8121 return MD->isVariadic();
8122
8123 return 0;
8124}
8125
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008126unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8127 CXString *language, CXString *definedIn,
8128 unsigned *isGenerated) {
8129 if (!clang_isDeclaration(C.kind))
8130 return 0;
8131
8132 const Decl *D = getCursorDecl(C);
8133
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008134 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008135 if (language)
8136 *language = cxstring::createDup(attr->getLanguage());
8137 if (definedIn)
8138 *definedIn = cxstring::createDup(attr->getDefinedIn());
8139 if (isGenerated)
8140 *isGenerated = attr->getGeneratedDeclaration();
8141 return 1;
8142 }
8143 return 0;
8144}
8145
Guy Benyei11169dd2012-12-18 14:30:41 +00008146CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8147 if (!clang_isDeclaration(C.kind))
8148 return clang_getNullRange();
8149
8150 const Decl *D = getCursorDecl(C);
8151 ASTContext &Context = getCursorContext(C);
8152 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8153 if (!RC)
8154 return clang_getNullRange();
8155
8156 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8157}
8158
8159CXString clang_Cursor_getRawCommentText(CXCursor C) {
8160 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008161 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008162
8163 const Decl *D = getCursorDecl(C);
8164 ASTContext &Context = getCursorContext(C);
8165 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8166 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8167 StringRef();
8168
8169 // Don't duplicate the string because RawText points directly into source
8170 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008171 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008172}
8173
8174CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8175 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008176 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008177
8178 const Decl *D = getCursorDecl(C);
8179 const ASTContext &Context = getCursorContext(C);
8180 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8181
8182 if (RC) {
8183 StringRef BriefText = RC->getBriefText(Context);
8184
8185 // Don't duplicate the string because RawComment ensures that this memory
8186 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008187 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008188 }
8189
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008190 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008191}
8192
Guy Benyei11169dd2012-12-18 14:30:41 +00008193CXModule clang_Cursor_getModule(CXCursor C) {
8194 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008195 if (const ImportDecl *ImportD =
8196 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008197 return ImportD->getImportedModule();
8198 }
8199
Craig Topper69186e72014-06-08 08:38:04 +00008200 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008201}
8202
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008203CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8204 if (isNotUsableTU(TU)) {
8205 LOG_BAD_TU(TU);
8206 return nullptr;
8207 }
8208 if (!File)
8209 return nullptr;
8210 FileEntry *FE = static_cast<FileEntry *>(File);
8211
8212 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8213 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8214 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8215
Richard Smithfeb54b62014-10-23 02:01:19 +00008216 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008217}
8218
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008219CXFile clang_Module_getASTFile(CXModule CXMod) {
8220 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008221 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008222 Module *Mod = static_cast<Module*>(CXMod);
8223 return const_cast<FileEntry *>(Mod->getASTFile());
8224}
8225
Guy Benyei11169dd2012-12-18 14:30:41 +00008226CXModule clang_Module_getParent(CXModule CXMod) {
8227 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008228 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008229 Module *Mod = static_cast<Module*>(CXMod);
8230 return Mod->Parent;
8231}
8232
8233CXString clang_Module_getName(CXModule CXMod) {
8234 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008235 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008237 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008238}
8239
8240CXString clang_Module_getFullName(CXModule CXMod) {
8241 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008242 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008243 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008244 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008245}
8246
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008247int clang_Module_isSystem(CXModule CXMod) {
8248 if (!CXMod)
8249 return 0;
8250 Module *Mod = static_cast<Module*>(CXMod);
8251 return Mod->IsSystem;
8252}
8253
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008254unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8255 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008256 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008257 LOG_BAD_TU(TU);
8258 return 0;
8259 }
8260 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008261 return 0;
8262 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008263 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8264 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8265 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008266}
8267
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008268CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8269 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008270 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008271 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008272 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008273 }
8274 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008275 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008276 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008277 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008278
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008279 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8280 if (Index < TopHeaders.size())
8281 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008282
Craig Topper69186e72014-06-08 08:38:04 +00008283 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008284}
8285
Guy Benyei11169dd2012-12-18 14:30:41 +00008286//===----------------------------------------------------------------------===//
8287// C++ AST instrospection.
8288//===----------------------------------------------------------------------===//
8289
Jonathan Coe29565352016-04-27 12:48:25 +00008290unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8291 if (!clang_isDeclaration(C.kind))
8292 return 0;
8293
8294 const Decl *D = cxcursor::getCursorDecl(C);
8295 const CXXConstructorDecl *Constructor =
8296 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8297 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8298}
8299
8300unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8301 if (!clang_isDeclaration(C.kind))
8302 return 0;
8303
8304 const Decl *D = cxcursor::getCursorDecl(C);
8305 const CXXConstructorDecl *Constructor =
8306 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8307 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8308}
8309
8310unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8311 if (!clang_isDeclaration(C.kind))
8312 return 0;
8313
8314 const Decl *D = cxcursor::getCursorDecl(C);
8315 const CXXConstructorDecl *Constructor =
8316 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8317 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8318}
8319
8320unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8321 if (!clang_isDeclaration(C.kind))
8322 return 0;
8323
8324 const Decl *D = cxcursor::getCursorDecl(C);
8325 const CXXConstructorDecl *Constructor =
8326 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8327 // Passing 'false' excludes constructors marked 'explicit'.
8328 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8329}
8330
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008331unsigned clang_CXXField_isMutable(CXCursor C) {
8332 if (!clang_isDeclaration(C.kind))
8333 return 0;
8334
8335 if (const auto D = cxcursor::getCursorDecl(C))
8336 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8337 return FD->isMutable() ? 1 : 0;
8338 return 0;
8339}
8340
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008341unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8342 if (!clang_isDeclaration(C.kind))
8343 return 0;
8344
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008345 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008346 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008347 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008348 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8349}
8350
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008351unsigned clang_CXXMethod_isConst(CXCursor C) {
8352 if (!clang_isDeclaration(C.kind))
8353 return 0;
8354
8355 const Decl *D = cxcursor::getCursorDecl(C);
8356 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008357 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008358 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
8359}
8360
Jonathan Coe29565352016-04-27 12:48:25 +00008361unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8362 if (!clang_isDeclaration(C.kind))
8363 return 0;
8364
8365 const Decl *D = cxcursor::getCursorDecl(C);
8366 const CXXMethodDecl *Method =
8367 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8368 return (Method && Method->isDefaulted()) ? 1 : 0;
8369}
8370
Guy Benyei11169dd2012-12-18 14:30:41 +00008371unsigned clang_CXXMethod_isStatic(CXCursor C) {
8372 if (!clang_isDeclaration(C.kind))
8373 return 0;
8374
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008375 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008376 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008377 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008378 return (Method && Method->isStatic()) ? 1 : 0;
8379}
8380
8381unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8382 if (!clang_isDeclaration(C.kind))
8383 return 0;
8384
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008385 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008386 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008387 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008388 return (Method && Method->isVirtual()) ? 1 : 0;
8389}
Guy Benyei11169dd2012-12-18 14:30:41 +00008390
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008391unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8392 if (!clang_isDeclaration(C.kind))
8393 return 0;
8394
8395 const auto *D = cxcursor::getCursorDecl(C);
8396 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8397 if (RD)
8398 RD = RD->getDefinition();
8399 return (RD && RD->isAbstract()) ? 1 : 0;
8400}
8401
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008402unsigned clang_EnumDecl_isScoped(CXCursor C) {
8403 if (!clang_isDeclaration(C.kind))
8404 return 0;
8405
8406 const Decl *D = cxcursor::getCursorDecl(C);
8407 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8408 return (Enum && Enum->isScoped()) ? 1 : 0;
8409}
8410
Guy Benyei11169dd2012-12-18 14:30:41 +00008411//===----------------------------------------------------------------------===//
8412// Attribute introspection.
8413//===----------------------------------------------------------------------===//
8414
Guy Benyei11169dd2012-12-18 14:30:41 +00008415CXType clang_getIBOutletCollectionType(CXCursor C) {
8416 if (C.kind != CXCursor_IBOutletCollectionAttr)
8417 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8418
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008419 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008420 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8421
8422 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8423}
Guy Benyei11169dd2012-12-18 14:30:41 +00008424
8425//===----------------------------------------------------------------------===//
8426// Inspecting memory usage.
8427//===----------------------------------------------------------------------===//
8428
8429typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8430
8431static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8432 enum CXTUResourceUsageKind k,
8433 unsigned long amount) {
8434 CXTUResourceUsageEntry entry = { k, amount };
8435 entries.push_back(entry);
8436}
8437
Guy Benyei11169dd2012-12-18 14:30:41 +00008438const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8439 const char *str = "";
8440 switch (kind) {
8441 case CXTUResourceUsage_AST:
8442 str = "ASTContext: expressions, declarations, and types";
8443 break;
8444 case CXTUResourceUsage_Identifiers:
8445 str = "ASTContext: identifiers";
8446 break;
8447 case CXTUResourceUsage_Selectors:
8448 str = "ASTContext: selectors";
8449 break;
8450 case CXTUResourceUsage_GlobalCompletionResults:
8451 str = "Code completion: cached global results";
8452 break;
8453 case CXTUResourceUsage_SourceManagerContentCache:
8454 str = "SourceManager: content cache allocator";
8455 break;
8456 case CXTUResourceUsage_AST_SideTables:
8457 str = "ASTContext: side tables";
8458 break;
8459 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8460 str = "SourceManager: malloc'ed memory buffers";
8461 break;
8462 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8463 str = "SourceManager: mmap'ed memory buffers";
8464 break;
8465 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8466 str = "ExternalASTSource: malloc'ed memory buffers";
8467 break;
8468 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8469 str = "ExternalASTSource: mmap'ed memory buffers";
8470 break;
8471 case CXTUResourceUsage_Preprocessor:
8472 str = "Preprocessor: malloc'ed memory";
8473 break;
8474 case CXTUResourceUsage_PreprocessingRecord:
8475 str = "Preprocessor: PreprocessingRecord";
8476 break;
8477 case CXTUResourceUsage_SourceManager_DataStructures:
8478 str = "SourceManager: data structures and tables";
8479 break;
8480 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8481 str = "Preprocessor: header search tables";
8482 break;
8483 }
8484 return str;
8485}
8486
8487CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008488 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008489 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008490 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008491 return usage;
8492 }
8493
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008494 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008495 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008496 ASTContext &astContext = astUnit->getASTContext();
8497
8498 // How much memory is used by AST nodes and types?
8499 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8500 (unsigned long) astContext.getASTAllocatedMemory());
8501
8502 // How much memory is used by identifiers?
8503 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8504 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8505
8506 // How much memory is used for selectors?
8507 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8508 (unsigned long) astContext.Selectors.getTotalMemory());
8509
8510 // How much memory is used by ASTContext's side tables?
8511 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8512 (unsigned long) astContext.getSideTableAllocatedMemory());
8513
8514 // How much memory is used for caching global code completion results?
8515 unsigned long completionBytes = 0;
8516 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008517 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008518 completionBytes = completionAllocator->getTotalMemory();
8519 }
8520 createCXTUResourceUsageEntry(*entries,
8521 CXTUResourceUsage_GlobalCompletionResults,
8522 completionBytes);
8523
8524 // How much memory is being used by SourceManager's content cache?
8525 createCXTUResourceUsageEntry(*entries,
8526 CXTUResourceUsage_SourceManagerContentCache,
8527 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8528
8529 // How much memory is being used by the MemoryBuffer's in SourceManager?
8530 const SourceManager::MemoryBufferSizes &srcBufs =
8531 astUnit->getSourceManager().getMemoryBufferSizes();
8532
8533 createCXTUResourceUsageEntry(*entries,
8534 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8535 (unsigned long) srcBufs.malloc_bytes);
8536 createCXTUResourceUsageEntry(*entries,
8537 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8538 (unsigned long) srcBufs.mmap_bytes);
8539 createCXTUResourceUsageEntry(*entries,
8540 CXTUResourceUsage_SourceManager_DataStructures,
8541 (unsigned long) astContext.getSourceManager()
8542 .getDataStructureSizes());
8543
8544 // How much memory is being used by the ExternalASTSource?
8545 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8546 const ExternalASTSource::MemoryBufferSizes &sizes =
8547 esrc->getMemoryBufferSizes();
8548
8549 createCXTUResourceUsageEntry(*entries,
8550 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8551 (unsigned long) sizes.malloc_bytes);
8552 createCXTUResourceUsageEntry(*entries,
8553 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8554 (unsigned long) sizes.mmap_bytes);
8555 }
8556
8557 // How much memory is being used by the Preprocessor?
8558 Preprocessor &pp = astUnit->getPreprocessor();
8559 createCXTUResourceUsageEntry(*entries,
8560 CXTUResourceUsage_Preprocessor,
8561 pp.getTotalMemory());
8562
8563 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8564 createCXTUResourceUsageEntry(*entries,
8565 CXTUResourceUsage_PreprocessingRecord,
8566 pRec->getTotalMemory());
8567 }
8568
8569 createCXTUResourceUsageEntry(*entries,
8570 CXTUResourceUsage_Preprocessor_HeaderSearch,
8571 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008572
Guy Benyei11169dd2012-12-18 14:30:41 +00008573 CXTUResourceUsage usage = { (void*) entries.get(),
8574 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008575 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008576 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008577 return usage;
8578}
8579
8580void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8581 if (usage.data)
8582 delete (MemUsageEntries*) usage.data;
8583}
8584
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008585CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8586 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008587 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008588 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008589
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008590 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008591 LOG_BAD_TU(TU);
8592 return skipped;
8593 }
8594
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008595 if (!file)
8596 return skipped;
8597
8598 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8599 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8600 if (!ppRec)
8601 return skipped;
8602
8603 ASTContext &Ctx = astUnit->getASTContext();
8604 SourceManager &sm = Ctx.getSourceManager();
8605 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8606 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008607 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008608
8609 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8610 std::vector<SourceRange> wantedRanges;
8611 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8612 i != ei; ++i) {
8613 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8614 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008615 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8616 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008617 }
8618
8619 skipped->count = wantedRanges.size();
8620 skipped->ranges = new CXSourceRange[skipped->count];
8621 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8622 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8623
8624 return skipped;
8625}
8626
Cameron Desrochersd8091282016-08-18 15:43:55 +00008627CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8628 CXSourceRangeList *skipped = new CXSourceRangeList;
8629 skipped->count = 0;
8630 skipped->ranges = nullptr;
8631
8632 if (isNotUsableTU(TU)) {
8633 LOG_BAD_TU(TU);
8634 return skipped;
8635 }
8636
8637 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8638 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8639 if (!ppRec)
8640 return skipped;
8641
8642 ASTContext &Ctx = astUnit->getASTContext();
8643
8644 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8645
8646 skipped->count = SkippedRanges.size();
8647 skipped->ranges = new CXSourceRange[skipped->count];
8648 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8649 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8650
8651 return skipped;
8652}
8653
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008654void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8655 if (ranges) {
8656 delete[] ranges->ranges;
8657 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008658 }
8659}
8660
Guy Benyei11169dd2012-12-18 14:30:41 +00008661void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8662 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8663 for (unsigned I = 0; I != Usage.numEntries; ++I)
8664 fprintf(stderr, " %s: %lu\n",
8665 clang_getTUResourceUsageName(Usage.entries[I].kind),
8666 Usage.entries[I].amount);
8667
8668 clang_disposeCXTUResourceUsage(Usage);
8669}
8670
8671//===----------------------------------------------------------------------===//
8672// Misc. utility functions.
8673//===----------------------------------------------------------------------===//
8674
Richard Smith0a7b2972018-07-03 21:34:13 +00008675/// Default to using our desired 8 MB stack size on "safety" threads.
8676static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008677
8678namespace clang {
8679
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008680bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008681 unsigned Size) {
8682 if (!Size)
8683 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008684 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008685 return CRC.RunSafelyOnThread(Fn, Size);
8686 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008687}
8688
8689unsigned GetSafetyThreadStackSize() {
8690 return SafetyStackThreadSize;
8691}
8692
8693void SetSafetyThreadStackSize(unsigned Value) {
8694 SafetyStackThreadSize = Value;
8695}
8696
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008697}
Guy Benyei11169dd2012-12-18 14:30:41 +00008698
8699void clang::setThreadBackgroundPriority() {
8700 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8701 return;
8702
Alp Toker1a86ad22014-07-06 06:24:00 +00008703#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008704 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8705#endif
8706}
8707
8708void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8709 if (!Unit)
8710 return;
8711
8712 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8713 DEnd = Unit->stored_diag_end();
8714 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008715 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008716 CXString Msg = clang_formatDiagnostic(&Diag,
8717 clang_defaultDiagnosticDisplayOptions());
8718 fprintf(stderr, "%s\n", clang_getCString(Msg));
8719 clang_disposeString(Msg);
8720 }
Nico Weber1865df42018-04-27 19:11:14 +00008721#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008722 // On Windows, force a flush, since there may be multiple copies of
8723 // stderr and stdout in the file system, all with different buffers
8724 // but writing to the same device.
8725 fflush(stderr);
8726#endif
8727}
8728
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008729MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8730 SourceLocation MacroDefLoc,
8731 CXTranslationUnit TU){
8732 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008733 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008734 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008735 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008736
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008737 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008738 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008739 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008740 if (MD) {
8741 for (MacroDirective::DefInfo
8742 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8743 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8744 return Def.getMacroInfo();
8745 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008746 }
8747
Craig Topper69186e72014-06-08 08:38:04 +00008748 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008749}
8750
Richard Smith66a81862015-05-04 02:25:31 +00008751const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008752 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008753 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008754 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008755 const IdentifierInfo *II = MacroDef->getName();
8756 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008757 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008758
8759 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8760}
8761
Richard Smith66a81862015-05-04 02:25:31 +00008762MacroDefinitionRecord *
8763cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8764 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008765 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008766 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008767 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008768 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008769
8770 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008771 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008772 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8773 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008774 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008775
8776 // Check that the token is inside the definition and not its argument list.
8777 SourceManager &SM = Unit->getSourceManager();
8778 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008779 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008780 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008781 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008782
8783 Preprocessor &PP = Unit->getPreprocessor();
8784 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8785 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008786 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008787
Alp Toker2d57cea2014-05-17 04:53:25 +00008788 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008789 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008790 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008791
8792 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008793 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008794 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008795
Richard Smith20e883e2015-04-29 23:20:19 +00008796 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008797 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008798 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008799
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008800 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008801}
8802
Richard Smith66a81862015-05-04 02:25:31 +00008803MacroDefinitionRecord *
8804cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8805 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008806 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008807 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008808
8809 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008810 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008811 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008812 Preprocessor &PP = Unit->getPreprocessor();
8813 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008814 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008815 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8816 Token Tok;
8817 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008818 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008819
8820 return checkForMacroInMacroDefinition(MI, Tok, TU);
8821}
8822
Guy Benyei11169dd2012-12-18 14:30:41 +00008823CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008824 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008825}
8826
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008827Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8828 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008829 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008830 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008831 if (Unit->isMainFileAST())
8832 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008833 return *this;
8834 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008835 } else {
8836 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008837 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008838 return *this;
8839}
8840
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008841Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8842 *this << FE->getName();
8843 return *this;
8844}
8845
8846Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8847 CXString cursorName = clang_getCursorDisplayName(cursor);
8848 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8849 clang_disposeString(cursorName);
8850 return *this;
8851}
8852
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008853Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8854 CXFile File;
8855 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008856 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008857 CXString FileName = clang_getFileName(File);
8858 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8859 clang_disposeString(FileName);
8860 return *this;
8861}
8862
8863Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8864 CXSourceLocation BLoc = clang_getRangeStart(range);
8865 CXSourceLocation ELoc = clang_getRangeEnd(range);
8866
8867 CXFile BFile;
8868 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008869 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008870
8871 CXFile EFile;
8872 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008873 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008874
8875 CXString BFileName = clang_getFileName(BFile);
8876 if (BFile == EFile) {
8877 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8878 BLine, BColumn, ELine, EColumn);
8879 } else {
8880 CXString EFileName = clang_getFileName(EFile);
8881 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8882 BLine, BColumn)
8883 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8884 ELine, EColumn);
8885 clang_disposeString(EFileName);
8886 }
8887 clang_disposeString(BFileName);
8888 return *this;
8889}
8890
8891Logger &cxindex::Logger::operator<<(CXString Str) {
8892 *this << clang_getCString(Str);
8893 return *this;
8894}
8895
8896Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8897 LogOS << Fmt;
8898 return *this;
8899}
8900
Chandler Carruth37ad2582014-06-27 15:14:39 +00008901static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8902
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008903cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008904 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008905
8906 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8907
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008908 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008909 OS << "[libclang:" << Name << ':';
8910
Alp Toker1a86ad22014-07-06 06:24:00 +00008911#ifdef USE_DARWIN_THREADS
8912 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008913 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8914 OS << tid << ':';
8915#endif
8916
8917 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8918 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008919 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008920
8921 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008922 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008923 OS << "--------------------------------------------------\n";
8924 }
8925}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008926
8927#ifdef CLANG_TOOL_EXTRA_BUILD
8928// This anchor is used to force the linker to link the clang-tidy plugin.
8929extern volatile int ClangTidyPluginAnchorSource;
8930static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8931 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008932
8933// This anchor is used to force the linker to link the clang-include-fixer
8934// plugin.
8935extern volatile int ClangIncludeFixerPluginAnchorSource;
8936static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8937 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008938#endif