blob: d104edd82d46e9f5d9869ff94410d41f56f33894 [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.
Fangrui Song55fab262018-09-26 22:16:28 +00001047 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001048 [&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
Patrick Lyster4a370b92018-10-01 13:47:43 +00002213void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2214 const OMPUnifiedSharedMemoryClause *) {}
2215
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002216void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2217 const OMPReverseOffloadClause *) {}
2218
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002219void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2220 const OMPDynamicAllocatorsClause *) {}
2221
Michael Wonge710d542015-08-07 16:16:36 +00002222void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2223 Visitor->AddStmt(C->getDevice());
2224}
2225
Kelvin Li099bb8c2015-11-24 20:50:12 +00002226void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002227 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002228 Visitor->AddStmt(C->getNumTeams());
2229}
2230
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002231void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002232 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002233 Visitor->AddStmt(C->getThreadLimit());
2234}
2235
Alexey Bataeva0569352015-12-01 10:17:31 +00002236void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2237 Visitor->AddStmt(C->getPriority());
2238}
2239
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002240void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2241 Visitor->AddStmt(C->getGrainsize());
2242}
2243
Alexey Bataev382967a2015-12-08 12:06:20 +00002244void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2245 Visitor->AddStmt(C->getNumTasks());
2246}
2247
Alexey Bataev28c75412015-12-15 08:19:24 +00002248void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2249 Visitor->AddStmt(C->getHint());
2250}
2251
Alexey Bataev756c1962013-09-24 03:17:45 +00002252template<typename T>
2253void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002254 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002255 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002256 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002257}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002258
2259void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002260 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002261 for (const auto *E : C->private_copies()) {
2262 Visitor->AddStmt(E);
2263 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002264}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002265void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2266 const OMPFirstprivateClause *C) {
2267 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002268 VisitOMPClauseWithPreInit(C);
2269 for (const auto *E : C->private_copies()) {
2270 Visitor->AddStmt(E);
2271 }
2272 for (const auto *E : C->inits()) {
2273 Visitor->AddStmt(E);
2274 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002275}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002276void OMPClauseEnqueue::VisitOMPLastprivateClause(
2277 const OMPLastprivateClause *C) {
2278 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002279 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002280 for (auto *E : C->private_copies()) {
2281 Visitor->AddStmt(E);
2282 }
2283 for (auto *E : C->source_exprs()) {
2284 Visitor->AddStmt(E);
2285 }
2286 for (auto *E : C->destination_exprs()) {
2287 Visitor->AddStmt(E);
2288 }
2289 for (auto *E : C->assignment_ops()) {
2290 Visitor->AddStmt(E);
2291 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002292}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002293void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002294 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002295}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002296void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2297 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002298 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002299 for (auto *E : C->privates()) {
2300 Visitor->AddStmt(E);
2301 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002302 for (auto *E : C->lhs_exprs()) {
2303 Visitor->AddStmt(E);
2304 }
2305 for (auto *E : C->rhs_exprs()) {
2306 Visitor->AddStmt(E);
2307 }
2308 for (auto *E : C->reduction_ops()) {
2309 Visitor->AddStmt(E);
2310 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002311}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002312void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2313 const OMPTaskReductionClause *C) {
2314 VisitOMPClauseList(C);
2315 VisitOMPClauseWithPostUpdate(C);
2316 for (auto *E : C->privates()) {
2317 Visitor->AddStmt(E);
2318 }
2319 for (auto *E : C->lhs_exprs()) {
2320 Visitor->AddStmt(E);
2321 }
2322 for (auto *E : C->rhs_exprs()) {
2323 Visitor->AddStmt(E);
2324 }
2325 for (auto *E : C->reduction_ops()) {
2326 Visitor->AddStmt(E);
2327 }
2328}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002329void OMPClauseEnqueue::VisitOMPInReductionClause(
2330 const OMPInReductionClause *C) {
2331 VisitOMPClauseList(C);
2332 VisitOMPClauseWithPostUpdate(C);
2333 for (auto *E : C->privates()) {
2334 Visitor->AddStmt(E);
2335 }
2336 for (auto *E : C->lhs_exprs()) {
2337 Visitor->AddStmt(E);
2338 }
2339 for (auto *E : C->rhs_exprs()) {
2340 Visitor->AddStmt(E);
2341 }
2342 for (auto *E : C->reduction_ops()) {
2343 Visitor->AddStmt(E);
2344 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002345 for (auto *E : C->taskgroup_descriptors())
2346 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002347}
Alexander Musman8dba6642014-04-22 13:09:42 +00002348void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2349 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002350 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002351 for (const auto *E : C->privates()) {
2352 Visitor->AddStmt(E);
2353 }
Alexander Musman3276a272015-03-21 10:12:56 +00002354 for (const auto *E : C->inits()) {
2355 Visitor->AddStmt(E);
2356 }
2357 for (const auto *E : C->updates()) {
2358 Visitor->AddStmt(E);
2359 }
2360 for (const auto *E : C->finals()) {
2361 Visitor->AddStmt(E);
2362 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002363 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002364 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002365}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002366void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2367 VisitOMPClauseList(C);
2368 Visitor->AddStmt(C->getAlignment());
2369}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002370void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2371 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002372 for (auto *E : C->source_exprs()) {
2373 Visitor->AddStmt(E);
2374 }
2375 for (auto *E : C->destination_exprs()) {
2376 Visitor->AddStmt(E);
2377 }
2378 for (auto *E : C->assignment_ops()) {
2379 Visitor->AddStmt(E);
2380 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002381}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002382void
2383OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2384 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002385 for (auto *E : C->source_exprs()) {
2386 Visitor->AddStmt(E);
2387 }
2388 for (auto *E : C->destination_exprs()) {
2389 Visitor->AddStmt(E);
2390 }
2391 for (auto *E : C->assignment_ops()) {
2392 Visitor->AddStmt(E);
2393 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002394}
Alexey Bataev6125da92014-07-21 11:26:11 +00002395void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2396 VisitOMPClauseList(C);
2397}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002398void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2399 VisitOMPClauseList(C);
2400}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002401void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2402 VisitOMPClauseList(C);
2403}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002404void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2405 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002406 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002407 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002408}
Alexey Bataev3392d762016-02-16 11:18:12 +00002409void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2410 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002411void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2412 VisitOMPClauseList(C);
2413}
Samuel Antaoec172c62016-05-26 17:49:04 +00002414void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2415 VisitOMPClauseList(C);
2416}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002417void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2418 VisitOMPClauseList(C);
2419}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002420void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2421 VisitOMPClauseList(C);
2422}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002423}
Alexey Bataev756c1962013-09-24 03:17:45 +00002424
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002425void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2426 unsigned size = WL.size();
2427 OMPClauseEnqueue Visitor(this);
2428 Visitor.Visit(S);
2429 if (size == WL.size())
2430 return;
2431 // Now reverse the entries we just added. This will match the DFS
2432 // ordering performed by the worklist.
2433 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2434 std::reverse(I, E);
2435}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002436void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2438}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002439void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 AddDecl(B->getBlockDecl());
2441}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002442void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 EnqueueChildren(E);
2444 AddTypeLoc(E->getTypeSourceInfo());
2445}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002446void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002447 for (auto &I : llvm::reverse(S->body()))
2448 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002449}
2450void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002451VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 AddStmt(S->getSubStmt());
2453 AddDeclarationNameInfo(S);
2454 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2455 AddNestedNameSpecifierLoc(QualifierLoc);
2456}
2457
2458void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002459VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002460 if (E->hasExplicitTemplateArgs())
2461 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 AddDeclarationNameInfo(E);
2463 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2464 AddNestedNameSpecifierLoc(QualifierLoc);
2465 if (!E->isImplicitAccess())
2466 AddStmt(E->getBase());
2467}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002468void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 // Enqueue the initializer , if any.
2470 AddStmt(E->getInitializer());
2471 // Enqueue the array size, if any.
2472 AddStmt(E->getArraySize());
2473 // Enqueue the allocated type.
2474 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2475 // Enqueue the placement arguments.
2476 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2477 AddStmt(E->getPlacementArg(I-1));
2478}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002479void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2481 AddStmt(CE->getArg(I-1));
2482 AddStmt(CE->getCallee());
2483 AddStmt(CE->getArg(0));
2484}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002485void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2486 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 // Visit the name of the type being destroyed.
2488 AddTypeLoc(E->getDestroyedTypeInfo());
2489 // Visit the scope type that looks disturbingly like the nested-name-specifier
2490 // but isn't.
2491 AddTypeLoc(E->getScopeTypeInfo());
2492 // Visit the nested-name-specifier.
2493 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2494 AddNestedNameSpecifierLoc(QualifierLoc);
2495 // Visit base expression.
2496 AddStmt(E->getBase());
2497}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002498void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2499 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 AddTypeLoc(E->getTypeSourceInfo());
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2503 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 EnqueueChildren(E);
2505 AddTypeLoc(E->getTypeSourceInfo());
2506}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002507void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 EnqueueChildren(E);
2509 if (E->isTypeOperand())
2510 AddTypeLoc(E->getTypeOperandSourceInfo());
2511}
2512
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002513void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2514 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 EnqueueChildren(E);
2516 AddTypeLoc(E->getTypeSourceInfo());
2517}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002518void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 EnqueueChildren(E);
2520 if (E->isTypeOperand())
2521 AddTypeLoc(E->getTypeOperandSourceInfo());
2522}
2523
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002524void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 EnqueueChildren(S);
2526 AddDecl(S->getExceptionDecl());
2527}
2528
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002529void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002530 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002531 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002532 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002533}
2534
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002535void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002536 if (DR->hasExplicitTemplateArgs())
2537 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 WL.push_back(DeclRefExprParts(DR, Parent));
2539}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002540void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2541 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002542 if (E->hasExplicitTemplateArgs())
2543 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 AddDeclarationNameInfo(E);
2545 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2546}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002547void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 unsigned size = WL.size();
2549 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002550 for (const auto *D : S->decls()) {
2551 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 isFirst = false;
2553 }
2554 if (size == WL.size())
2555 return;
2556 // Now reverse the entries we just added. This will match the DFS
2557 // ordering performed by the worklist.
2558 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2559 std::reverse(I, E);
2560}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002561void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002563 for (const DesignatedInitExpr::Designator &D :
2564 llvm::reverse(E->designators())) {
2565 if (D.isFieldDesignator()) {
2566 if (FieldDecl *Field = D.getField())
2567 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 continue;
2569 }
David Majnemerf7e36092016-06-23 00:15:04 +00002570 if (D.isArrayDesignator()) {
2571 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 continue;
2573 }
David Majnemerf7e36092016-06-23 00:15:04 +00002574 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2575 AddStmt(E->getArrayRangeEnd(D));
2576 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 }
2578}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002579void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 EnqueueChildren(E);
2581 AddTypeLoc(E->getTypeInfoAsWritten());
2582}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002583void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 AddStmt(FS->getBody());
2585 AddStmt(FS->getInc());
2586 AddStmt(FS->getCond());
2587 AddDecl(FS->getConditionVariable());
2588 AddStmt(FS->getInit());
2589}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002590void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2592}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002593void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 AddStmt(If->getElse());
2595 AddStmt(If->getThen());
2596 AddStmt(If->getCond());
2597 AddDecl(If->getConditionVariable());
2598}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002599void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 // We care about the syntactic form of the initializer list, only.
2601 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2602 IE = Syntactic;
2603 EnqueueChildren(IE);
2604}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002605void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 WL.push_back(MemberExprParts(M, Parent));
2607
2608 // If the base of the member access expression is an implicit 'this', don't
2609 // visit it.
2610 // FIXME: If we ever want to show these implicit accesses, this will be
2611 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002612 if (M->isImplicitAccess())
2613 return;
2614
2615 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002616 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002617 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2618 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2619 if (FD->isAnonymousStructOrUnion()) {
2620 AddStmt(SubME->getBase());
2621 return;
2622 }
2623 }
2624 }
2625
2626 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002627}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002628void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 AddTypeLoc(E->getEncodedTypeSourceInfo());
2630}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002631void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002632 EnqueueChildren(M);
2633 AddTypeLoc(M->getClassReceiverTypeInfo());
2634}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002635void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 // Visit the components of the offsetof expression.
2637 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 const OffsetOfNode &Node = E->getComponent(I-1);
2639 switch (Node.getKind()) {
2640 case OffsetOfNode::Array:
2641 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2642 break;
2643 case OffsetOfNode::Field:
2644 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2645 break;
2646 case OffsetOfNode::Identifier:
2647 case OffsetOfNode::Base:
2648 continue;
2649 }
2650 }
2651 // Visit the type into which we're computing the offset.
2652 AddTypeLoc(E->getTypeSourceInfo());
2653}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002654void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002655 if (E->hasExplicitTemplateArgs())
2656 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 WL.push_back(OverloadExprParts(E, Parent));
2658}
2659void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002660 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 EnqueueChildren(E);
2662 if (E->isArgumentType())
2663 AddTypeLoc(E->getArgumentTypeInfo());
2664}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002665void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 EnqueueChildren(S);
2667}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002668void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 AddStmt(S->getBody());
2670 AddStmt(S->getCond());
2671 AddDecl(S->getConditionVariable());
2672}
2673
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002674void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 AddStmt(W->getBody());
2676 AddStmt(W->getCond());
2677 AddDecl(W->getConditionVariable());
2678}
2679
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002680void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 for (unsigned I = E->getNumArgs(); I > 0; --I)
2682 AddTypeLoc(E->getArg(I-1));
2683}
2684
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002685void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 AddTypeLoc(E->getQueriedTypeSourceInfo());
2687}
2688
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002689void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 EnqueueChildren(E);
2691}
2692
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002693void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 VisitOverloadExpr(U);
2695 if (!U->isImplicitAccess())
2696 AddStmt(U->getBase());
2697}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002698void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 AddStmt(E->getSubExpr());
2700 AddTypeLoc(E->getWrittenTypeInfo());
2701}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002702void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 WL.push_back(SizeOfPackExprParts(E, Parent));
2704}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002705void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 // If the opaque value has a source expression, just transparently
2707 // visit that. This is useful for (e.g.) pseudo-object expressions.
2708 if (Expr *SourceExpr = E->getSourceExpr())
2709 return Visit(SourceExpr);
2710}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002711void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 AddStmt(E->getBody());
2713 WL.push_back(LambdaExprParts(E, Parent));
2714}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002715void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 // Treat the expression like its syntactic form.
2717 Visit(E->getSyntacticForm());
2718}
2719
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002720void EnqueueVisitor::VisitOMPExecutableDirective(
2721 const OMPExecutableDirective *D) {
2722 EnqueueChildren(D);
2723 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2724 E = D->clauses().end();
2725 I != E; ++I)
2726 EnqueueChildren(*I);
2727}
2728
Alexander Musman3aaab662014-08-19 11:27:13 +00002729void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2730 VisitOMPExecutableDirective(D);
2731}
2732
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002733void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2734 VisitOMPExecutableDirective(D);
2735}
2736
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002737void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002738 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002739}
2740
Alexey Bataevf29276e2014-06-18 04:14:57 +00002741void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002742 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002743}
2744
Alexander Musmanf82886e2014-09-18 05:12:34 +00002745void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2746 VisitOMPLoopDirective(D);
2747}
2748
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002749void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2750 VisitOMPExecutableDirective(D);
2751}
2752
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002753void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2754 VisitOMPExecutableDirective(D);
2755}
2756
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002757void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2758 VisitOMPExecutableDirective(D);
2759}
2760
Alexander Musman80c22892014-07-17 08:54:58 +00002761void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2762 VisitOMPExecutableDirective(D);
2763}
2764
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002765void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2766 VisitOMPExecutableDirective(D);
2767 AddDeclarationNameInfo(D);
2768}
2769
Alexey Bataev4acb8592014-07-07 13:01:15 +00002770void
2771EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002772 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002773}
2774
Alexander Musmane4e893b2014-09-23 09:33:00 +00002775void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2776 const OMPParallelForSimdDirective *D) {
2777 VisitOMPLoopDirective(D);
2778}
2779
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002780void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2781 const OMPParallelSectionsDirective *D) {
2782 VisitOMPExecutableDirective(D);
2783}
2784
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002785void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2786 VisitOMPExecutableDirective(D);
2787}
2788
Alexey Bataev68446b72014-07-18 07:47:19 +00002789void
2790EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2791 VisitOMPExecutableDirective(D);
2792}
2793
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002794void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2795 VisitOMPExecutableDirective(D);
2796}
2797
Alexey Bataev2df347a2014-07-18 10:17:07 +00002798void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2799 VisitOMPExecutableDirective(D);
2800}
2801
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002802void EnqueueVisitor::VisitOMPTaskgroupDirective(
2803 const OMPTaskgroupDirective *D) {
2804 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002805 if (const Expr *E = D->getReductionRef())
2806 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002807}
2808
Alexey Bataev6125da92014-07-21 11:26:11 +00002809void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2810 VisitOMPExecutableDirective(D);
2811}
2812
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002813void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2814 VisitOMPExecutableDirective(D);
2815}
2816
Alexey Bataev0162e452014-07-22 10:10:35 +00002817void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819}
2820
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002821void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2822 VisitOMPExecutableDirective(D);
2823}
2824
Michael Wong65f367f2015-07-21 13:44:28 +00002825void EnqueueVisitor::VisitOMPTargetDataDirective(const
2826 OMPTargetDataDirective *D) {
2827 VisitOMPExecutableDirective(D);
2828}
2829
Samuel Antaodf67fc42016-01-19 19:15:56 +00002830void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2831 const OMPTargetEnterDataDirective *D) {
2832 VisitOMPExecutableDirective(D);
2833}
2834
Samuel Antao72590762016-01-19 20:04:50 +00002835void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2836 const OMPTargetExitDataDirective *D) {
2837 VisitOMPExecutableDirective(D);
2838}
2839
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002840void EnqueueVisitor::VisitOMPTargetParallelDirective(
2841 const OMPTargetParallelDirective *D) {
2842 VisitOMPExecutableDirective(D);
2843}
2844
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002845void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2846 const OMPTargetParallelForDirective *D) {
2847 VisitOMPLoopDirective(D);
2848}
2849
Alexey Bataev13314bf2014-10-09 04:18:56 +00002850void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2851 VisitOMPExecutableDirective(D);
2852}
2853
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002854void EnqueueVisitor::VisitOMPCancellationPointDirective(
2855 const OMPCancellationPointDirective *D) {
2856 VisitOMPExecutableDirective(D);
2857}
2858
Alexey Bataev80909872015-07-02 11:25:17 +00002859void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2860 VisitOMPExecutableDirective(D);
2861}
2862
Alexey Bataev49f6e782015-12-01 04:18:41 +00002863void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2864 VisitOMPLoopDirective(D);
2865}
2866
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002867void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2868 const OMPTaskLoopSimdDirective *D) {
2869 VisitOMPLoopDirective(D);
2870}
2871
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002872void EnqueueVisitor::VisitOMPDistributeDirective(
2873 const OMPDistributeDirective *D) {
2874 VisitOMPLoopDirective(D);
2875}
2876
Carlo Bertolli9925f152016-06-27 14:55:37 +00002877void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2878 const OMPDistributeParallelForDirective *D) {
2879 VisitOMPLoopDirective(D);
2880}
2881
Kelvin Li4a39add2016-07-05 05:00:15 +00002882void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2883 const OMPDistributeParallelForSimdDirective *D) {
2884 VisitOMPLoopDirective(D);
2885}
2886
Kelvin Li787f3fc2016-07-06 04:45:38 +00002887void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2888 const OMPDistributeSimdDirective *D) {
2889 VisitOMPLoopDirective(D);
2890}
2891
Kelvin Lia579b912016-07-14 02:54:56 +00002892void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2893 const OMPTargetParallelForSimdDirective *D) {
2894 VisitOMPLoopDirective(D);
2895}
2896
Kelvin Li986330c2016-07-20 22:57:10 +00002897void EnqueueVisitor::VisitOMPTargetSimdDirective(
2898 const OMPTargetSimdDirective *D) {
2899 VisitOMPLoopDirective(D);
2900}
2901
Kelvin Li02532872016-08-05 14:37:37 +00002902void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2903 const OMPTeamsDistributeDirective *D) {
2904 VisitOMPLoopDirective(D);
2905}
2906
Kelvin Li4e325f72016-10-25 12:50:55 +00002907void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2908 const OMPTeamsDistributeSimdDirective *D) {
2909 VisitOMPLoopDirective(D);
2910}
2911
Kelvin Li579e41c2016-11-30 23:51:03 +00002912void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2913 const OMPTeamsDistributeParallelForSimdDirective *D) {
2914 VisitOMPLoopDirective(D);
2915}
2916
Kelvin Li7ade93f2016-12-09 03:24:30 +00002917void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2918 const OMPTeamsDistributeParallelForDirective *D) {
2919 VisitOMPLoopDirective(D);
2920}
2921
Kelvin Libf594a52016-12-17 05:48:59 +00002922void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2923 const OMPTargetTeamsDirective *D) {
2924 VisitOMPExecutableDirective(D);
2925}
2926
Kelvin Li83c451e2016-12-25 04:52:54 +00002927void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2928 const OMPTargetTeamsDistributeDirective *D) {
2929 VisitOMPLoopDirective(D);
2930}
2931
Kelvin Li80e8f562016-12-29 22:16:30 +00002932void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2933 const OMPTargetTeamsDistributeParallelForDirective *D) {
2934 VisitOMPLoopDirective(D);
2935}
2936
Kelvin Li1851df52017-01-03 05:23:48 +00002937void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2938 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2939 VisitOMPLoopDirective(D);
2940}
2941
Kelvin Lida681182017-01-10 18:08:18 +00002942void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2943 const OMPTargetTeamsDistributeSimdDirective *D) {
2944 VisitOMPLoopDirective(D);
2945}
2946
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002947void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2949}
2950
2951bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2952 if (RegionOfInterest.isValid()) {
2953 SourceRange Range = getRawCursorExtent(C);
2954 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2955 return false;
2956 }
2957 return true;
2958}
2959
2960bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2961 while (!WL.empty()) {
2962 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002963 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002964
2965 // Set the Parent field, then back to its old value once we're done.
2966 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2967
2968 switch (LI.getKind()) {
2969 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002970 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 if (!D)
2972 continue;
2973
2974 // For now, perform default visitation for Decls.
2975 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2976 cast<DeclVisit>(&LI)->isFirst())))
2977 return true;
2978
2979 continue;
2980 }
2981 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002982 for (const TemplateArgumentLoc &Arg :
2983 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2984 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002985 return true;
2986 }
2987 continue;
2988 }
2989 case VisitorJob::TypeLocVisitKind: {
2990 // Perform default visitation for TypeLocs.
2991 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2992 return true;
2993 continue;
2994 }
2995 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002996 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002997 if (LabelStmt *stmt = LS->getStmt()) {
2998 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2999 TU))) {
3000 return true;
3001 }
3002 }
3003 continue;
3004 }
3005
3006 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3007 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3008 if (VisitNestedNameSpecifierLoc(V->get()))
3009 return true;
3010 continue;
3011 }
3012
3013 case VisitorJob::DeclarationNameInfoVisitKind: {
3014 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3015 ->get()))
3016 return true;
3017 continue;
3018 }
3019 case VisitorJob::MemberRefVisitKind: {
3020 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3021 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3022 return true;
3023 continue;
3024 }
3025 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003026 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 if (!S)
3028 continue;
3029
3030 // Update the current cursor.
3031 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3032 if (!IsInRegionOfInterest(Cursor))
3033 continue;
3034 switch (Visitor(Cursor, Parent, ClientData)) {
3035 case CXChildVisit_Break: return true;
3036 case CXChildVisit_Continue: break;
3037 case CXChildVisit_Recurse:
3038 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003039 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003040 EnqueueWorkList(WL, S);
3041 break;
3042 }
3043 continue;
3044 }
3045 case VisitorJob::MemberExprPartsKind: {
3046 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003047 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003048
3049 // Visit the nested-name-specifier
3050 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3051 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3052 return true;
3053
3054 // Visit the declaration name.
3055 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3056 return true;
3057
3058 // Visit the explicitly-specified template arguments, if any.
3059 if (M->hasExplicitTemplateArgs()) {
3060 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3061 *ArgEnd = Arg + M->getNumTemplateArgs();
3062 Arg != ArgEnd; ++Arg) {
3063 if (VisitTemplateArgumentLoc(*Arg))
3064 return true;
3065 }
3066 }
3067 continue;
3068 }
3069 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003070 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 // Visit nested-name-specifier, if present.
3072 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3073 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3074 return true;
3075 // Visit declaration name.
3076 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3077 return true;
3078 continue;
3079 }
3080 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003081 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 // Visit the nested-name-specifier.
3083 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3084 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3085 return true;
3086 // Visit the declaration name.
3087 if (VisitDeclarationNameInfo(O->getNameInfo()))
3088 return true;
3089 // Visit the overloaded declaration reference.
3090 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3091 return true;
3092 continue;
3093 }
3094 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003095 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 NamedDecl *Pack = E->getPack();
3097 if (isa<TemplateTypeParmDecl>(Pack)) {
3098 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3099 E->getPackLoc(), TU)))
3100 return true;
3101
3102 continue;
3103 }
3104
3105 if (isa<TemplateTemplateParmDecl>(Pack)) {
3106 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3107 E->getPackLoc(), TU)))
3108 return true;
3109
3110 continue;
3111 }
3112
3113 // Non-type template parameter packs and function parameter packs are
3114 // treated like DeclRefExpr cursors.
3115 continue;
3116 }
3117
3118 case VisitorJob::LambdaExprPartsKind: {
3119 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003120 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3122 CEnd = E->explicit_capture_end();
3123 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003124 // FIXME: Lambda init-captures.
3125 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003127
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3129 C->getLocation(),
3130 TU)))
3131 return true;
3132 }
3133
3134 // Visit parameters and return type, if present.
3135 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3136 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3137 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3138 // Visit the whole type.
3139 if (Visit(TL))
3140 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003141 } else if (FunctionProtoTypeLoc Proto =
3142 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 if (E->hasExplicitParameters()) {
3144 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003145 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3146 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 return true;
3148 } else {
3149 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003150 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 return true;
3152 }
3153 }
3154 }
3155 break;
3156 }
3157
3158 case VisitorJob::PostChildrenVisitKind:
3159 if (PostChildrenVisitor(Parent, ClientData))
3160 return true;
3161 break;
3162 }
3163 }
3164 return false;
3165}
3166
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003167bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003168 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 if (!WorkListFreeList.empty()) {
3170 WL = WorkListFreeList.back();
3171 WL->clear();
3172 WorkListFreeList.pop_back();
3173 }
3174 else {
3175 WL = new VisitorWorkList();
3176 WorkListCache.push_back(WL);
3177 }
3178 EnqueueWorkList(*WL, S);
3179 bool result = RunVisitorWorkList(*WL);
3180 WorkListFreeList.push_back(WL);
3181 return result;
3182}
3183
3184namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003185typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003186RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3187 const DeclarationNameInfo &NI, SourceRange QLoc,
3188 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003189 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3190 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3191 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3192
3193 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3194
3195 RefNamePieces Pieces;
3196
3197 if (WantQualifier && QLoc.isValid())
3198 Pieces.push_back(QLoc);
3199
3200 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3201 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003202
3203 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3204 Pieces.push_back(*TemplateArgsLoc);
3205
Guy Benyei11169dd2012-12-18 14:30:41 +00003206 if (Kind == DeclarationName::CXXOperatorName) {
3207 Pieces.push_back(SourceLocation::getFromRawEncoding(
3208 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3209 Pieces.push_back(SourceLocation::getFromRawEncoding(
3210 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3211 }
3212
3213 if (WantSinglePiece) {
3214 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3215 Pieces.clear();
3216 Pieces.push_back(R);
3217 }
3218
3219 return Pieces;
3220}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003221}
Guy Benyei11169dd2012-12-18 14:30:41 +00003222
3223//===----------------------------------------------------------------------===//
3224// Misc. API hooks.
3225//===----------------------------------------------------------------------===//
3226
Chad Rosier05c71aa2013-03-27 18:28:23 +00003227static void fatal_error_handler(void *user_data, const std::string& reason,
3228 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 // Write the result out to stderr avoiding errs() because raw_ostreams can
3230 // call report_fatal_error.
3231 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3232 ::abort();
3233}
3234
Chandler Carruth66660742014-06-27 16:37:27 +00003235namespace {
3236struct RegisterFatalErrorHandler {
3237 RegisterFatalErrorHandler() {
3238 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3239 }
3240};
3241}
3242
3243static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3244
Guy Benyei11169dd2012-12-18 14:30:41 +00003245CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3246 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003247 // We use crash recovery to make some of our APIs more reliable, implicitly
3248 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003249 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3250 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003251
Chandler Carruth66660742014-06-27 16:37:27 +00003252 // Look through the managed static to trigger construction of the managed
3253 // static which registers our fatal error handler. This ensures it is only
3254 // registered once.
3255 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003256
Adrian Prantlbc068582015-07-08 01:00:30 +00003257 // Initialize targets for clang module support.
3258 llvm::InitializeAllTargets();
3259 llvm::InitializeAllTargetMCs();
3260 llvm::InitializeAllAsmPrinters();
3261 llvm::InitializeAllAsmParsers();
3262
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003263 CIndexer *CIdxr = new CIndexer();
3264
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 if (excludeDeclarationsFromPCH)
3266 CIdxr->setOnlyLocalDecls();
3267 if (displayDiagnostics)
3268 CIdxr->setDisplayDiagnostics();
3269
3270 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3271 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3272 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3273 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3274 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3275 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3276
3277 return CIdxr;
3278}
3279
3280void clang_disposeIndex(CXIndex CIdx) {
3281 if (CIdx)
3282 delete static_cast<CIndexer *>(CIdx);
3283}
3284
3285void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3286 if (CIdx)
3287 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3288}
3289
3290unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3291 if (CIdx)
3292 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3293 return 0;
3294}
3295
Alex Lorenz08615792017-12-04 21:56:36 +00003296void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3297 const char *Path) {
3298 if (CIdx)
3299 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3300}
3301
Guy Benyei11169dd2012-12-18 14:30:41 +00003302void clang_toggleCrashRecovery(unsigned isEnabled) {
3303 if (isEnabled)
3304 llvm::CrashRecoveryContext::Enable();
3305 else
3306 llvm::CrashRecoveryContext::Disable();
3307}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003308
Guy Benyei11169dd2012-12-18 14:30:41 +00003309CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3310 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003311 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003312 enum CXErrorCode Result =
3313 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003314 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003315 assert((TU && Result == CXError_Success) ||
3316 (!TU && Result != CXError_Success));
3317 return TU;
3318}
3319
3320enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3321 const char *ast_filename,
3322 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003323 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003324 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003325
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003326 if (!CIdx || !ast_filename || !out_TU)
3327 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003328
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003329 LOG_FUNC_SECTION {
3330 *Log << ast_filename;
3331 }
3332
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3334 FileSystemOptions FileSystemOpts;
3335
Justin Bognerd512c1e2014-10-15 00:33:06 +00003336 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3337 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003338 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003339 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3340 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003341 FileSystemOpts, /*UseDebugInfo=*/false,
3342 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003343 /*CaptureDiagnostics=*/true,
3344 /*AllowPCHWithCompilerErrors=*/true,
3345 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003346 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003347 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003348}
3349
3350unsigned clang_defaultEditingTranslationUnitOptions() {
3351 return CXTranslationUnit_PrecompiledPreamble |
3352 CXTranslationUnit_CacheCompletionResults;
3353}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003354
Guy Benyei11169dd2012-12-18 14:30:41 +00003355CXTranslationUnit
3356clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3357 const char *source_filename,
3358 int num_command_line_args,
3359 const char * const *command_line_args,
3360 unsigned num_unsaved_files,
3361 struct CXUnsavedFile *unsaved_files) {
3362 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3363 return clang_parseTranslationUnit(CIdx, source_filename,
3364 command_line_args, num_command_line_args,
3365 unsaved_files, num_unsaved_files,
3366 Options);
3367}
3368
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003369static CXErrorCode
3370clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3371 const char *const *command_line_args,
3372 int num_command_line_args,
3373 ArrayRef<CXUnsavedFile> unsaved_files,
3374 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003375 // Set up the initial return values.
3376 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003377 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003378
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003379 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003380 if (!CIdx || !out_TU)
3381 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003382
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3384
3385 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3386 setThreadBackgroundPriority();
3387
3388 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003389 bool CreatePreambleOnFirstParse =
3390 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003391 // FIXME: Add a flag for modules.
3392 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003393 = (options & (CXTranslationUnit_Incomplete |
3394 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003395 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003396 = options & CXTranslationUnit_CacheCompletionResults;
3397 bool IncludeBriefCommentsInCodeCompletion
3398 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003399 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3400 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003401 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3402 if (options & CXTranslationUnit_SkipFunctionBodies) {
3403 SkipFunctionBodies =
3404 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3405 ? SkipFunctionBodiesScope::Preamble
3406 : SkipFunctionBodiesScope::PreambleAndMainFile;
3407 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003408
3409 // Configure the diagnostics.
3410 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003411 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003412
Manuel Klimek016c0242016-03-01 10:56:19 +00003413 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003414 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003415
Guy Benyei11169dd2012-12-18 14:30:41 +00003416 // Recover resources if we crash before exiting this function.
3417 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3418 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003419 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003420
Ahmed Charlesb8984322014-03-07 20:03:18 +00003421 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3422 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003423
3424 // Recover resources if we crash before exiting this function.
3425 llvm::CrashRecoveryContextCleanupRegistrar<
3426 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3427
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003428 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003429 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003430 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003431 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 }
3433
Ahmed Charlesb8984322014-03-07 20:03:18 +00003434 std::unique_ptr<std::vector<const char *>> Args(
3435 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003436
3437 // Recover resources if we crash before exiting this method.
3438 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3439 ArgsCleanup(Args.get());
3440
3441 // Since the Clang C library is primarily used by batch tools dealing with
3442 // (often very broken) source code, where spell-checking can have a
3443 // significant negative impact on performance (particularly when
3444 // precompiled headers are involved), we disable it by default.
3445 // Only do this if we haven't found a spell-checking-related argument.
3446 bool FoundSpellCheckingArgument = false;
3447 for (int I = 0; I != num_command_line_args; ++I) {
3448 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3449 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3450 FoundSpellCheckingArgument = true;
3451 break;
3452 }
3453 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003454 Args->insert(Args->end(), command_line_args,
3455 command_line_args + num_command_line_args);
3456
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003457 if (!FoundSpellCheckingArgument)
3458 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3459
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 // The 'source_filename' argument is optional. If the caller does not
3461 // specify it then it is assumed that the source file is specified
3462 // in the actual argument list.
3463 // Put the source file after command_line_args otherwise if '-x' flag is
3464 // present it will be unused.
3465 if (source_filename)
3466 Args->push_back(source_filename);
3467
3468 // Do we need the detailed preprocessing record?
3469 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3470 Args->push_back("-Xclang");
3471 Args->push_back("-detailed-preprocessing-record");
3472 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003473
3474 // Suppress any editor placeholder diagnostics.
3475 Args->push_back("-fallow-editor-placeholders");
3476
Guy Benyei11169dd2012-12-18 14:30:41 +00003477 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003478 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003479 // Unless the user specified that they want the preamble on the first parse
3480 // set it up to be created on the first reparse. This makes the first parse
3481 // faster, trading for a slower (first) reparse.
3482 unsigned PrecompilePreambleAfterNParses =
3483 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003484
Alex Lorenz08615792017-12-04 21:56:36 +00003485 LibclangInvocationReporter InvocationReporter(
3486 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003487 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3488 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003489 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003490 Args->data(), Args->data() + Args->size(),
3491 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003492 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3493 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003494 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3495 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003496 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003497 /*UserFilesAreVolatile=*/true, ForSerialization,
3498 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3499 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003500
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003501 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003502 if (!Unit && !ErrUnit)
3503 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003504
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 if (NumErrors != Diags->getClient()->getNumErrors()) {
3506 // Make sure to check that 'Unit' is non-NULL.
3507 if (CXXIdx->getDisplayDiagnostics())
3508 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3509 }
3510
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003511 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3512 return CXError_ASTReadError;
3513
David Blaikieea4395e2017-01-06 19:49:01 +00003514 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003515 if (CXTranslationUnitImpl *TU = *out_TU) {
3516 TU->ParsingOptions = options;
3517 TU->Arguments.reserve(Args->size());
3518 for (const char *Arg : *Args)
3519 TU->Arguments.push_back(Arg);
3520 return CXError_Success;
3521 }
3522 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003523}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003524
3525CXTranslationUnit
3526clang_parseTranslationUnit(CXIndex CIdx,
3527 const char *source_filename,
3528 const char *const *command_line_args,
3529 int num_command_line_args,
3530 struct CXUnsavedFile *unsaved_files,
3531 unsigned num_unsaved_files,
3532 unsigned options) {
3533 CXTranslationUnit TU;
3534 enum CXErrorCode Result = clang_parseTranslationUnit2(
3535 CIdx, source_filename, command_line_args, num_command_line_args,
3536 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003537 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003538 assert((TU && Result == CXError_Success) ||
3539 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003540 return TU;
3541}
3542
3543enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003544 CXIndex CIdx, const char *source_filename,
3545 const char *const *command_line_args, int num_command_line_args,
3546 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3547 unsigned options, CXTranslationUnit *out_TU) {
3548 SmallVector<const char *, 4> Args;
3549 Args.push_back("clang");
3550 Args.append(command_line_args, command_line_args + num_command_line_args);
3551 return clang_parseTranslationUnit2FullArgv(
3552 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3553 num_unsaved_files, options, out_TU);
3554}
3555
3556enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3557 CXIndex CIdx, const char *source_filename,
3558 const char *const *command_line_args, int num_command_line_args,
3559 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3560 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003561 LOG_FUNC_SECTION {
3562 *Log << source_filename << ": ";
3563 for (int i = 0; i != num_command_line_args; ++i)
3564 *Log << command_line_args[i] << " ";
3565 }
3566
Alp Toker9d85b182014-07-07 01:23:14 +00003567 if (num_unsaved_files && !unsaved_files)
3568 return CXError_InvalidArguments;
3569
Alp Toker5c532982014-07-07 22:42:03 +00003570 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003571 auto ParseTranslationUnitImpl = [=, &result] {
3572 result = clang_parseTranslationUnit_Impl(
3573 CIdx, source_filename, command_line_args, num_command_line_args,
3574 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3575 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003576
Guy Benyei11169dd2012-12-18 14:30:41 +00003577 llvm::CrashRecoveryContext CRC;
3578
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003579 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003580 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3581 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3582 fprintf(stderr, " 'command_line_args' : [");
3583 for (int i = 0; i != num_command_line_args; ++i) {
3584 if (i)
3585 fprintf(stderr, ", ");
3586 fprintf(stderr, "'%s'", command_line_args[i]);
3587 }
3588 fprintf(stderr, "],\n");
3589 fprintf(stderr, " 'unsaved_files' : [");
3590 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3591 if (i)
3592 fprintf(stderr, ", ");
3593 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3594 unsaved_files[i].Length);
3595 }
3596 fprintf(stderr, "],\n");
3597 fprintf(stderr, " 'options' : %d,\n", options);
3598 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003599
3600 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003601 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003602 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003603 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003604 }
Alp Toker5c532982014-07-07 22:42:03 +00003605
3606 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003607}
3608
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003609CXString clang_Type_getObjCEncoding(CXType CT) {
3610 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3611 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3612 std::string encoding;
3613 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3614 encoding);
3615
3616 return cxstring::createDup(encoding);
3617}
3618
3619static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3620 if (C.kind == CXCursor_MacroDefinition) {
3621 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3622 return MDR->getName();
3623 } else if (C.kind == CXCursor_MacroExpansion) {
3624 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3625 return ME.getName();
3626 }
3627 return nullptr;
3628}
3629
3630unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3631 const IdentifierInfo *II = getMacroIdentifier(C);
3632 if (!II) {
3633 return false;
3634 }
3635 ASTUnit *ASTU = getCursorASTUnit(C);
3636 Preprocessor &PP = ASTU->getPreprocessor();
3637 if (const MacroInfo *MI = PP.getMacroInfo(II))
3638 return MI->isFunctionLike();
3639 return false;
3640}
3641
3642unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3643 const IdentifierInfo *II = getMacroIdentifier(C);
3644 if (!II) {
3645 return false;
3646 }
3647 ASTUnit *ASTU = getCursorASTUnit(C);
3648 Preprocessor &PP = ASTU->getPreprocessor();
3649 if (const MacroInfo *MI = PP.getMacroInfo(II))
3650 return MI->isBuiltinMacro();
3651 return false;
3652}
3653
3654unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3655 const Decl *D = getCursorDecl(C);
3656 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3657 if (!FD) {
3658 return false;
3659 }
3660 return FD->isInlined();
3661}
3662
3663static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3664 if (callExpr->getNumArgs() != 1) {
3665 return nullptr;
3666 }
3667
3668 StringLiteral *S = nullptr;
3669 auto *arg = callExpr->getArg(0);
3670 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3671 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3672 auto *subExpr = I->getSubExprAsWritten();
3673
3674 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3675 return nullptr;
3676 }
3677
3678 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3679 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3680 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3681 } else {
3682 return nullptr;
3683 }
3684 return S;
3685}
3686
David Blaikie59272572016-04-13 18:23:33 +00003687struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003688 CXEvalResultKind EvalType;
3689 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003690 unsigned long long unsignedVal;
3691 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003692 double floatVal;
3693 char *stringVal;
3694 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003695 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003696 ~ExprEvalResult() {
3697 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3698 EvalType != CXEval_Int) {
3699 delete EvalData.stringVal;
3700 }
3701 }
3702};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003703
3704void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003705 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003706}
3707
3708CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3709 if (!E) {
3710 return CXEval_UnExposed;
3711 }
3712 return ((ExprEvalResult *)E)->EvalType;
3713}
3714
3715int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003716 return clang_EvalResult_getAsLongLong(E);
3717}
3718
3719long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003720 if (!E) {
3721 return 0;
3722 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003723 ExprEvalResult *Result = (ExprEvalResult*)E;
3724 if (Result->IsUnsignedInt)
3725 return Result->EvalData.unsignedVal;
3726 return Result->EvalData.intVal;
3727}
3728
3729unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3730 return ((ExprEvalResult *)E)->IsUnsignedInt;
3731}
3732
3733unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3734 if (!E) {
3735 return 0;
3736 }
3737
3738 ExprEvalResult *Result = (ExprEvalResult*)E;
3739 if (Result->IsUnsignedInt)
3740 return Result->EvalData.unsignedVal;
3741 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003742}
3743
3744double clang_EvalResult_getAsDouble(CXEvalResult E) {
3745 if (!E) {
3746 return 0;
3747 }
3748 return ((ExprEvalResult *)E)->EvalData.floatVal;
3749}
3750
3751const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3752 if (!E) {
3753 return nullptr;
3754 }
3755 return ((ExprEvalResult *)E)->EvalData.stringVal;
3756}
3757
3758static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3759 Expr::EvalResult ER;
3760 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003761 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003762 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003763
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003764 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003765 if (!expr->EvaluateAsRValue(ER, ctx))
3766 return nullptr;
3767
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003768 QualType rettype;
3769 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003770 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003771 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003772 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003773
David Blaikiebbc00882016-04-13 18:36:19 +00003774 if (ER.Val.isInt()) {
3775 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003776
3777 auto& val = ER.Val.getInt();
3778 if (val.isUnsigned()) {
3779 result->IsUnsignedInt = true;
3780 result->EvalData.unsignedVal = val.getZExtValue();
3781 } else {
3782 result->EvalData.intVal = val.getExtValue();
3783 }
3784
David Blaikiebbc00882016-04-13 18:36:19 +00003785 return result.release();
3786 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003787
David Blaikiebbc00882016-04-13 18:36:19 +00003788 if (ER.Val.isFloat()) {
3789 llvm::SmallVector<char, 100> Buffer;
3790 ER.Val.getFloat().toString(Buffer);
3791 std::string floatStr(Buffer.data(), Buffer.size());
3792 result->EvalType = CXEval_Float;
3793 bool ignored;
3794 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003795 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003796 llvm::APFloat::rmNearestTiesToEven, &ignored);
3797 result->EvalData.floatVal = apFloat.convertToDouble();
3798 return result.release();
3799 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003800
David Blaikiebbc00882016-04-13 18:36:19 +00003801 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3802 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3803 auto *subExpr = I->getSubExprAsWritten();
3804 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3805 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003806 const StringLiteral *StrE = nullptr;
3807 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003808 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003809
3810 if (ObjCExpr) {
3811 StrE = ObjCExpr->getString();
3812 result->EvalType = CXEval_ObjCStrLiteral;
3813 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003814 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003815 result->EvalType = CXEval_StrLiteral;
3816 }
3817
3818 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003819 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003820 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3821 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003822 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003823 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003824 }
3825 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3826 expr->getStmtClass() == Stmt::StringLiteralClass) {
3827 const StringLiteral *StrE = nullptr;
3828 const ObjCStringLiteral *ObjCExpr;
3829 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003830
David Blaikiebbc00882016-04-13 18:36:19 +00003831 if (ObjCExpr) {
3832 StrE = ObjCExpr->getString();
3833 result->EvalType = CXEval_ObjCStrLiteral;
3834 } else {
3835 StrE = cast<StringLiteral>(expr);
3836 result->EvalType = CXEval_StrLiteral;
3837 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003838
David Blaikiebbc00882016-04-13 18:36:19 +00003839 std::string strRef(StrE->getString().str());
3840 result->EvalData.stringVal = new char[strRef.size() + 1];
3841 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3842 result->EvalData.stringVal[strRef.size()] = '\0';
3843 return result.release();
3844 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003845
David Blaikiebbc00882016-04-13 18:36:19 +00003846 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3847 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003848
David Blaikiebbc00882016-04-13 18:36:19 +00003849 rettype = CC->getType();
3850 if (rettype.getAsString() == "CFStringRef" &&
3851 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003852
David Blaikiebbc00882016-04-13 18:36:19 +00003853 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3854 StringLiteral *S = getCFSTR_value(callExpr);
3855 if (S) {
3856 std::string strLiteral(S->getString().str());
3857 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003858
David Blaikiebbc00882016-04-13 18:36:19 +00003859 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3860 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3861 strLiteral.size());
3862 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003863 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003864 }
3865 }
3866
David Blaikiebbc00882016-04-13 18:36:19 +00003867 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3868 callExpr = static_cast<CallExpr *>(expr);
3869 rettype = callExpr->getCallReturnType(ctx);
3870
3871 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3872 return nullptr;
3873
3874 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3875 if (callExpr->getNumArgs() == 1 &&
3876 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3877 return nullptr;
3878 } else if (rettype.getAsString() == "CFStringRef") {
3879
3880 StringLiteral *S = getCFSTR_value(callExpr);
3881 if (S) {
3882 std::string strLiteral(S->getString().str());
3883 result->EvalType = CXEval_CFStr;
3884 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3885 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3886 strLiteral.size());
3887 result->EvalData.stringVal[strLiteral.size()] = '\0';
3888 return result.release();
3889 }
3890 }
3891 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3892 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3893 ValueDecl *V = D->getDecl();
3894 if (V->getKind() == Decl::Function) {
3895 std::string strName = V->getNameAsString();
3896 result->EvalType = CXEval_Other;
3897 result->EvalData.stringVal = new char[strName.size() + 1];
3898 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3899 result->EvalData.stringVal[strName.size()] = '\0';
3900 return result.release();
3901 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003902 }
3903
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003904 return nullptr;
3905}
3906
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003907CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003908 const Decl *D = getCursorDecl(C);
3909 if (D) {
3910 const Expr *expr = nullptr;
3911 if (auto *Var = dyn_cast<VarDecl>(D)) {
3912 expr = Var->getInit();
3913 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3914 expr = Field->getInClassInitializer();
3915 }
3916 if (expr)
3917 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3918 evaluateExpr(const_cast<Expr *>(expr), C)));
3919 return nullptr;
3920 }
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003921
3922 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3923 if (compoundStmt) {
3924 Expr *expr = nullptr;
3925 for (auto *bodyIterator : compoundStmt->body()) {
3926 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3927 break;
3928 }
3929 }
3930 if (expr)
3931 return const_cast<CXEvalResult>(
3932 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
3933 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003934 return nullptr;
3935}
3936
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003937unsigned clang_Cursor_hasAttrs(CXCursor C) {
3938 const Decl *D = getCursorDecl(C);
3939 if (!D) {
3940 return 0;
3941 }
3942
3943 if (D->hasAttrs()) {
3944 return 1;
3945 }
3946
3947 return 0;
3948}
Guy Benyei11169dd2012-12-18 14:30:41 +00003949unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3950 return CXSaveTranslationUnit_None;
3951}
3952
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003953static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3954 const char *FileName,
3955 unsigned options) {
3956 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003957 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3958 setThreadBackgroundPriority();
3959
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003960 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3961 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003962}
3963
3964int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3965 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003966 LOG_FUNC_SECTION {
3967 *Log << TU << ' ' << FileName;
3968 }
3969
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003970 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003971 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003972 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003973 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003974
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003975 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3977 if (!CXXUnit->hasSema())
3978 return CXSaveError_InvalidTU;
3979
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003980 CXSaveError result;
3981 auto SaveTranslationUnitImpl = [=, &result]() {
3982 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3983 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003984
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003985 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003986 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003987
3988 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3989 PrintLibclangResourceUsage(TU);
3990
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003991 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 }
3993
3994 // We have an AST that has invalid nodes due to compiler errors.
3995 // Use a crash recovery thread for protection.
3996
3997 llvm::CrashRecoveryContext CRC;
3998
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003999 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4001 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4002 fprintf(stderr, " 'options' : %d,\n", options);
4003 fprintf(stderr, "}\n");
4004
4005 return CXSaveError_Unknown;
4006
4007 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4008 PrintLibclangResourceUsage(TU);
4009 }
4010
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004011 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004012}
4013
4014void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4015 if (CTUnit) {
4016 // If the translation unit has been marked as unsafe to free, just discard
4017 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004018 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4019 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004020 return;
4021
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004022 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004023 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4025 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004026 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004027 delete CTUnit;
4028 }
4029}
4030
Erik Verbruggen346066b2017-05-30 14:25:54 +00004031unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4032 if (CTUnit) {
4033 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4034
4035 if (Unit && Unit->isUnsafeToFree())
4036 return false;
4037
4038 Unit->ResetForParse();
4039 return true;
4040 }
4041
4042 return false;
4043}
4044
Guy Benyei11169dd2012-12-18 14:30:41 +00004045unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4046 return CXReparse_None;
4047}
4048
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004049static CXErrorCode
4050clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4051 ArrayRef<CXUnsavedFile> unsaved_files,
4052 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004053 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004054 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004055 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004056 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004057 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004058
4059 // Reset the associated diagnostics.
4060 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004061 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004062
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004063 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004064 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4065 setThreadBackgroundPriority();
4066
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004067 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004068 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004069
4070 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4071 new std::vector<ASTUnit::RemappedFile>());
4072
Guy Benyei11169dd2012-12-18 14:30:41 +00004073 // Recover resources if we crash before exiting this function.
4074 llvm::CrashRecoveryContextCleanupRegistrar<
4075 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004076
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004077 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004078 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004079 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004080 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004082
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004083 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4084 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004085 return CXError_Success;
4086 if (isASTReadError(CXXUnit))
4087 return CXError_ASTReadError;
4088 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004089}
4090
4091int clang_reparseTranslationUnit(CXTranslationUnit TU,
4092 unsigned num_unsaved_files,
4093 struct CXUnsavedFile *unsaved_files,
4094 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004095 LOG_FUNC_SECTION {
4096 *Log << TU;
4097 }
4098
Alp Toker9d85b182014-07-07 01:23:14 +00004099 if (num_unsaved_files && !unsaved_files)
4100 return CXError_InvalidArguments;
4101
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004102 CXErrorCode result;
4103 auto ReparseTranslationUnitImpl = [=, &result]() {
4104 result = clang_reparseTranslationUnit_Impl(
4105 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4106 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004107
Guy Benyei11169dd2012-12-18 14:30:41 +00004108 llvm::CrashRecoveryContext CRC;
4109
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004110 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004112 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004113 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4115 PrintLibclangResourceUsage(TU);
4116
Alp Toker5c532982014-07-07 22:42:03 +00004117 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004118}
4119
4120
4121CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004122 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004123 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004124 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004125 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004126
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004127 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004128 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004129}
4130
4131CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004132 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004133 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004134 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004135 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004136
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004137 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004138 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4139}
4140
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004141CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4142 if (isNotUsableTU(CTUnit)) {
4143 LOG_BAD_TU(CTUnit);
4144 return nullptr;
4145 }
4146
4147 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4148 impl->TranslationUnit = CTUnit;
4149 return impl;
4150}
4151
4152CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4153 if (!TargetInfo)
4154 return cxstring::createEmpty();
4155
4156 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4157 assert(!isNotUsableTU(CTUnit) &&
4158 "Unexpected unusable translation unit in TargetInfo");
4159
4160 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4161 std::string Triple =
4162 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4163 return cxstring::createDup(Triple);
4164}
4165
4166int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4167 if (!TargetInfo)
4168 return -1;
4169
4170 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4171 assert(!isNotUsableTU(CTUnit) &&
4172 "Unexpected unusable translation unit in TargetInfo");
4173
4174 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4175 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4176}
4177
4178void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4179 if (!TargetInfo)
4180 return;
4181
4182 delete TargetInfo;
4183}
4184
Guy Benyei11169dd2012-12-18 14:30:41 +00004185//===----------------------------------------------------------------------===//
4186// CXFile Operations.
4187//===----------------------------------------------------------------------===//
4188
Guy Benyei11169dd2012-12-18 14:30:41 +00004189CXString clang_getFileName(CXFile SFile) {
4190 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004191 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004192
4193 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004194 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004195}
4196
4197time_t clang_getFileTime(CXFile SFile) {
4198 if (!SFile)
4199 return 0;
4200
4201 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4202 return FEnt->getModificationTime();
4203}
4204
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004205CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004206 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004207 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004208 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004209 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004210
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004211 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004212
4213 FileManager &FMgr = CXXUnit->getFileManager();
4214 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4215}
4216
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004217const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4218 size_t *size) {
4219 if (isNotUsableTU(TU)) {
4220 LOG_BAD_TU(TU);
4221 return nullptr;
4222 }
4223
4224 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4225 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4226 bool Invalid = true;
4227 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4228 if (Invalid) {
4229 if (size)
4230 *size = 0;
4231 return nullptr;
4232 }
4233 if (size)
4234 *size = buf->getBufferSize();
4235 return buf->getBufferStart();
4236}
4237
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004238unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4239 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004240 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004241 LOG_BAD_TU(TU);
4242 return 0;
4243 }
4244
4245 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 return 0;
4247
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004248 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 FileEntry *FEnt = static_cast<FileEntry *>(file);
4250 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4251 .isFileMultipleIncludeGuarded(FEnt);
4252}
4253
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004254int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4255 if (!file || !outID)
4256 return 1;
4257
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004258 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004259 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4260 outID->data[0] = ID.getDevice();
4261 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004262 outID->data[2] = FEnt->getModificationTime();
4263 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004264}
4265
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004266int clang_File_isEqual(CXFile file1, CXFile file2) {
4267 if (file1 == file2)
4268 return true;
4269
4270 if (!file1 || !file2)
4271 return false;
4272
4273 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4274 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4275 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4276}
4277
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004278CXString clang_File_tryGetRealPathName(CXFile SFile) {
4279 if (!SFile)
4280 return cxstring::createNull();
4281
4282 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4283 return cxstring::createRef(FEnt->tryGetRealPathName());
4284}
4285
Guy Benyei11169dd2012-12-18 14:30:41 +00004286//===----------------------------------------------------------------------===//
4287// CXCursor Operations.
4288//===----------------------------------------------------------------------===//
4289
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004290static const Decl *getDeclFromExpr(const Stmt *E) {
4291 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 return getDeclFromExpr(CE->getSubExpr());
4293
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004294 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004296 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004298 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004300 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 if (PRE->isExplicitProperty())
4302 return PRE->getExplicitProperty();
4303 // It could be messaging both getter and setter as in:
4304 // ++myobj.myprop;
4305 // in which case prefer to associate the setter since it is less obvious
4306 // from inspecting the source that the setter is going to get called.
4307 if (PRE->isMessagingSetter())
4308 return PRE->getImplicitPropertySetter();
4309 return PRE->getImplicitPropertyGetter();
4310 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004311 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004313 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 if (Expr *Src = OVE->getSourceExpr())
4315 return getDeclFromExpr(Src);
4316
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004317 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004318 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004319 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 if (!CE->isElidable())
4321 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004322 if (const CXXInheritedCtorInitExpr *CE =
4323 dyn_cast<CXXInheritedCtorInitExpr>(E))
4324 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004325 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 return OME->getMethodDecl();
4327
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004328 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004330 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4332 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004333 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4335 isa<ParmVarDecl>(SizeOfPack->getPack()))
4336 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004337
4338 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004339}
4340
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004341static SourceLocation getLocationFromExpr(const Expr *E) {
4342 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 return getLocationFromExpr(CE->getSubExpr());
4344
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004345 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004347 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004349 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004350 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004351 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004353 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004355 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004357
4358 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004359}
4360
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004361extern "C" {
4362
Guy Benyei11169dd2012-12-18 14:30:41 +00004363unsigned clang_visitChildren(CXCursor parent,
4364 CXCursorVisitor visitor,
4365 CXClientData client_data) {
4366 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4367 /*VisitPreprocessorLast=*/false);
4368 return CursorVis.VisitChildren(parent);
4369}
4370
4371#ifndef __has_feature
4372#define __has_feature(x) 0
4373#endif
4374#if __has_feature(blocks)
4375typedef enum CXChildVisitResult
4376 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4377
4378static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4379 CXClientData client_data) {
4380 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4381 return block(cursor, parent);
4382}
4383#else
4384// If we are compiled with a compiler that doesn't have native blocks support,
4385// define and call the block manually, so the
4386typedef struct _CXChildVisitResult
4387{
4388 void *isa;
4389 int flags;
4390 int reserved;
4391 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4392 CXCursor);
4393} *CXCursorVisitorBlock;
4394
4395static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4396 CXClientData client_data) {
4397 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4398 return block->invoke(block, cursor, parent);
4399}
4400#endif
4401
4402
4403unsigned clang_visitChildrenWithBlock(CXCursor parent,
4404 CXCursorVisitorBlock block) {
4405 return clang_visitChildren(parent, visitWithBlock, block);
4406}
4407
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004408static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004410 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004411
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004412 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004414 if (const ObjCPropertyImplDecl *PropImpl =
4415 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004417 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004418
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004419 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004421 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004422
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004423 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 }
4425
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004426 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004427 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004428
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004429 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4431 // and returns different names. NamedDecl returns the class name and
4432 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004433 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004434
4435 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004436 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004437
4438 SmallString<1024> S;
4439 llvm::raw_svector_ostream os(S);
4440 ND->printName(os);
4441
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004442 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004443}
4444
4445CXString clang_getCursorSpelling(CXCursor C) {
4446 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004447 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004448
4449 if (clang_isReference(C.kind)) {
4450 switch (C.kind) {
4451 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004452 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004453 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 }
4455 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004456 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004457 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 }
4459 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004460 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004462 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 }
4464 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004465 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004466 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 }
4468 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004469 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 assert(Type && "Missing type decl");
4471
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004472 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 getAsString());
4474 }
4475 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004476 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 assert(Template && "Missing template decl");
4478
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004479 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 }
4481
4482 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004483 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 assert(NS && "Missing namespace decl");
4485
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004486 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 }
4488
4489 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004490 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 assert(Field && "Missing member decl");
4492
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004493 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 }
4495
4496 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004497 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 assert(Label && "Missing label");
4499
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004500 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 }
4502
4503 case CXCursor_OverloadedDeclRef: {
4504 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004505 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4506 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004507 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004508 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004510 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004511 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 OverloadedTemplateStorage *Ovl
4513 = Storage.get<OverloadedTemplateStorage*>();
4514 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004515 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004516 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 }
4518
4519 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004520 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 assert(Var && "Missing variable decl");
4522
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004523 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 }
4525
4526 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004527 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 }
4529 }
4530
4531 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004532 const Expr *E = getCursorExpr(C);
4533
4534 if (C.kind == CXCursor_ObjCStringLiteral ||
4535 C.kind == CXCursor_StringLiteral) {
4536 const StringLiteral *SLit;
4537 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4538 SLit = OSL->getString();
4539 } else {
4540 SLit = cast<StringLiteral>(E);
4541 }
4542 SmallString<256> Buf;
4543 llvm::raw_svector_ostream OS(Buf);
4544 SLit->outputString(OS);
4545 return cxstring::createDup(OS.str());
4546 }
4547
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004548 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 if (D)
4550 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004551 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004552 }
4553
4554 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004555 const Stmt *S = getCursorStmt(C);
4556 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004557 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004558
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004559 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 }
4561
4562 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004563 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 ->getNameStart());
4565
4566 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004567 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 ->getNameStart());
4569
4570 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004571 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004572
4573 if (clang_isDeclaration(C.kind))
4574 return getDeclSpelling(getCursorDecl(C));
4575
4576 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004577 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004578 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 }
4580
4581 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004582 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004583 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 }
4585
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004586 if (C.kind == CXCursor_PackedAttr) {
4587 return cxstring::createRef("packed");
4588 }
4589
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004590 if (C.kind == CXCursor_VisibilityAttr) {
4591 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4592 switch (AA->getVisibility()) {
4593 case VisibilityAttr::VisibilityType::Default:
4594 return cxstring::createRef("default");
4595 case VisibilityAttr::VisibilityType::Hidden:
4596 return cxstring::createRef("hidden");
4597 case VisibilityAttr::VisibilityType::Protected:
4598 return cxstring::createRef("protected");
4599 }
4600 llvm_unreachable("unknown visibility type");
4601 }
4602
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004603 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004604}
4605
4606CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4607 unsigned pieceIndex,
4608 unsigned options) {
4609 if (clang_Cursor_isNull(C))
4610 return clang_getNullRange();
4611
4612 ASTContext &Ctx = getCursorContext(C);
4613
4614 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004615 const Stmt *S = getCursorStmt(C);
4616 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 if (pieceIndex > 0)
4618 return clang_getNullRange();
4619 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4620 }
4621
4622 return clang_getNullRange();
4623 }
4624
4625 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004626 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4628 if (pieceIndex >= ME->getNumSelectorLocs())
4629 return clang_getNullRange();
4630 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4631 }
4632 }
4633
4634 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4635 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004636 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4638 if (pieceIndex >= MD->getNumSelectorLocs())
4639 return clang_getNullRange();
4640 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4641 }
4642 }
4643
4644 if (C.kind == CXCursor_ObjCCategoryDecl ||
4645 C.kind == CXCursor_ObjCCategoryImplDecl) {
4646 if (pieceIndex > 0)
4647 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004648 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4650 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004651 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4653 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4654 }
4655
4656 if (C.kind == CXCursor_ModuleImportDecl) {
4657 if (pieceIndex > 0)
4658 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004659 if (const ImportDecl *ImportD =
4660 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4662 if (!Locs.empty())
4663 return cxloc::translateSourceRange(Ctx,
4664 SourceRange(Locs.front(), Locs.back()));
4665 }
4666 return clang_getNullRange();
4667 }
4668
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004669 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004670 C.kind == CXCursor_ConversionFunction ||
4671 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004672 if (pieceIndex > 0)
4673 return clang_getNullRange();
4674 if (const FunctionDecl *FD =
4675 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4676 DeclarationNameInfo FunctionName = FD->getNameInfo();
4677 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4678 }
4679 return clang_getNullRange();
4680 }
4681
Guy Benyei11169dd2012-12-18 14:30:41 +00004682 // FIXME: A CXCursor_InclusionDirective should give the location of the
4683 // filename, but we don't keep track of this.
4684
4685 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4686 // but we don't keep track of this.
4687
4688 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4689 // but we don't keep track of this.
4690
4691 // Default handling, give the location of the cursor.
4692
4693 if (pieceIndex > 0)
4694 return clang_getNullRange();
4695
4696 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4697 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4698 return cxloc::translateSourceRange(Ctx, Loc);
4699}
4700
Eli Bendersky44a206f2014-07-31 18:04:56 +00004701CXString clang_Cursor_getMangling(CXCursor C) {
4702 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4703 return cxstring::createEmpty();
4704
Eli Bendersky44a206f2014-07-31 18:04:56 +00004705 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004706 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004707 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4708 return cxstring::createEmpty();
4709
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004710 ASTContext &Ctx = D->getASTContext();
4711 index::CodegenNameGenerator CGNameGen(Ctx);
4712 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004713}
4714
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004715CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4716 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4717 return nullptr;
4718
4719 const Decl *D = getCursorDecl(C);
4720 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4721 return nullptr;
4722
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004723 ASTContext &Ctx = D->getASTContext();
4724 index::CodegenNameGenerator CGNameGen(Ctx);
4725 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004726 return cxstring::createSet(Manglings);
4727}
4728
Dave Lee1a532c92017-09-22 16:58:57 +00004729CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4730 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4731 return nullptr;
4732
4733 const Decl *D = getCursorDecl(C);
4734 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4735 return nullptr;
4736
4737 ASTContext &Ctx = D->getASTContext();
4738 index::CodegenNameGenerator CGNameGen(Ctx);
4739 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4740 return cxstring::createSet(Manglings);
4741}
4742
Jonathan Coe45ef5032018-01-16 10:19:56 +00004743CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4744 if (clang_Cursor_isNull(C))
4745 return 0;
4746 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4747}
4748
4749void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4750 if (Policy)
4751 delete static_cast<PrintingPolicy *>(Policy);
4752}
4753
4754unsigned
4755clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4756 enum CXPrintingPolicyProperty Property) {
4757 if (!Policy)
4758 return 0;
4759
4760 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4761 switch (Property) {
4762 case CXPrintingPolicy_Indentation:
4763 return P->Indentation;
4764 case CXPrintingPolicy_SuppressSpecifiers:
4765 return P->SuppressSpecifiers;
4766 case CXPrintingPolicy_SuppressTagKeyword:
4767 return P->SuppressTagKeyword;
4768 case CXPrintingPolicy_IncludeTagDefinition:
4769 return P->IncludeTagDefinition;
4770 case CXPrintingPolicy_SuppressScope:
4771 return P->SuppressScope;
4772 case CXPrintingPolicy_SuppressUnwrittenScope:
4773 return P->SuppressUnwrittenScope;
4774 case CXPrintingPolicy_SuppressInitializers:
4775 return P->SuppressInitializers;
4776 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4777 return P->ConstantArraySizeAsWritten;
4778 case CXPrintingPolicy_AnonymousTagLocations:
4779 return P->AnonymousTagLocations;
4780 case CXPrintingPolicy_SuppressStrongLifetime:
4781 return P->SuppressStrongLifetime;
4782 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4783 return P->SuppressLifetimeQualifiers;
4784 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4785 return P->SuppressTemplateArgsInCXXConstructors;
4786 case CXPrintingPolicy_Bool:
4787 return P->Bool;
4788 case CXPrintingPolicy_Restrict:
4789 return P->Restrict;
4790 case CXPrintingPolicy_Alignof:
4791 return P->Alignof;
4792 case CXPrintingPolicy_UnderscoreAlignof:
4793 return P->UnderscoreAlignof;
4794 case CXPrintingPolicy_UseVoidForZeroParams:
4795 return P->UseVoidForZeroParams;
4796 case CXPrintingPolicy_TerseOutput:
4797 return P->TerseOutput;
4798 case CXPrintingPolicy_PolishForDeclaration:
4799 return P->PolishForDeclaration;
4800 case CXPrintingPolicy_Half:
4801 return P->Half;
4802 case CXPrintingPolicy_MSWChar:
4803 return P->MSWChar;
4804 case CXPrintingPolicy_IncludeNewlines:
4805 return P->IncludeNewlines;
4806 case CXPrintingPolicy_MSVCFormatting:
4807 return P->MSVCFormatting;
4808 case CXPrintingPolicy_ConstantsAsWritten:
4809 return P->ConstantsAsWritten;
4810 case CXPrintingPolicy_SuppressImplicitBase:
4811 return P->SuppressImplicitBase;
4812 case CXPrintingPolicy_FullyQualifiedName:
4813 return P->FullyQualifiedName;
4814 }
4815
4816 assert(false && "Invalid CXPrintingPolicyProperty");
4817 return 0;
4818}
4819
4820void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4821 enum CXPrintingPolicyProperty Property,
4822 unsigned Value) {
4823 if (!Policy)
4824 return;
4825
4826 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4827 switch (Property) {
4828 case CXPrintingPolicy_Indentation:
4829 P->Indentation = Value;
4830 return;
4831 case CXPrintingPolicy_SuppressSpecifiers:
4832 P->SuppressSpecifiers = Value;
4833 return;
4834 case CXPrintingPolicy_SuppressTagKeyword:
4835 P->SuppressTagKeyword = Value;
4836 return;
4837 case CXPrintingPolicy_IncludeTagDefinition:
4838 P->IncludeTagDefinition = Value;
4839 return;
4840 case CXPrintingPolicy_SuppressScope:
4841 P->SuppressScope = Value;
4842 return;
4843 case CXPrintingPolicy_SuppressUnwrittenScope:
4844 P->SuppressUnwrittenScope = Value;
4845 return;
4846 case CXPrintingPolicy_SuppressInitializers:
4847 P->SuppressInitializers = Value;
4848 return;
4849 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4850 P->ConstantArraySizeAsWritten = Value;
4851 return;
4852 case CXPrintingPolicy_AnonymousTagLocations:
4853 P->AnonymousTagLocations = Value;
4854 return;
4855 case CXPrintingPolicy_SuppressStrongLifetime:
4856 P->SuppressStrongLifetime = Value;
4857 return;
4858 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4859 P->SuppressLifetimeQualifiers = Value;
4860 return;
4861 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4862 P->SuppressTemplateArgsInCXXConstructors = Value;
4863 return;
4864 case CXPrintingPolicy_Bool:
4865 P->Bool = Value;
4866 return;
4867 case CXPrintingPolicy_Restrict:
4868 P->Restrict = Value;
4869 return;
4870 case CXPrintingPolicy_Alignof:
4871 P->Alignof = Value;
4872 return;
4873 case CXPrintingPolicy_UnderscoreAlignof:
4874 P->UnderscoreAlignof = Value;
4875 return;
4876 case CXPrintingPolicy_UseVoidForZeroParams:
4877 P->UseVoidForZeroParams = Value;
4878 return;
4879 case CXPrintingPolicy_TerseOutput:
4880 P->TerseOutput = Value;
4881 return;
4882 case CXPrintingPolicy_PolishForDeclaration:
4883 P->PolishForDeclaration = Value;
4884 return;
4885 case CXPrintingPolicy_Half:
4886 P->Half = Value;
4887 return;
4888 case CXPrintingPolicy_MSWChar:
4889 P->MSWChar = Value;
4890 return;
4891 case CXPrintingPolicy_IncludeNewlines:
4892 P->IncludeNewlines = Value;
4893 return;
4894 case CXPrintingPolicy_MSVCFormatting:
4895 P->MSVCFormatting = Value;
4896 return;
4897 case CXPrintingPolicy_ConstantsAsWritten:
4898 P->ConstantsAsWritten = Value;
4899 return;
4900 case CXPrintingPolicy_SuppressImplicitBase:
4901 P->SuppressImplicitBase = Value;
4902 return;
4903 case CXPrintingPolicy_FullyQualifiedName:
4904 P->FullyQualifiedName = Value;
4905 return;
4906 }
4907
4908 assert(false && "Invalid CXPrintingPolicyProperty");
4909}
4910
4911CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4912 if (clang_Cursor_isNull(C))
4913 return cxstring::createEmpty();
4914
4915 if (clang_isDeclaration(C.kind)) {
4916 const Decl *D = getCursorDecl(C);
4917 if (!D)
4918 return cxstring::createEmpty();
4919
4920 SmallString<128> Str;
4921 llvm::raw_svector_ostream OS(Str);
4922 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4923 D->print(OS, UserPolicy ? *UserPolicy
4924 : getCursorContext(C).getPrintingPolicy());
4925
4926 return cxstring::createDup(OS.str());
4927 }
4928
4929 return cxstring::createEmpty();
4930}
4931
Guy Benyei11169dd2012-12-18 14:30:41 +00004932CXString clang_getCursorDisplayName(CXCursor C) {
4933 if (!clang_isDeclaration(C.kind))
4934 return clang_getCursorSpelling(C);
4935
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004936 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004938 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004939
4940 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004941 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004942 D = FunTmpl->getTemplatedDecl();
4943
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004944 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 SmallString<64> Str;
4946 llvm::raw_svector_ostream OS(Str);
4947 OS << *Function;
4948 if (Function->getPrimaryTemplate())
4949 OS << "<>";
4950 OS << "(";
4951 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4952 if (I)
4953 OS << ", ";
4954 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4955 }
4956
4957 if (Function->isVariadic()) {
4958 if (Function->getNumParams())
4959 OS << ", ";
4960 OS << "...";
4961 }
4962 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004963 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 }
4965
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004966 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 SmallString<64> Str;
4968 llvm::raw_svector_ostream OS(Str);
4969 OS << *ClassTemplate;
4970 OS << "<";
4971 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4972 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4973 if (I)
4974 OS << ", ";
4975
4976 NamedDecl *Param = Params->getParam(I);
4977 if (Param->getIdentifier()) {
4978 OS << Param->getIdentifier()->getName();
4979 continue;
4980 }
4981
4982 // There is no parameter name, which makes this tricky. Try to come up
4983 // with something useful that isn't too long.
4984 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4985 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4986 else if (NonTypeTemplateParmDecl *NTTP
4987 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4988 OS << NTTP->getType().getAsString(Policy);
4989 else
4990 OS << "template<...> class";
4991 }
4992
4993 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004994 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 }
4996
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004997 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4999 // If the type was explicitly written, use that.
5000 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005001 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005002
Benjamin Kramer9170e912013-02-22 15:46:01 +00005003 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 llvm::raw_svector_ostream OS(Str);
5005 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005006 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5007 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005008 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 }
5010
5011 return clang_getCursorSpelling(C);
5012}
5013
5014CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5015 switch (Kind) {
5016 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005017 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005019 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005021 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005023 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005025 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005027 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005029 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005031 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005033 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005035 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005037 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005039 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005041 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005043 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005045 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005047 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005049 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005051 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005053 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005055 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005057 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005059 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005061 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005063 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005065 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005067 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005069 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005071 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005073 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005075 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005077 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005079 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005080 case CXCursor_FixedPointLiteral:
5081 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005083 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005085 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005087 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005089 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005091 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005093 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005096 case CXCursor_OMPArraySectionExpr:
5097 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005101 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005148 case CXCursor_ObjCAvailabilityCheckExpr:
5149 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005150 case CXCursor_ObjCSelfExpr:
5151 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005240 case CXCursor_SEHLeaveStmt:
5241 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005257 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005265 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005270 case CXCursor_PackedAttr:
5271 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005272 case CXCursor_PureAttr:
5273 return cxstring::createRef("attribute(pure)");
5274 case CXCursor_ConstAttr:
5275 return cxstring::createRef("attribute(const)");
5276 case CXCursor_NoDuplicateAttr:
5277 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005278 case CXCursor_CUDAConstantAttr:
5279 return cxstring::createRef("attribute(constant)");
5280 case CXCursor_CUDADeviceAttr:
5281 return cxstring::createRef("attribute(device)");
5282 case CXCursor_CUDAGlobalAttr:
5283 return cxstring::createRef("attribute(global)");
5284 case CXCursor_CUDAHostAttr:
5285 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005286 case CXCursor_CUDASharedAttr:
5287 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005288 case CXCursor_VisibilityAttr:
5289 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005290 case CXCursor_DLLExport:
5291 return cxstring::createRef("attribute(dllexport)");
5292 case CXCursor_DLLImport:
5293 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005294 case CXCursor_NSReturnsRetained:
5295 return cxstring::createRef("attribute(ns_returns_retained)");
5296 case CXCursor_NSReturnsNotRetained:
5297 return cxstring::createRef("attribute(ns_returns_not_retained)");
5298 case CXCursor_NSReturnsAutoreleased:
5299 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5300 case CXCursor_NSConsumesSelf:
5301 return cxstring::createRef("attribute(ns_consumes_self)");
5302 case CXCursor_NSConsumed:
5303 return cxstring::createRef("attribute(ns_consumed)");
5304 case CXCursor_ObjCException:
5305 return cxstring::createRef("attribute(objc_exception)");
5306 case CXCursor_ObjCNSObject:
5307 return cxstring::createRef("attribute(NSObject)");
5308 case CXCursor_ObjCIndependentClass:
5309 return cxstring::createRef("attribute(objc_independent_class)");
5310 case CXCursor_ObjCPreciseLifetime:
5311 return cxstring::createRef("attribute(objc_precise_lifetime)");
5312 case CXCursor_ObjCReturnsInnerPointer:
5313 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5314 case CXCursor_ObjCRequiresSuper:
5315 return cxstring::createRef("attribute(objc_requires_super)");
5316 case CXCursor_ObjCRootClass:
5317 return cxstring::createRef("attribute(objc_root_class)");
5318 case CXCursor_ObjCSubclassingRestricted:
5319 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5320 case CXCursor_ObjCExplicitProtocolImpl:
5321 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5322 case CXCursor_ObjCDesignatedInitializer:
5323 return cxstring::createRef("attribute(objc_designated_initializer)");
5324 case CXCursor_ObjCRuntimeVisible:
5325 return cxstring::createRef("attribute(objc_runtime_visible)");
5326 case CXCursor_ObjCBoxable:
5327 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005328 case CXCursor_FlagEnum:
5329 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005330 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005331 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005333 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005335 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005337 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005338 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005339 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005340 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005341 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005343 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005345 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005347 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005349 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005350 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005351 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005352 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005353 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005355 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005357 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005359 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005360 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005361 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005362 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005363 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005365 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005367 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005369 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005370 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005371 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005372 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005373 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005374 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005375 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005376 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005377 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005378 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005379 return cxstring::createRef("OMPParallelDirective");
5380 case CXCursor_OMPSimdDirective:
5381 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005382 case CXCursor_OMPForDirective:
5383 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005384 case CXCursor_OMPForSimdDirective:
5385 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005386 case CXCursor_OMPSectionsDirective:
5387 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005388 case CXCursor_OMPSectionDirective:
5389 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005390 case CXCursor_OMPSingleDirective:
5391 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005392 case CXCursor_OMPMasterDirective:
5393 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005394 case CXCursor_OMPCriticalDirective:
5395 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005396 case CXCursor_OMPParallelForDirective:
5397 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005398 case CXCursor_OMPParallelForSimdDirective:
5399 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005400 case CXCursor_OMPParallelSectionsDirective:
5401 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005402 case CXCursor_OMPTaskDirective:
5403 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005404 case CXCursor_OMPTaskyieldDirective:
5405 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005406 case CXCursor_OMPBarrierDirective:
5407 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005408 case CXCursor_OMPTaskwaitDirective:
5409 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005410 case CXCursor_OMPTaskgroupDirective:
5411 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005412 case CXCursor_OMPFlushDirective:
5413 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005414 case CXCursor_OMPOrderedDirective:
5415 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005416 case CXCursor_OMPAtomicDirective:
5417 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005418 case CXCursor_OMPTargetDirective:
5419 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005420 case CXCursor_OMPTargetDataDirective:
5421 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005422 case CXCursor_OMPTargetEnterDataDirective:
5423 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005424 case CXCursor_OMPTargetExitDataDirective:
5425 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005426 case CXCursor_OMPTargetParallelDirective:
5427 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005428 case CXCursor_OMPTargetParallelForDirective:
5429 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005430 case CXCursor_OMPTargetUpdateDirective:
5431 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005432 case CXCursor_OMPTeamsDirective:
5433 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005434 case CXCursor_OMPCancellationPointDirective:
5435 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005436 case CXCursor_OMPCancelDirective:
5437 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005438 case CXCursor_OMPTaskLoopDirective:
5439 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005440 case CXCursor_OMPTaskLoopSimdDirective:
5441 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005442 case CXCursor_OMPDistributeDirective:
5443 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005444 case CXCursor_OMPDistributeParallelForDirective:
5445 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005446 case CXCursor_OMPDistributeParallelForSimdDirective:
5447 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005448 case CXCursor_OMPDistributeSimdDirective:
5449 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005450 case CXCursor_OMPTargetParallelForSimdDirective:
5451 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005452 case CXCursor_OMPTargetSimdDirective:
5453 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005454 case CXCursor_OMPTeamsDistributeDirective:
5455 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005456 case CXCursor_OMPTeamsDistributeSimdDirective:
5457 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005458 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5459 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005460 case CXCursor_OMPTeamsDistributeParallelForDirective:
5461 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005462 case CXCursor_OMPTargetTeamsDirective:
5463 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005464 case CXCursor_OMPTargetTeamsDistributeDirective:
5465 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005466 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5467 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005468 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5469 return cxstring::createRef(
5470 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005471 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5472 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005473 case CXCursor_OverloadCandidate:
5474 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005475 case CXCursor_TypeAliasTemplateDecl:
5476 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005477 case CXCursor_StaticAssert:
5478 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005479 case CXCursor_FriendDecl:
5480 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005481 }
5482
5483 llvm_unreachable("Unhandled CXCursorKind");
5484}
5485
5486struct GetCursorData {
5487 SourceLocation TokenBeginLoc;
5488 bool PointsAtMacroArgExpansion;
5489 bool VisitedObjCPropertyImplDecl;
5490 SourceLocation VisitedDeclaratorDeclStartLoc;
5491 CXCursor &BestCursor;
5492
5493 GetCursorData(SourceManager &SM,
5494 SourceLocation tokenBegin, CXCursor &outputCursor)
5495 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5496 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5497 VisitedObjCPropertyImplDecl = false;
5498 }
5499};
5500
5501static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5502 CXCursor parent,
5503 CXClientData client_data) {
5504 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5505 CXCursor *BestCursor = &Data->BestCursor;
5506
5507 // If we point inside a macro argument we should provide info of what the
5508 // token is so use the actual cursor, don't replace it with a macro expansion
5509 // cursor.
5510 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5511 return CXChildVisit_Recurse;
5512
5513 if (clang_isDeclaration(cursor.kind)) {
5514 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005515 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005516 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5517 if (MD->isImplicit())
5518 return CXChildVisit_Break;
5519
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005520 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005521 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5522 // Check that when we have multiple @class references in the same line,
5523 // that later ones do not override the previous ones.
5524 // If we have:
5525 // @class Foo, Bar;
5526 // source ranges for both start at '@', so 'Bar' will end up overriding
5527 // 'Foo' even though the cursor location was at 'Foo'.
5528 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5529 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005530 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005531 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5532 if (PrevID != ID &&
5533 !PrevID->isThisDeclarationADefinition() &&
5534 !ID->isThisDeclarationADefinition())
5535 return CXChildVisit_Break;
5536 }
5537
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005538 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5540 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5541 // Check that when we have multiple declarators in the same line,
5542 // that later ones do not override the previous ones.
5543 // If we have:
5544 // int Foo, Bar;
5545 // source ranges for both start at 'int', so 'Bar' will end up overriding
5546 // 'Foo' even though the cursor location was at 'Foo'.
5547 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5548 return CXChildVisit_Break;
5549 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5550
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005551 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005552 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5553 (void)PropImp;
5554 // Check that when we have multiple @synthesize in the same line,
5555 // that later ones do not override the previous ones.
5556 // If we have:
5557 // @synthesize Foo, Bar;
5558 // source ranges for both start at '@', so 'Bar' will end up overriding
5559 // 'Foo' even though the cursor location was at 'Foo'.
5560 if (Data->VisitedObjCPropertyImplDecl)
5561 return CXChildVisit_Break;
5562 Data->VisitedObjCPropertyImplDecl = true;
5563 }
5564 }
5565
5566 if (clang_isExpression(cursor.kind) &&
5567 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005568 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005569 // Avoid having the cursor of an expression replace the declaration cursor
5570 // when the expression source range overlaps the declaration range.
5571 // This can happen for C++ constructor expressions whose range generally
5572 // include the variable declaration, e.g.:
5573 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5574 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5575 D->getLocation() == Data->TokenBeginLoc)
5576 return CXChildVisit_Break;
5577 }
5578 }
5579
5580 // If our current best cursor is the construction of a temporary object,
5581 // don't replace that cursor with a type reference, because we want
5582 // clang_getCursor() to point at the constructor.
5583 if (clang_isExpression(BestCursor->kind) &&
5584 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5585 cursor.kind == CXCursor_TypeRef) {
5586 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5587 // as having the actual point on the type reference.
5588 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5589 return CXChildVisit_Recurse;
5590 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005591
5592 // If we already have an Objective-C superclass reference, don't
5593 // update it further.
5594 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5595 return CXChildVisit_Break;
5596
Guy Benyei11169dd2012-12-18 14:30:41 +00005597 *BestCursor = cursor;
5598 return CXChildVisit_Recurse;
5599}
5600
5601CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005602 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005603 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005604 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005605 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005606
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005607 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005608 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5609
5610 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5611 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5612
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005613 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005614 CXFile SearchFile;
5615 unsigned SearchLine, SearchColumn;
5616 CXFile ResultFile;
5617 unsigned ResultLine, ResultColumn;
5618 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5619 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5620 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005621
5622 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5623 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005624 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005625 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 SearchFileName = clang_getFileName(SearchFile);
5627 ResultFileName = clang_getFileName(ResultFile);
5628 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5629 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005630 *Log << llvm::format("(%s:%d:%d) = %s",
5631 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5632 clang_getCString(KindSpelling))
5633 << llvm::format("(%s:%d:%d):%s%s",
5634 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5635 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005636 clang_disposeString(SearchFileName);
5637 clang_disposeString(ResultFileName);
5638 clang_disposeString(KindSpelling);
5639 clang_disposeString(USR);
5640
5641 CXCursor Definition = clang_getCursorDefinition(Result);
5642 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5643 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5644 CXString DefinitionKindSpelling
5645 = clang_getCursorKindSpelling(Definition.kind);
5646 CXFile DefinitionFile;
5647 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005648 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005649 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005650 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005651 *Log << llvm::format(" -> %s(%s:%d:%d)",
5652 clang_getCString(DefinitionKindSpelling),
5653 clang_getCString(DefinitionFileName),
5654 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 clang_disposeString(DefinitionFileName);
5656 clang_disposeString(DefinitionKindSpelling);
5657 }
5658 }
5659
5660 return Result;
5661}
5662
5663CXCursor clang_getNullCursor(void) {
5664 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5665}
5666
5667unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005668 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5669 // can't set consistently. For example, when visiting a DeclStmt we will set
5670 // it but we don't set it on the result of clang_getCursorDefinition for
5671 // a reference of the same declaration.
5672 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5673 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5674 // to provide that kind of info.
5675 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005676 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005677 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005678 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005679
Guy Benyei11169dd2012-12-18 14:30:41 +00005680 return X == Y;
5681}
5682
5683unsigned clang_hashCursor(CXCursor C) {
5684 unsigned Index = 0;
5685 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5686 Index = 1;
5687
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005688 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005689 std::make_pair(C.kind, C.data[Index]));
5690}
5691
5692unsigned clang_isInvalid(enum CXCursorKind K) {
5693 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5694}
5695
5696unsigned clang_isDeclaration(enum CXCursorKind K) {
5697 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005698 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5699}
5700
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005701unsigned clang_isInvalidDeclaration(CXCursor C) {
5702 if (clang_isDeclaration(C.kind)) {
5703 if (const Decl *D = getCursorDecl(C))
5704 return D->isInvalidDecl();
5705 }
5706
5707 return 0;
5708}
5709
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005710unsigned clang_isReference(enum CXCursorKind K) {
5711 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5712}
Guy Benyei11169dd2012-12-18 14:30:41 +00005713
5714unsigned clang_isExpression(enum CXCursorKind K) {
5715 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5716}
5717
5718unsigned clang_isStatement(enum CXCursorKind K) {
5719 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5720}
5721
5722unsigned clang_isAttribute(enum CXCursorKind K) {
5723 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5724}
5725
5726unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5727 return K == CXCursor_TranslationUnit;
5728}
5729
5730unsigned clang_isPreprocessing(enum CXCursorKind K) {
5731 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5732}
5733
5734unsigned clang_isUnexposed(enum CXCursorKind K) {
5735 switch (K) {
5736 case CXCursor_UnexposedDecl:
5737 case CXCursor_UnexposedExpr:
5738 case CXCursor_UnexposedStmt:
5739 case CXCursor_UnexposedAttr:
5740 return true;
5741 default:
5742 return false;
5743 }
5744}
5745
5746CXCursorKind clang_getCursorKind(CXCursor C) {
5747 return C.kind;
5748}
5749
5750CXSourceLocation clang_getCursorLocation(CXCursor C) {
5751 if (clang_isReference(C.kind)) {
5752 switch (C.kind) {
5753 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005754 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005755 = getCursorObjCSuperClassRef(C);
5756 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5757 }
5758
5759 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005760 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005761 = getCursorObjCProtocolRef(C);
5762 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5763 }
5764
5765 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005766 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005767 = getCursorObjCClassRef(C);
5768 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5769 }
5770
5771 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005772 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005773 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5774 }
5775
5776 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005777 std::pair<const TemplateDecl *, SourceLocation> P =
5778 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005779 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5780 }
5781
5782 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005783 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005784 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5785 }
5786
5787 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005788 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5790 }
5791
5792 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005793 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005794 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5795 }
5796
5797 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005798 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005799 if (!BaseSpec)
5800 return clang_getNullLocation();
5801
5802 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5803 return cxloc::translateSourceLocation(getCursorContext(C),
5804 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005805
Guy Benyei11169dd2012-12-18 14:30:41 +00005806 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005807 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005808 }
5809
5810 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005811 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005812 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5813 }
5814
5815 case CXCursor_OverloadedDeclRef:
5816 return cxloc::translateSourceLocation(getCursorContext(C),
5817 getCursorOverloadedDeclRef(C).second);
5818
5819 default:
5820 // FIXME: Need a way to enumerate all non-reference cases.
5821 llvm_unreachable("Missed a reference kind");
5822 }
5823 }
5824
5825 if (clang_isExpression(C.kind))
5826 return cxloc::translateSourceLocation(getCursorContext(C),
5827 getLocationFromExpr(getCursorExpr(C)));
5828
5829 if (clang_isStatement(C.kind))
5830 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005831 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005832
5833 if (C.kind == CXCursor_PreprocessingDirective) {
5834 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5835 return cxloc::translateSourceLocation(getCursorContext(C), L);
5836 }
5837
5838 if (C.kind == CXCursor_MacroExpansion) {
5839 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005840 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 return cxloc::translateSourceLocation(getCursorContext(C), L);
5842 }
5843
5844 if (C.kind == CXCursor_MacroDefinition) {
5845 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5846 return cxloc::translateSourceLocation(getCursorContext(C), L);
5847 }
5848
5849 if (C.kind == CXCursor_InclusionDirective) {
5850 SourceLocation L
5851 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5852 return cxloc::translateSourceLocation(getCursorContext(C), L);
5853 }
5854
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005855 if (clang_isAttribute(C.kind)) {
5856 SourceLocation L
5857 = cxcursor::getCursorAttr(C)->getLocation();
5858 return cxloc::translateSourceLocation(getCursorContext(C), L);
5859 }
5860
Guy Benyei11169dd2012-12-18 14:30:41 +00005861 if (!clang_isDeclaration(C.kind))
5862 return clang_getNullLocation();
5863
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005864 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005865 if (!D)
5866 return clang_getNullLocation();
5867
5868 SourceLocation Loc = D->getLocation();
5869 // FIXME: Multiple variables declared in a single declaration
5870 // currently lack the information needed to correctly determine their
5871 // ranges when accounting for the type-specifier. We use context
5872 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5873 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005874 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005875 if (!cxcursor::isFirstInDeclGroup(C))
5876 Loc = VD->getLocation();
5877 }
5878
5879 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005880 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005881 Loc = MD->getSelectorStartLoc();
5882
5883 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5884}
5885
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005886} // end extern "C"
5887
Guy Benyei11169dd2012-12-18 14:30:41 +00005888CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5889 assert(TU);
5890
5891 // Guard against an invalid SourceLocation, or we may assert in one
5892 // of the following calls.
5893 if (SLoc.isInvalid())
5894 return clang_getNullCursor();
5895
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005896 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005897
5898 // Translate the given source location to make it point at the beginning of
5899 // the token under the cursor.
5900 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5901 CXXUnit->getASTContext().getLangOpts());
5902
5903 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5904 if (SLoc.isValid()) {
5905 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5906 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5907 /*VisitPreprocessorLast=*/true,
5908 /*VisitIncludedEntities=*/false,
5909 SourceLocation(SLoc));
5910 CursorVis.visitFileRegion();
5911 }
5912
5913 return Result;
5914}
5915
5916static SourceRange getRawCursorExtent(CXCursor C) {
5917 if (clang_isReference(C.kind)) {
5918 switch (C.kind) {
5919 case CXCursor_ObjCSuperClassRef:
5920 return getCursorObjCSuperClassRef(C).second;
5921
5922 case CXCursor_ObjCProtocolRef:
5923 return getCursorObjCProtocolRef(C).second;
5924
5925 case CXCursor_ObjCClassRef:
5926 return getCursorObjCClassRef(C).second;
5927
5928 case CXCursor_TypeRef:
5929 return getCursorTypeRef(C).second;
5930
5931 case CXCursor_TemplateRef:
5932 return getCursorTemplateRef(C).second;
5933
5934 case CXCursor_NamespaceRef:
5935 return getCursorNamespaceRef(C).second;
5936
5937 case CXCursor_MemberRef:
5938 return getCursorMemberRef(C).second;
5939
5940 case CXCursor_CXXBaseSpecifier:
5941 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5942
5943 case CXCursor_LabelRef:
5944 return getCursorLabelRef(C).second;
5945
5946 case CXCursor_OverloadedDeclRef:
5947 return getCursorOverloadedDeclRef(C).second;
5948
5949 case CXCursor_VariableRef:
5950 return getCursorVariableRef(C).second;
5951
5952 default:
5953 // FIXME: Need a way to enumerate all non-reference cases.
5954 llvm_unreachable("Missed a reference kind");
5955 }
5956 }
5957
5958 if (clang_isExpression(C.kind))
5959 return getCursorExpr(C)->getSourceRange();
5960
5961 if (clang_isStatement(C.kind))
5962 return getCursorStmt(C)->getSourceRange();
5963
5964 if (clang_isAttribute(C.kind))
5965 return getCursorAttr(C)->getRange();
5966
5967 if (C.kind == CXCursor_PreprocessingDirective)
5968 return cxcursor::getCursorPreprocessingDirective(C);
5969
5970 if (C.kind == CXCursor_MacroExpansion) {
5971 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005972 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005973 return TU->mapRangeFromPreamble(Range);
5974 }
5975
5976 if (C.kind == CXCursor_MacroDefinition) {
5977 ASTUnit *TU = getCursorASTUnit(C);
5978 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5979 return TU->mapRangeFromPreamble(Range);
5980 }
5981
5982 if (C.kind == CXCursor_InclusionDirective) {
5983 ASTUnit *TU = getCursorASTUnit(C);
5984 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5985 return TU->mapRangeFromPreamble(Range);
5986 }
5987
5988 if (C.kind == CXCursor_TranslationUnit) {
5989 ASTUnit *TU = getCursorASTUnit(C);
5990 FileID MainID = TU->getSourceManager().getMainFileID();
5991 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5992 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5993 return SourceRange(Start, End);
5994 }
5995
5996 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005997 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005998 if (!D)
5999 return SourceRange();
6000
6001 SourceRange R = D->getSourceRange();
6002 // FIXME: Multiple variables declared in a single declaration
6003 // currently lack the information needed to correctly determine their
6004 // ranges when accounting for the type-specifier. We use context
6005 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6006 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006007 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006008 if (!cxcursor::isFirstInDeclGroup(C))
6009 R.setBegin(VD->getLocation());
6010 }
6011 return R;
6012 }
6013 return SourceRange();
6014}
6015
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006016/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006017/// the decl-specifier-seq for declarations.
6018static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6019 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006020 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006021 if (!D)
6022 return SourceRange();
6023
6024 SourceRange R = D->getSourceRange();
6025
6026 // Adjust the start of the location for declarations preceded by
6027 // declaration specifiers.
6028 SourceLocation StartLoc;
6029 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6030 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006031 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006032 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006033 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006034 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006035 }
6036
6037 if (StartLoc.isValid() && R.getBegin().isValid() &&
6038 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6039 R.setBegin(StartLoc);
6040
6041 // FIXME: Multiple variables declared in a single declaration
6042 // currently lack the information needed to correctly determine their
6043 // ranges when accounting for the type-specifier. We use context
6044 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6045 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006046 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 if (!cxcursor::isFirstInDeclGroup(C))
6048 R.setBegin(VD->getLocation());
6049 }
6050
6051 return R;
6052 }
6053
6054 return getRawCursorExtent(C);
6055}
6056
Guy Benyei11169dd2012-12-18 14:30:41 +00006057CXSourceRange clang_getCursorExtent(CXCursor C) {
6058 SourceRange R = getRawCursorExtent(C);
6059 if (R.isInvalid())
6060 return clang_getNullRange();
6061
6062 return cxloc::translateSourceRange(getCursorContext(C), R);
6063}
6064
6065CXCursor clang_getCursorReferenced(CXCursor C) {
6066 if (clang_isInvalid(C.kind))
6067 return clang_getNullCursor();
6068
6069 CXTranslationUnit tu = getCursorTU(C);
6070 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006071 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006072 if (!D)
6073 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006074 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006076 if (const ObjCPropertyImplDecl *PropImpl =
6077 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006078 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6079 return MakeCXCursor(Property, tu);
6080
6081 return C;
6082 }
6083
6084 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006085 const Expr *E = getCursorExpr(C);
6086 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 if (D) {
6088 CXCursor declCursor = MakeCXCursor(D, tu);
6089 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6090 declCursor);
6091 return declCursor;
6092 }
6093
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006094 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006095 return MakeCursorOverloadedDeclRef(Ovl, tu);
6096
6097 return clang_getNullCursor();
6098 }
6099
6100 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006101 const Stmt *S = getCursorStmt(C);
6102 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006103 if (LabelDecl *label = Goto->getLabel())
6104 if (LabelStmt *labelS = label->getStmt())
6105 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6106
6107 return clang_getNullCursor();
6108 }
Richard Smith66a81862015-05-04 02:25:31 +00006109
Guy Benyei11169dd2012-12-18 14:30:41 +00006110 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006111 if (const MacroDefinitionRecord *Def =
6112 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006113 return MakeMacroDefinitionCursor(Def, tu);
6114 }
6115
6116 if (!clang_isReference(C.kind))
6117 return clang_getNullCursor();
6118
6119 switch (C.kind) {
6120 case CXCursor_ObjCSuperClassRef:
6121 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6122
6123 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006124 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6125 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006126 return MakeCXCursor(Def, tu);
6127
6128 return MakeCXCursor(Prot, tu);
6129 }
6130
6131 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006132 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6133 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006134 return MakeCXCursor(Def, tu);
6135
6136 return MakeCXCursor(Class, tu);
6137 }
6138
6139 case CXCursor_TypeRef:
6140 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6141
6142 case CXCursor_TemplateRef:
6143 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6144
6145 case CXCursor_NamespaceRef:
6146 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6147
6148 case CXCursor_MemberRef:
6149 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6150
6151 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006152 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6154 tu ));
6155 }
6156
6157 case CXCursor_LabelRef:
6158 // FIXME: We end up faking the "parent" declaration here because we
6159 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006160 return MakeCXCursor(getCursorLabelRef(C).first,
6161 cxtu::getASTUnit(tu)->getASTContext()
6162 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006163 tu);
6164
6165 case CXCursor_OverloadedDeclRef:
6166 return C;
6167
6168 case CXCursor_VariableRef:
6169 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6170
6171 default:
6172 // We would prefer to enumerate all non-reference cursor kinds here.
6173 llvm_unreachable("Unhandled reference cursor kind");
6174 }
6175}
6176
6177CXCursor clang_getCursorDefinition(CXCursor C) {
6178 if (clang_isInvalid(C.kind))
6179 return clang_getNullCursor();
6180
6181 CXTranslationUnit TU = getCursorTU(C);
6182
6183 bool WasReference = false;
6184 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6185 C = clang_getCursorReferenced(C);
6186 WasReference = true;
6187 }
6188
6189 if (C.kind == CXCursor_MacroExpansion)
6190 return clang_getCursorReferenced(C);
6191
6192 if (!clang_isDeclaration(C.kind))
6193 return clang_getNullCursor();
6194
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006195 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 if (!D)
6197 return clang_getNullCursor();
6198
6199 switch (D->getKind()) {
6200 // Declaration kinds that don't really separate the notions of
6201 // declaration and definition.
6202 case Decl::Namespace:
6203 case Decl::Typedef:
6204 case Decl::TypeAlias:
6205 case Decl::TypeAliasTemplate:
6206 case Decl::TemplateTypeParm:
6207 case Decl::EnumConstant:
6208 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006209 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006210 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006211 case Decl::IndirectField:
6212 case Decl::ObjCIvar:
6213 case Decl::ObjCAtDefsField:
6214 case Decl::ImplicitParam:
6215 case Decl::ParmVar:
6216 case Decl::NonTypeTemplateParm:
6217 case Decl::TemplateTemplateParm:
6218 case Decl::ObjCCategoryImpl:
6219 case Decl::ObjCImplementation:
6220 case Decl::AccessSpec:
6221 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006222 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006223 case Decl::ObjCPropertyImpl:
6224 case Decl::FileScopeAsm:
6225 case Decl::StaticAssert:
6226 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006227 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006228 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 case Decl::Label: // FIXME: Is this right??
6230 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006231 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006233 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006234 case Decl::OMPDeclareReduction:
Kelvin Li1408f912018-09-26 04:28:39 +00006235 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006236 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006237 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006238 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006239 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006240 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006241 return C;
6242
6243 // Declaration kinds that don't make any sense here, but are
6244 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006245 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006246 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006247 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006248 break;
6249
6250 // Declaration kinds for which the definition is not resolvable.
6251 case Decl::UnresolvedUsingTypename:
6252 case Decl::UnresolvedUsingValue:
6253 break;
6254
6255 case Decl::UsingDirective:
6256 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6257 TU);
6258
6259 case Decl::NamespaceAlias:
6260 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6261
6262 case Decl::Enum:
6263 case Decl::Record:
6264 case Decl::CXXRecord:
6265 case Decl::ClassTemplateSpecialization:
6266 case Decl::ClassTemplatePartialSpecialization:
6267 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6268 return MakeCXCursor(Def, TU);
6269 return clang_getNullCursor();
6270
6271 case Decl::Function:
6272 case Decl::CXXMethod:
6273 case Decl::CXXConstructor:
6274 case Decl::CXXDestructor:
6275 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006276 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006278 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006279 return clang_getNullCursor();
6280 }
6281
Larisse Voufo39a1e502013-08-06 01:03:05 +00006282 case Decl::Var:
6283 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006284 case Decl::VarTemplatePartialSpecialization:
6285 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006286 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006287 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006288 return MakeCXCursor(Def, TU);
6289 return clang_getNullCursor();
6290 }
6291
6292 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006293 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6295 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6296 return clang_getNullCursor();
6297 }
6298
6299 case Decl::ClassTemplate: {
6300 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6301 ->getDefinition())
6302 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6303 TU);
6304 return clang_getNullCursor();
6305 }
6306
Larisse Voufo39a1e502013-08-06 01:03:05 +00006307 case Decl::VarTemplate: {
6308 if (VarDecl *Def =
6309 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6310 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6311 return clang_getNullCursor();
6312 }
6313
Guy Benyei11169dd2012-12-18 14:30:41 +00006314 case Decl::Using:
6315 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6316 D->getLocation(), TU);
6317
6318 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006319 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 return clang_getCursorDefinition(
6321 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6322 TU));
6323
6324 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006325 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006326 if (Method->isThisDeclarationADefinition())
6327 return C;
6328
6329 // Dig out the method definition in the associated
6330 // @implementation, if we have it.
6331 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006332 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006333 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6334 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6335 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6336 Method->isInstanceMethod()))
6337 if (Def->isThisDeclarationADefinition())
6338 return MakeCXCursor(Def, TU);
6339
6340 return clang_getNullCursor();
6341 }
6342
6343 case Decl::ObjCCategory:
6344 if (ObjCCategoryImplDecl *Impl
6345 = cast<ObjCCategoryDecl>(D)->getImplementation())
6346 return MakeCXCursor(Impl, TU);
6347 return clang_getNullCursor();
6348
6349 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006350 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006351 return MakeCXCursor(Def, TU);
6352 return clang_getNullCursor();
6353
6354 case Decl::ObjCInterface: {
6355 // There are two notions of a "definition" for an Objective-C
6356 // class: the interface and its implementation. When we resolved a
6357 // reference to an Objective-C class, produce the @interface as
6358 // the definition; when we were provided with the interface,
6359 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006360 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006361 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006362 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006363 return MakeCXCursor(Def, TU);
6364 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6365 return MakeCXCursor(Impl, TU);
6366 return clang_getNullCursor();
6367 }
6368
6369 case Decl::ObjCProperty:
6370 // FIXME: We don't really know where to find the
6371 // ObjCPropertyImplDecls that implement this property.
6372 return clang_getNullCursor();
6373
6374 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006375 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006376 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006377 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006378 return MakeCXCursor(Def, TU);
6379
6380 return clang_getNullCursor();
6381
6382 case Decl::Friend:
6383 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6384 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6385 return clang_getNullCursor();
6386
6387 case Decl::FriendTemplate:
6388 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6389 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6390 return clang_getNullCursor();
6391 }
6392
6393 return clang_getNullCursor();
6394}
6395
6396unsigned clang_isCursorDefinition(CXCursor C) {
6397 if (!clang_isDeclaration(C.kind))
6398 return 0;
6399
6400 return clang_getCursorDefinition(C) == C;
6401}
6402
6403CXCursor clang_getCanonicalCursor(CXCursor C) {
6404 if (!clang_isDeclaration(C.kind))
6405 return C;
6406
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006407 if (const Decl *D = getCursorDecl(C)) {
6408 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006409 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6410 return MakeCXCursor(CatD, getCursorTU(C));
6411
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006412 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6413 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006414 return MakeCXCursor(IFD, getCursorTU(C));
6415
6416 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6417 }
6418
6419 return C;
6420}
6421
6422int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6423 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6424}
6425
6426unsigned clang_getNumOverloadedDecls(CXCursor C) {
6427 if (C.kind != CXCursor_OverloadedDeclRef)
6428 return 0;
6429
6430 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006431 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 return E->getNumDecls();
6433
6434 if (OverloadedTemplateStorage *S
6435 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6436 return S->size();
6437
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006438 const Decl *D = Storage.get<const Decl *>();
6439 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006440 return Using->shadow_size();
6441
6442 return 0;
6443}
6444
6445CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6446 if (cursor.kind != CXCursor_OverloadedDeclRef)
6447 return clang_getNullCursor();
6448
6449 if (index >= clang_getNumOverloadedDecls(cursor))
6450 return clang_getNullCursor();
6451
6452 CXTranslationUnit TU = getCursorTU(cursor);
6453 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006454 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006455 return MakeCXCursor(E->decls_begin()[index], TU);
6456
6457 if (OverloadedTemplateStorage *S
6458 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6459 return MakeCXCursor(S->begin()[index], TU);
6460
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006461 const Decl *D = Storage.get<const Decl *>();
6462 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006463 // FIXME: This is, unfortunately, linear time.
6464 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6465 std::advance(Pos, index);
6466 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6467 }
6468
6469 return clang_getNullCursor();
6470}
6471
6472void clang_getDefinitionSpellingAndExtent(CXCursor C,
6473 const char **startBuf,
6474 const char **endBuf,
6475 unsigned *startLine,
6476 unsigned *startColumn,
6477 unsigned *endLine,
6478 unsigned *endColumn) {
6479 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006480 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006481 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6482
6483 SourceManager &SM = FD->getASTContext().getSourceManager();
6484 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6485 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6486 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6487 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6488 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6489 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6490}
6491
6492
6493CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6494 unsigned PieceIndex) {
6495 RefNamePieces Pieces;
6496
6497 switch (C.kind) {
6498 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006499 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006500 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6501 E->getQualifierLoc().getSourceRange());
6502 break;
6503
6504 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006505 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6506 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6507 Pieces =
6508 buildPieces(NameFlags, false, E->getNameInfo(),
6509 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6510 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006511 break;
6512
6513 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006514 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006515 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006516 const Expr *Callee = OCE->getCallee();
6517 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006518 Callee = ICE->getSubExpr();
6519
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006520 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6522 DRE->getQualifierLoc().getSourceRange());
6523 }
6524 break;
6525
6526 default:
6527 break;
6528 }
6529
6530 if (Pieces.empty()) {
6531 if (PieceIndex == 0)
6532 return clang_getCursorExtent(C);
6533 } else if (PieceIndex < Pieces.size()) {
6534 SourceRange R = Pieces[PieceIndex];
6535 if (R.isValid())
6536 return cxloc::translateSourceRange(getCursorContext(C), R);
6537 }
6538
6539 return clang_getNullRange();
6540}
6541
6542void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006543 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6544 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006545}
6546
6547void clang_executeOnThread(void (*fn)(void*), void *user_data,
6548 unsigned stack_size) {
6549 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6550}
6551
Guy Benyei11169dd2012-12-18 14:30:41 +00006552//===----------------------------------------------------------------------===//
6553// Token-based Operations.
6554//===----------------------------------------------------------------------===//
6555
6556/* CXToken layout:
6557 * int_data[0]: a CXTokenKind
6558 * int_data[1]: starting token location
6559 * int_data[2]: token length
6560 * int_data[3]: reserved
6561 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6562 * otherwise unused.
6563 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006564CXTokenKind clang_getTokenKind(CXToken CXTok) {
6565 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6566}
6567
6568CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6569 switch (clang_getTokenKind(CXTok)) {
6570 case CXToken_Identifier:
6571 case CXToken_Keyword:
6572 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006573 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006574 ->getNameStart());
6575
6576 case CXToken_Literal: {
6577 // We have stashed the starting pointer in the ptr_data field. Use it.
6578 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006579 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006580 }
6581
6582 case CXToken_Punctuation:
6583 case CXToken_Comment:
6584 break;
6585 }
6586
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006587 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006588 LOG_BAD_TU(TU);
6589 return cxstring::createEmpty();
6590 }
6591
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 // We have to find the starting buffer pointer the hard way, by
6593 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006594 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006596 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006597
6598 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6599 std::pair<FileID, unsigned> LocInfo
6600 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6601 bool Invalid = false;
6602 StringRef Buffer
6603 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6604 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006605 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006606
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006607 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006608}
6609
6610CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006611 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006612 LOG_BAD_TU(TU);
6613 return clang_getNullLocation();
6614 }
6615
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006616 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006617 if (!CXXUnit)
6618 return clang_getNullLocation();
6619
6620 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6621 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6622}
6623
6624CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006625 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006626 LOG_BAD_TU(TU);
6627 return clang_getNullRange();
6628 }
6629
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006630 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006631 if (!CXXUnit)
6632 return clang_getNullRange();
6633
6634 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6635 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6636}
6637
6638static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6639 SmallVectorImpl<CXToken> &CXTokens) {
6640 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6641 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006642 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006643 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006644 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006645
6646 // Cannot tokenize across files.
6647 if (BeginLocInfo.first != EndLocInfo.first)
6648 return;
6649
6650 // Create a lexer
6651 bool Invalid = false;
6652 StringRef Buffer
6653 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6654 if (Invalid)
6655 return;
6656
6657 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6658 CXXUnit->getASTContext().getLangOpts(),
6659 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6660 Lex.SetCommentRetentionState(true);
6661
6662 // Lex tokens until we hit the end of the range.
6663 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6664 Token Tok;
6665 bool previousWasAt = false;
6666 do {
6667 // Lex the next token
6668 Lex.LexFromRawLexer(Tok);
6669 if (Tok.is(tok::eof))
6670 break;
6671
6672 // Initialize the CXToken.
6673 CXToken CXTok;
6674
6675 // - Common fields
6676 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6677 CXTok.int_data[2] = Tok.getLength();
6678 CXTok.int_data[3] = 0;
6679
6680 // - Kind-specific fields
6681 if (Tok.isLiteral()) {
6682 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006683 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006684 } else if (Tok.is(tok::raw_identifier)) {
6685 // Lookup the identifier to determine whether we have a keyword.
6686 IdentifierInfo *II
6687 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6688
6689 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6690 CXTok.int_data[0] = CXToken_Keyword;
6691 }
6692 else {
6693 CXTok.int_data[0] = Tok.is(tok::identifier)
6694 ? CXToken_Identifier
6695 : CXToken_Keyword;
6696 }
6697 CXTok.ptr_data = II;
6698 } else if (Tok.is(tok::comment)) {
6699 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006700 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006701 } else {
6702 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006703 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006704 }
6705 CXTokens.push_back(CXTok);
6706 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006707 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006708}
6709
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006710CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6711 LOG_FUNC_SECTION {
6712 *Log << TU << ' ' << Location;
6713 }
6714
6715 if (isNotUsableTU(TU)) {
6716 LOG_BAD_TU(TU);
6717 return NULL;
6718 }
6719
6720 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6721 if (!CXXUnit)
6722 return NULL;
6723
6724 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6725 if (Begin.isInvalid())
6726 return NULL;
6727 SourceManager &SM = CXXUnit->getSourceManager();
6728 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6729 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6730
6731 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6732
6733 SmallVector<CXToken, 32> CXTokens;
6734 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6735
6736 if (CXTokens.empty())
6737 return NULL;
6738
6739 CXTokens.resize(1);
6740 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6741
6742 memmove(Token, CXTokens.data(), sizeof(CXToken));
6743 return Token;
6744}
6745
Guy Benyei11169dd2012-12-18 14:30:41 +00006746void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6747 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006748 LOG_FUNC_SECTION {
6749 *Log << TU << ' ' << Range;
6750 }
6751
Guy Benyei11169dd2012-12-18 14:30:41 +00006752 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006753 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006754 if (NumTokens)
6755 *NumTokens = 0;
6756
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006757 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006758 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006759 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006760 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006761
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006762 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006763 if (!CXXUnit || !Tokens || !NumTokens)
6764 return;
6765
6766 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6767
6768 SourceRange R = cxloc::translateCXSourceRange(Range);
6769 if (R.isInvalid())
6770 return;
6771
6772 SmallVector<CXToken, 32> CXTokens;
6773 getTokens(CXXUnit, R, CXTokens);
6774
6775 if (CXTokens.empty())
6776 return;
6777
Serge Pavlov52525732018-02-21 02:02:39 +00006778 *Tokens = static_cast<CXToken *>(
6779 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6781 *NumTokens = CXTokens.size();
6782}
6783
6784void clang_disposeTokens(CXTranslationUnit TU,
6785 CXToken *Tokens, unsigned NumTokens) {
6786 free(Tokens);
6787}
6788
Guy Benyei11169dd2012-12-18 14:30:41 +00006789//===----------------------------------------------------------------------===//
6790// Token annotation APIs.
6791//===----------------------------------------------------------------------===//
6792
Guy Benyei11169dd2012-12-18 14:30:41 +00006793static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6794 CXCursor parent,
6795 CXClientData client_data);
6796static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6797 CXClientData client_data);
6798
6799namespace {
6800class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006801 CXToken *Tokens;
6802 CXCursor *Cursors;
6803 unsigned NumTokens;
6804 unsigned TokIdx;
6805 unsigned PreprocessingTokIdx;
6806 CursorVisitor AnnotateVis;
6807 SourceManager &SrcMgr;
6808 bool HasContextSensitiveKeywords;
6809
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006810 struct PostChildrenAction {
6811 CXCursor cursor;
6812 enum Action { Invalid, Ignore, Postpone } action;
6813 };
6814 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6815
Guy Benyei11169dd2012-12-18 14:30:41 +00006816 struct PostChildrenInfo {
6817 CXCursor Cursor;
6818 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006819 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006820 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006821 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006822 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006823 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006824
6825 CXToken &getTok(unsigned Idx) {
6826 assert(Idx < NumTokens);
6827 return Tokens[Idx];
6828 }
6829 const CXToken &getTok(unsigned Idx) const {
6830 assert(Idx < NumTokens);
6831 return Tokens[Idx];
6832 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006833 bool MoreTokens() const { return TokIdx < NumTokens; }
6834 unsigned NextToken() const { return TokIdx; }
6835 void AdvanceToken() { ++TokIdx; }
6836 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006837 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006838 }
6839 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006840 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006841 }
6842 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006843 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006844 }
6845
6846 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006847 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006848 SourceRange);
6849
6850public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006851 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006852 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006853 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006854 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006855 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006856 AnnotateTokensVisitor, this,
6857 /*VisitPreprocessorLast=*/true,
6858 /*VisitIncludedEntities=*/false,
6859 RegionOfInterest,
6860 /*VisitDeclsOnly=*/false,
6861 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006862 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006863 HasContextSensitiveKeywords(false) { }
6864
6865 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6866 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006867 bool IsIgnoredChildCursor(CXCursor cursor) const;
6868 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6869
Guy Benyei11169dd2012-12-18 14:30:41 +00006870 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006871 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6872 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6873
Guy Benyei11169dd2012-12-18 14:30:41 +00006874 void AnnotateTokens();
6875
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006876 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006877 /// context-sensitive keywords.
6878 bool hasContextSensitiveKeywords() const {
6879 return HasContextSensitiveKeywords;
6880 }
6881
6882 ~AnnotateTokensWorker() {
6883 assert(PostChildrenInfos.empty());
6884 }
6885};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006886}
Guy Benyei11169dd2012-12-18 14:30:41 +00006887
6888void AnnotateTokensWorker::AnnotateTokens() {
6889 // Walk the AST within the region of interest, annotating tokens
6890 // along the way.
6891 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006892}
Guy Benyei11169dd2012-12-18 14:30:41 +00006893
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006894bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6895 if (PostChildrenInfos.empty())
6896 return false;
6897
6898 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6899 if (ChildAction.cursor == cursor &&
6900 ChildAction.action == PostChildrenAction::Ignore) {
6901 return true;
6902 }
6903 }
6904
6905 return false;
6906}
6907
6908const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6909 if (!clang_isExpression(Cursor.kind))
6910 return nullptr;
6911
6912 const Expr *E = getCursorExpr(Cursor);
6913 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6914 const OverloadedOperatorKind Kind = OCE->getOperator();
6915 if (Kind == OO_Call || Kind == OO_Subscript)
6916 return OCE;
6917 }
6918
6919 return nullptr;
6920}
6921
6922AnnotateTokensWorker::PostChildrenActions
6923AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6924 PostChildrenActions actions;
6925
6926 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6927 // visited before the arguments to the operator call. For the Call and
6928 // Subscript operator the range of this DeclRefExpr includes the whole call
6929 // expression, so that all tokens in that range would be mapped to the
6930 // operator function, including the tokens of the arguments. To avoid that,
6931 // ensure to visit this DeclRefExpr as last node.
6932 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6933 const Expr *Callee = OCE->getCallee();
6934 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6935 const Expr *SubExpr = ICE->getSubExpr();
6936 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6937 const Decl *parentDecl = getCursorParentDecl(Cursor);
6938 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6939
6940 // Visit the DeclRefExpr as last.
6941 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6942 actions.push_back({cxChild, PostChildrenAction::Postpone});
6943
6944 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6945 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6946 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6947 actions.push_back({cxChild, PostChildrenAction::Ignore});
6948 }
6949 }
6950 }
6951
6952 return actions;
6953}
6954
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006955static inline void updateCursorAnnotation(CXCursor &Cursor,
6956 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006957 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006959 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006960}
6961
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006962/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006963//// between the cursor location and the source range is the same as
6964/// \arg compResult.
6965///
6966/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6967/// Pass RangeOverlap to annotate tokens inside a range.
6968void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6969 RangeComparisonResult compResult,
6970 SourceRange range) {
6971 while (MoreTokens()) {
6972 const unsigned I = NextToken();
6973 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006974 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6975 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006976
6977 SourceLocation TokLoc = GetTokenLoc(I);
6978 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006979 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006980 AdvanceToken();
6981 continue;
6982 }
6983 break;
6984 }
6985}
6986
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006987/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006988/// \returns true if it advanced beyond all macro tokens, false otherwise.
6989bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006990 CXCursor updateC,
6991 RangeComparisonResult compResult,
6992 SourceRange range) {
6993 assert(MoreTokens());
6994 assert(isFunctionMacroToken(NextToken()) &&
6995 "Should be called only for macro arg tokens");
6996
6997 // This works differently than annotateAndAdvanceTokens; because expanded
6998 // macro arguments can have arbitrary translation-unit source order, we do not
6999 // advance the token index one by one until a token fails the range test.
7000 // We only advance once past all of the macro arg tokens if all of them
7001 // pass the range test. If one of them fails we keep the token index pointing
7002 // at the start of the macro arg tokens so that the failing token will be
7003 // annotated by a subsequent annotation try.
7004
7005 bool atLeastOneCompFail = false;
7006
7007 unsigned I = NextToken();
7008 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7009 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7010 if (TokLoc.isFileID())
7011 continue; // not macro arg token, it's parens or comma.
7012 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7013 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7014 Cursors[I] = updateC;
7015 } else
7016 atLeastOneCompFail = true;
7017 }
7018
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007019 if (atLeastOneCompFail)
7020 return false;
7021
7022 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7023 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007024}
7025
7026enum CXChildVisitResult
7027AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007028 SourceRange cursorRange = getRawCursorExtent(cursor);
7029 if (cursorRange.isInvalid())
7030 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007031
7032 if (IsIgnoredChildCursor(cursor))
7033 return CXChildVisit_Continue;
7034
Guy Benyei11169dd2012-12-18 14:30:41 +00007035 if (!HasContextSensitiveKeywords) {
7036 // Objective-C properties can have context-sensitive keywords.
7037 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007038 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007039 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7040 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7041 }
7042 // Objective-C methods can have context-sensitive keywords.
7043 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7044 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007045 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007046 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7047 if (Method->getObjCDeclQualifier())
7048 HasContextSensitiveKeywords = true;
7049 else {
David Majnemer59f77922016-06-24 04:05:48 +00007050 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007051 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007052 HasContextSensitiveKeywords = true;
7053 break;
7054 }
7055 }
7056 }
7057 }
7058 }
7059 // C++ methods can have context-sensitive keywords.
7060 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007061 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007062 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7063 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7064 HasContextSensitiveKeywords = true;
7065 }
7066 }
7067 // C++ classes can have context-sensitive keywords.
7068 else if (cursor.kind == CXCursor_StructDecl ||
7069 cursor.kind == CXCursor_ClassDecl ||
7070 cursor.kind == CXCursor_ClassTemplate ||
7071 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007072 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007073 if (D->hasAttr<FinalAttr>())
7074 HasContextSensitiveKeywords = true;
7075 }
7076 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007077
7078 // Don't override a property annotation with its getter/setter method.
7079 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7080 parent.kind == CXCursor_ObjCPropertyDecl)
7081 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007082
7083 if (clang_isPreprocessing(cursor.kind)) {
7084 // Items in the preprocessing record are kept separate from items in
7085 // declarations, so we keep a separate token index.
7086 unsigned SavedTokIdx = TokIdx;
7087 TokIdx = PreprocessingTokIdx;
7088
7089 // Skip tokens up until we catch up to the beginning of the preprocessing
7090 // entry.
7091 while (MoreTokens()) {
7092 const unsigned I = NextToken();
7093 SourceLocation TokLoc = GetTokenLoc(I);
7094 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7095 case RangeBefore:
7096 AdvanceToken();
7097 continue;
7098 case RangeAfter:
7099 case RangeOverlap:
7100 break;
7101 }
7102 break;
7103 }
7104
7105 // Look at all of the tokens within this range.
7106 while (MoreTokens()) {
7107 const unsigned I = NextToken();
7108 SourceLocation TokLoc = GetTokenLoc(I);
7109 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7110 case RangeBefore:
7111 llvm_unreachable("Infeasible");
7112 case RangeAfter:
7113 break;
7114 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007115 // For macro expansions, just note where the beginning of the macro
7116 // expansion occurs.
7117 if (cursor.kind == CXCursor_MacroExpansion) {
7118 if (TokLoc == cursorRange.getBegin())
7119 Cursors[I] = cursor;
7120 AdvanceToken();
7121 break;
7122 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007123 // We may have already annotated macro names inside macro definitions.
7124 if (Cursors[I].kind != CXCursor_MacroExpansion)
7125 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007126 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007127 continue;
7128 }
7129 break;
7130 }
7131
7132 // Save the preprocessing token index; restore the non-preprocessing
7133 // token index.
7134 PreprocessingTokIdx = TokIdx;
7135 TokIdx = SavedTokIdx;
7136 return CXChildVisit_Recurse;
7137 }
7138
7139 if (cursorRange.isInvalid())
7140 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007141
7142 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007143 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007144 const enum CXCursorKind K = clang_getCursorKind(parent);
7145 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007146 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7147 // Attributes are annotated out-of-order, skip tokens until we reach it.
7148 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007149 ? clang_getNullCursor() : parent;
7150
7151 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7152
7153 // Avoid having the cursor of an expression "overwrite" the annotation of the
7154 // variable declaration that it belongs to.
7155 // This can happen for C++ constructor expressions whose range generally
7156 // include the variable declaration, e.g.:
7157 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007158 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007159 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00007160 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007161 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007162 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7163 E->getBeginLoc() == D->getLocation() &&
7164 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007165 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007166 AdvanceToken();
7167 }
7168 }
7169 }
7170
7171 // Before recursing into the children keep some state that we are going
7172 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7173 // extra work after the child nodes are visited.
7174 // Note that we don't call VisitChildren here to avoid traversing statements
7175 // code-recursively which can blow the stack.
7176
7177 PostChildrenInfo Info;
7178 Info.Cursor = cursor;
7179 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007180 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007181 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007182 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007183 PostChildrenInfos.push_back(Info);
7184
7185 return CXChildVisit_Recurse;
7186}
7187
7188bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7189 if (PostChildrenInfos.empty())
7190 return false;
7191 const PostChildrenInfo &Info = PostChildrenInfos.back();
7192 if (!clang_equalCursors(Info.Cursor, cursor))
7193 return false;
7194
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007195 HandlePostPonedChildCursors(Info);
7196
Guy Benyei11169dd2012-12-18 14:30:41 +00007197 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7198 const unsigned AfterChildren = NextToken();
7199 SourceRange cursorRange = Info.CursorRange;
7200
7201 // Scan the tokens that are at the end of the cursor, but are not captured
7202 // but the child cursors.
7203 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7204
7205 // Scan the tokens that are at the beginning of the cursor, but are not
7206 // capture by the child cursors.
7207 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7208 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7209 break;
7210
7211 Cursors[I] = cursor;
7212 }
7213
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007214 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7215 // encountered the attribute cursor.
7216 if (clang_isAttribute(cursor.kind))
7217 TokIdx = Info.BeforeReachingCursorIdx;
7218
Guy Benyei11169dd2012-12-18 14:30:41 +00007219 PostChildrenInfos.pop_back();
7220 return false;
7221}
7222
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007223void AnnotateTokensWorker::HandlePostPonedChildCursors(
7224 const PostChildrenInfo &Info) {
7225 for (const auto &ChildAction : Info.ChildActions) {
7226 if (ChildAction.action == PostChildrenAction::Postpone) {
7227 HandlePostPonedChildCursor(ChildAction.cursor,
7228 Info.BeforeChildrenTokenIdx);
7229 }
7230 }
7231}
7232
7233void AnnotateTokensWorker::HandlePostPonedChildCursor(
7234 CXCursor Cursor, unsigned StartTokenIndex) {
7235 const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier;
7236 unsigned I = StartTokenIndex;
7237
7238 // The bracket tokens of a Call or Subscript operator are mapped to
7239 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7240 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7241 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
7242 const CXSourceRange CXRefNameRange =
7243 clang_getCursorReferenceNameRange(Cursor, flags, RefNameRangeNr);
7244 if (clang_Range_isNull(CXRefNameRange))
7245 break; // All ranges handled.
7246
7247 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7248 while (I < NumTokens) {
7249 const SourceLocation TokenLocation = GetTokenLoc(I);
7250 if (!TokenLocation.isValid())
7251 break;
7252
7253 // Adapt the end range, because LocationCompare() reports
7254 // RangeOverlap even for the not-inclusive end location.
7255 const SourceLocation fixedEnd =
7256 RefNameRange.getEnd().getLocWithOffset(-1);
7257 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7258
7259 const RangeComparisonResult ComparisonResult =
7260 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7261
7262 if (ComparisonResult == RangeOverlap) {
7263 Cursors[I++] = Cursor;
7264 } else if (ComparisonResult == RangeBefore) {
7265 ++I; // Not relevant token, check next one.
7266 } else if (ComparisonResult == RangeAfter) {
7267 break; // All tokens updated for current range, check next.
7268 }
7269 }
7270 }
7271}
7272
Guy Benyei11169dd2012-12-18 14:30:41 +00007273static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7274 CXCursor parent,
7275 CXClientData client_data) {
7276 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7277}
7278
7279static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7280 CXClientData client_data) {
7281 return static_cast<AnnotateTokensWorker*>(client_data)->
7282 postVisitChildren(cursor);
7283}
7284
7285namespace {
7286
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007287/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007288/// and mark tokens that are macro arguments. This info is used by the
7289/// AnnotateTokensWorker.
7290class MarkMacroArgTokensVisitor {
7291 SourceManager &SM;
7292 CXToken *Tokens;
7293 unsigned NumTokens;
7294 unsigned CurIdx;
7295
7296public:
7297 MarkMacroArgTokensVisitor(SourceManager &SM,
7298 CXToken *tokens, unsigned numTokens)
7299 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7300
7301 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7302 if (cursor.kind != CXCursor_MacroExpansion)
7303 return CXChildVisit_Continue;
7304
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007305 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007306 if (macroRange.getBegin() == macroRange.getEnd())
7307 return CXChildVisit_Continue; // it's not a function macro.
7308
7309 for (; CurIdx < NumTokens; ++CurIdx) {
7310 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7311 macroRange.getBegin()))
7312 break;
7313 }
7314
7315 if (CurIdx == NumTokens)
7316 return CXChildVisit_Break;
7317
7318 for (; CurIdx < NumTokens; ++CurIdx) {
7319 SourceLocation tokLoc = getTokenLoc(CurIdx);
7320 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7321 break;
7322
7323 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7324 }
7325
7326 if (CurIdx == NumTokens)
7327 return CXChildVisit_Break;
7328
7329 return CXChildVisit_Continue;
7330 }
7331
7332private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007333 CXToken &getTok(unsigned Idx) {
7334 assert(Idx < NumTokens);
7335 return Tokens[Idx];
7336 }
7337 const CXToken &getTok(unsigned Idx) const {
7338 assert(Idx < NumTokens);
7339 return Tokens[Idx];
7340 }
7341
Guy Benyei11169dd2012-12-18 14:30:41 +00007342 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007343 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007344 }
7345
7346 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7347 // The third field is reserved and currently not used. Use it here
7348 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007349 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007350 }
7351};
7352
7353} // end anonymous namespace
7354
7355static CXChildVisitResult
7356MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7357 CXClientData client_data) {
7358 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7359 parent);
7360}
7361
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007362/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007363/// \returns true if lexing was finished, false otherwise.
7364static bool lexNext(Lexer &Lex, Token &Tok,
7365 unsigned &NextIdx, unsigned NumTokens) {
7366 if (NextIdx >= NumTokens)
7367 return true;
7368
7369 ++NextIdx;
7370 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007371 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007372}
7373
Guy Benyei11169dd2012-12-18 14:30:41 +00007374static void annotatePreprocessorTokens(CXTranslationUnit TU,
7375 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007376 CXCursor *Cursors,
7377 CXToken *Tokens,
7378 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007379 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007380
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007381 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007382 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7383 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007384 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007385 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007386 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007387
7388 if (BeginLocInfo.first != EndLocInfo.first)
7389 return;
7390
7391 StringRef Buffer;
7392 bool Invalid = false;
7393 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7394 if (Buffer.empty() || Invalid)
7395 return;
7396
7397 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7398 CXXUnit->getASTContext().getLangOpts(),
7399 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7400 Buffer.end());
7401 Lex.SetCommentRetentionState(true);
7402
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007403 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007404 // Lex tokens in raw mode until we hit the end of the range, to avoid
7405 // entering #includes or expanding macros.
7406 while (true) {
7407 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007408 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7409 break;
7410 unsigned TokIdx = NextIdx-1;
7411 assert(Tok.getLocation() ==
7412 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007413
7414 reprocess:
7415 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007416 // We have found a preprocessing directive. Annotate the tokens
7417 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 //
7419 // FIXME: Some simple tests here could identify macro definitions and
7420 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007421
7422 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007423 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7424 break;
7425
Craig Topper69186e72014-06-08 08:38:04 +00007426 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007427 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007428 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7429 break;
7430
7431 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007432 IdentifierInfo &II =
7433 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007434 SourceLocation MappedTokLoc =
7435 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7436 MI = getMacroInfo(II, MappedTokLoc, TU);
7437 }
7438 }
7439
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007440 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007441 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007442 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7443 finished = true;
7444 break;
7445 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007446 // If we are in a macro definition, check if the token was ever a
7447 // macro name and annotate it if that's the case.
7448 if (MI) {
7449 SourceLocation SaveLoc = Tok.getLocation();
7450 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007451 MacroDefinitionRecord *MacroDef =
7452 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007453 Tok.setLocation(SaveLoc);
7454 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007455 Cursors[NextIdx - 1] =
7456 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007457 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007458 } while (!Tok.isAtStartOfLine());
7459
7460 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7461 assert(TokIdx <= LastIdx);
7462 SourceLocation EndLoc =
7463 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7464 CXCursor Cursor =
7465 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7466
7467 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007468 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007469
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007470 if (finished)
7471 break;
7472 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007473 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007474 }
7475}
7476
7477// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007478static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7479 CXToken *Tokens, unsigned NumTokens,
7480 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007481 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007482 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7483 setThreadBackgroundPriority();
7484
7485 // Determine the region of interest, which contains all of the tokens.
7486 SourceRange RegionOfInterest;
7487 RegionOfInterest.setBegin(
7488 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7489 RegionOfInterest.setEnd(
7490 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7491 Tokens[NumTokens-1])));
7492
Guy Benyei11169dd2012-12-18 14:30:41 +00007493 // Relex the tokens within the source range to look for preprocessing
7494 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007495 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007496
7497 // If begin location points inside a macro argument, set it to the expansion
7498 // location so we can have the full context when annotating semantically.
7499 {
7500 SourceManager &SM = CXXUnit->getSourceManager();
7501 SourceLocation Loc =
7502 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7503 if (Loc.isMacroID())
7504 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7505 }
7506
Guy Benyei11169dd2012-12-18 14:30:41 +00007507 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7508 // Search and mark tokens that are macro argument expansions.
7509 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7510 Tokens, NumTokens);
7511 CursorVisitor MacroArgMarker(TU,
7512 MarkMacroArgTokensVisitorDelegate, &Visitor,
7513 /*VisitPreprocessorLast=*/true,
7514 /*VisitIncludedEntities=*/false,
7515 RegionOfInterest);
7516 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7517 }
7518
7519 // Annotate all of the source locations in the region of interest that map to
7520 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007521 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007522
7523 // FIXME: We use a ridiculous stack size here because the data-recursion
7524 // algorithm uses a large stack frame than the non-data recursive version,
7525 // and AnnotationTokensWorker currently transforms the data-recursion
7526 // algorithm back into a traditional recursion by explicitly calling
7527 // VisitChildren(). We will need to remove this explicit recursive call.
7528 W.AnnotateTokens();
7529
7530 // If we ran into any entities that involve context-sensitive keywords,
7531 // take another pass through the tokens to mark them as such.
7532 if (W.hasContextSensitiveKeywords()) {
7533 for (unsigned I = 0; I != NumTokens; ++I) {
7534 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7535 continue;
7536
7537 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7538 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007539 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007540 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7541 if (Property->getPropertyAttributesAsWritten() != 0 &&
7542 llvm::StringSwitch<bool>(II->getName())
7543 .Case("readonly", true)
7544 .Case("assign", true)
7545 .Case("unsafe_unretained", true)
7546 .Case("readwrite", true)
7547 .Case("retain", true)
7548 .Case("copy", true)
7549 .Case("nonatomic", true)
7550 .Case("atomic", true)
7551 .Case("getter", true)
7552 .Case("setter", true)
7553 .Case("strong", true)
7554 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007555 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007556 .Default(false))
7557 Tokens[I].int_data[0] = CXToken_Keyword;
7558 }
7559 continue;
7560 }
7561
7562 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7563 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7564 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7565 if (llvm::StringSwitch<bool>(II->getName())
7566 .Case("in", true)
7567 .Case("out", true)
7568 .Case("inout", true)
7569 .Case("oneway", true)
7570 .Case("bycopy", true)
7571 .Case("byref", true)
7572 .Default(false))
7573 Tokens[I].int_data[0] = CXToken_Keyword;
7574 continue;
7575 }
7576
7577 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7578 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7579 Tokens[I].int_data[0] = CXToken_Keyword;
7580 continue;
7581 }
7582 }
7583 }
7584}
7585
Guy Benyei11169dd2012-12-18 14:30:41 +00007586void clang_annotateTokens(CXTranslationUnit TU,
7587 CXToken *Tokens, unsigned NumTokens,
7588 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007589 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007590 LOG_BAD_TU(TU);
7591 return;
7592 }
7593 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007594 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007595 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007596 }
7597
7598 LOG_FUNC_SECTION {
7599 *Log << TU << ' ';
7600 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7601 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7602 *Log << clang_getRange(bloc, eloc);
7603 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007604
7605 // Any token we don't specifically annotate will have a NULL cursor.
7606 CXCursor C = clang_getNullCursor();
7607 for (unsigned I = 0; I != NumTokens; ++I)
7608 Cursors[I] = C;
7609
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007610 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007611 if (!CXXUnit)
7612 return;
7613
7614 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007615
7616 auto AnnotateTokensImpl = [=]() {
7617 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7618 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007619 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007620 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007621 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7622 }
7623}
7624
Guy Benyei11169dd2012-12-18 14:30:41 +00007625//===----------------------------------------------------------------------===//
7626// Operations for querying linkage of a cursor.
7627//===----------------------------------------------------------------------===//
7628
Guy Benyei11169dd2012-12-18 14:30:41 +00007629CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7630 if (!clang_isDeclaration(cursor.kind))
7631 return CXLinkage_Invalid;
7632
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007633 const Decl *D = cxcursor::getCursorDecl(cursor);
7634 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007635 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007636 case NoLinkage:
7637 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007638 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007639 case InternalLinkage: return CXLinkage_Internal;
7640 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007641 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007642 case ExternalLinkage: return CXLinkage_External;
7643 };
7644
7645 return CXLinkage_Invalid;
7646}
Guy Benyei11169dd2012-12-18 14:30:41 +00007647
7648//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007649// Operations for querying visibility of a cursor.
7650//===----------------------------------------------------------------------===//
7651
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007652CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7653 if (!clang_isDeclaration(cursor.kind))
7654 return CXVisibility_Invalid;
7655
7656 const Decl *D = cxcursor::getCursorDecl(cursor);
7657 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7658 switch (ND->getVisibility()) {
7659 case HiddenVisibility: return CXVisibility_Hidden;
7660 case ProtectedVisibility: return CXVisibility_Protected;
7661 case DefaultVisibility: return CXVisibility_Default;
7662 };
7663
7664 return CXVisibility_Invalid;
7665}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007666
7667//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007668// Operations for querying language of a cursor.
7669//===----------------------------------------------------------------------===//
7670
7671static CXLanguageKind getDeclLanguage(const Decl *D) {
7672 if (!D)
7673 return CXLanguage_C;
7674
7675 switch (D->getKind()) {
7676 default:
7677 break;
7678 case Decl::ImplicitParam:
7679 case Decl::ObjCAtDefsField:
7680 case Decl::ObjCCategory:
7681 case Decl::ObjCCategoryImpl:
7682 case Decl::ObjCCompatibleAlias:
7683 case Decl::ObjCImplementation:
7684 case Decl::ObjCInterface:
7685 case Decl::ObjCIvar:
7686 case Decl::ObjCMethod:
7687 case Decl::ObjCProperty:
7688 case Decl::ObjCPropertyImpl:
7689 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007690 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007691 return CXLanguage_ObjC;
7692 case Decl::CXXConstructor:
7693 case Decl::CXXConversion:
7694 case Decl::CXXDestructor:
7695 case Decl::CXXMethod:
7696 case Decl::CXXRecord:
7697 case Decl::ClassTemplate:
7698 case Decl::ClassTemplatePartialSpecialization:
7699 case Decl::ClassTemplateSpecialization:
7700 case Decl::Friend:
7701 case Decl::FriendTemplate:
7702 case Decl::FunctionTemplate:
7703 case Decl::LinkageSpec:
7704 case Decl::Namespace:
7705 case Decl::NamespaceAlias:
7706 case Decl::NonTypeTemplateParm:
7707 case Decl::StaticAssert:
7708 case Decl::TemplateTemplateParm:
7709 case Decl::TemplateTypeParm:
7710 case Decl::UnresolvedUsingTypename:
7711 case Decl::UnresolvedUsingValue:
7712 case Decl::Using:
7713 case Decl::UsingDirective:
7714 case Decl::UsingShadow:
7715 return CXLanguage_CPlusPlus;
7716 }
7717
7718 return CXLanguage_C;
7719}
7720
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007721static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7722 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007723 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007724
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007725 switch (D->getAvailability()) {
7726 case AR_Available:
7727 case AR_NotYetIntroduced:
7728 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007729 return getCursorAvailabilityForDecl(
7730 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007731 return CXAvailability_Available;
7732
7733 case AR_Deprecated:
7734 return CXAvailability_Deprecated;
7735
7736 case AR_Unavailable:
7737 return CXAvailability_NotAvailable;
7738 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007739
7740 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007741}
7742
Guy Benyei11169dd2012-12-18 14:30:41 +00007743enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7744 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007745 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7746 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007747
7748 return CXAvailability_Available;
7749}
7750
7751static CXVersion convertVersion(VersionTuple In) {
7752 CXVersion Out = { -1, -1, -1 };
7753 if (In.empty())
7754 return Out;
7755
7756 Out.Major = In.getMajor();
7757
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007758 Optional<unsigned> Minor = In.getMinor();
7759 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007760 Out.Minor = *Minor;
7761 else
7762 return Out;
7763
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007764 Optional<unsigned> Subminor = In.getSubminor();
7765 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007766 Out.Subminor = *Subminor;
7767
7768 return Out;
7769}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007770
Alex Lorenz1345ea22017-06-12 19:06:30 +00007771static void getCursorPlatformAvailabilityForDecl(
7772 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7773 int *always_unavailable, CXString *unavailable_message,
7774 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007775 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007776 for (auto A : D->attrs()) {
7777 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007778 HadAvailAttr = true;
7779 if (always_deprecated)
7780 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007781 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007782 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007783 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007784 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007785 continue;
7786 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007787
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007788 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007789 HadAvailAttr = true;
7790 if (always_unavailable)
7791 *always_unavailable = 1;
7792 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007793 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007794 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7795 }
7796 continue;
7797 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007798
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007799 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007800 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007801 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007802 }
7803 }
7804
7805 if (!HadAvailAttr)
7806 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7807 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007808 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7809 deprecated_message, always_unavailable, unavailable_message,
7810 AvailabilityAttrs);
7811
7812 if (AvailabilityAttrs.empty())
7813 return;
7814
Fangrui Song55fab262018-09-26 22:16:28 +00007815 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007816 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7817 return LHS->getPlatform()->getName() <
7818 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007819 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007820 ASTContext &Ctx = D->getASTContext();
7821 auto It = std::unique(
7822 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7823 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7824 if (LHS->getPlatform() != RHS->getPlatform())
7825 return false;
7826
7827 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7828 LHS->getDeprecated() == RHS->getDeprecated() &&
7829 LHS->getObsoleted() == RHS->getObsoleted() &&
7830 LHS->getMessage() == RHS->getMessage() &&
7831 LHS->getReplacement() == RHS->getReplacement())
7832 return true;
7833
7834 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7835 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7836 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7837 return false;
7838
7839 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7840 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7841
7842 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7843 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7844 if (LHS->getMessage().empty())
7845 LHS->setMessage(Ctx, RHS->getMessage());
7846 if (LHS->getReplacement().empty())
7847 LHS->setReplacement(Ctx, RHS->getReplacement());
7848 }
7849
7850 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7851 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7852 if (LHS->getMessage().empty())
7853 LHS->setMessage(Ctx, RHS->getMessage());
7854 if (LHS->getReplacement().empty())
7855 LHS->setReplacement(Ctx, RHS->getReplacement());
7856 }
7857
7858 return true;
7859 });
7860 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007861}
7862
Alex Lorenz1345ea22017-06-12 19:06:30 +00007863int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007864 CXString *deprecated_message,
7865 int *always_unavailable,
7866 CXString *unavailable_message,
7867 CXPlatformAvailability *availability,
7868 int availability_size) {
7869 if (always_deprecated)
7870 *always_deprecated = 0;
7871 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007872 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007873 if (always_unavailable)
7874 *always_unavailable = 0;
7875 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007876 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007877
Guy Benyei11169dd2012-12-18 14:30:41 +00007878 if (!clang_isDeclaration(cursor.kind))
7879 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007880
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007881 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007882 if (!D)
7883 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007884
Alex Lorenz1345ea22017-06-12 19:06:30 +00007885 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7886 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7887 always_unavailable, unavailable_message,
7888 AvailabilityAttrs);
7889 for (const auto &Avail :
7890 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7891 .take_front(availability_size))) {
7892 availability[Avail.index()].Platform =
7893 cxstring::createDup(Avail.value()->getPlatform()->getName());
7894 availability[Avail.index()].Introduced =
7895 convertVersion(Avail.value()->getIntroduced());
7896 availability[Avail.index()].Deprecated =
7897 convertVersion(Avail.value()->getDeprecated());
7898 availability[Avail.index()].Obsoleted =
7899 convertVersion(Avail.value()->getObsoleted());
7900 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7901 availability[Avail.index()].Message =
7902 cxstring::createDup(Avail.value()->getMessage());
7903 }
7904
7905 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007906}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007907
Guy Benyei11169dd2012-12-18 14:30:41 +00007908void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7909 clang_disposeString(availability->Platform);
7910 clang_disposeString(availability->Message);
7911}
7912
7913CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7914 if (clang_isDeclaration(cursor.kind))
7915 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7916
7917 return CXLanguage_Invalid;
7918}
7919
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007920CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7921 const Decl *D = cxcursor::getCursorDecl(cursor);
7922 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7923 switch (VD->getTLSKind()) {
7924 case VarDecl::TLS_None:
7925 return CXTLS_None;
7926 case VarDecl::TLS_Dynamic:
7927 return CXTLS_Dynamic;
7928 case VarDecl::TLS_Static:
7929 return CXTLS_Static;
7930 }
7931 }
7932
7933 return CXTLS_None;
7934}
7935
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007936 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007937 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007938 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007939static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007941 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007942
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007943 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007944 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7945 return FunTmpl;
7946
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007947 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007948 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7949 return ClassTmpl;
7950
7951 return D;
7952}
7953
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007954
7955enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7956 StorageClass sc = SC_None;
7957 const Decl *D = getCursorDecl(C);
7958 if (D) {
7959 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7960 sc = FD->getStorageClass();
7961 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7962 sc = VD->getStorageClass();
7963 } else {
7964 return CX_SC_Invalid;
7965 }
7966 } else {
7967 return CX_SC_Invalid;
7968 }
7969 switch (sc) {
7970 case SC_None:
7971 return CX_SC_None;
7972 case SC_Extern:
7973 return CX_SC_Extern;
7974 case SC_Static:
7975 return CX_SC_Static;
7976 case SC_PrivateExtern:
7977 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007978 case SC_Auto:
7979 return CX_SC_Auto;
7980 case SC_Register:
7981 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007982 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007983 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007984}
7985
Guy Benyei11169dd2012-12-18 14:30:41 +00007986CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7987 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007988 if (const Decl *D = getCursorDecl(cursor)) {
7989 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007990 if (!DC)
7991 return clang_getNullCursor();
7992
7993 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7994 getCursorTU(cursor));
7995 }
7996 }
7997
7998 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007999 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008000 return MakeCXCursor(D, getCursorTU(cursor));
8001 }
8002
8003 return clang_getNullCursor();
8004}
8005
8006CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8007 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008008 if (const Decl *D = getCursorDecl(cursor)) {
8009 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008010 if (!DC)
8011 return clang_getNullCursor();
8012
8013 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8014 getCursorTU(cursor));
8015 }
8016 }
8017
8018 // FIXME: Note that we can't easily compute the lexical context of a
8019 // statement or expression, so we return nothing.
8020 return clang_getNullCursor();
8021}
8022
8023CXFile clang_getIncludedFile(CXCursor cursor) {
8024 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008025 return nullptr;
8026
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008027 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008028 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008029}
8030
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008031unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8032 if (C.kind != CXCursor_ObjCPropertyDecl)
8033 return CXObjCPropertyAttr_noattr;
8034
8035 unsigned Result = CXObjCPropertyAttr_noattr;
8036 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8037 ObjCPropertyDecl::PropertyAttributeKind Attr =
8038 PD->getPropertyAttributesAsWritten();
8039
8040#define SET_CXOBJCPROP_ATTR(A) \
8041 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8042 Result |= CXObjCPropertyAttr_##A
8043 SET_CXOBJCPROP_ATTR(readonly);
8044 SET_CXOBJCPROP_ATTR(getter);
8045 SET_CXOBJCPROP_ATTR(assign);
8046 SET_CXOBJCPROP_ATTR(readwrite);
8047 SET_CXOBJCPROP_ATTR(retain);
8048 SET_CXOBJCPROP_ATTR(copy);
8049 SET_CXOBJCPROP_ATTR(nonatomic);
8050 SET_CXOBJCPROP_ATTR(setter);
8051 SET_CXOBJCPROP_ATTR(atomic);
8052 SET_CXOBJCPROP_ATTR(weak);
8053 SET_CXOBJCPROP_ATTR(strong);
8054 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008055 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008056#undef SET_CXOBJCPROP_ATTR
8057
8058 return Result;
8059}
8060
Michael Wu6e88f532018-08-03 05:38:29 +00008061CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8062 if (C.kind != CXCursor_ObjCPropertyDecl)
8063 return cxstring::createNull();
8064
8065 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8066 Selector sel = PD->getGetterName();
8067 if (sel.isNull())
8068 return cxstring::createNull();
8069
8070 return cxstring::createDup(sel.getAsString());
8071}
8072
8073CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8074 if (C.kind != CXCursor_ObjCPropertyDecl)
8075 return cxstring::createNull();
8076
8077 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8078 Selector sel = PD->getSetterName();
8079 if (sel.isNull())
8080 return cxstring::createNull();
8081
8082 return cxstring::createDup(sel.getAsString());
8083}
8084
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008085unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8086 if (!clang_isDeclaration(C.kind))
8087 return CXObjCDeclQualifier_None;
8088
8089 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8090 const Decl *D = getCursorDecl(C);
8091 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8092 QT = MD->getObjCDeclQualifier();
8093 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8094 QT = PD->getObjCDeclQualifier();
8095 if (QT == Decl::OBJC_TQ_None)
8096 return CXObjCDeclQualifier_None;
8097
8098 unsigned Result = CXObjCDeclQualifier_None;
8099 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8100 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8101 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8102 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8103 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8104 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8105
8106 return Result;
8107}
8108
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008109unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8110 if (!clang_isDeclaration(C.kind))
8111 return 0;
8112
8113 const Decl *D = getCursorDecl(C);
8114 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8115 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8116 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8117 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8118
8119 return 0;
8120}
8121
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008122unsigned clang_Cursor_isVariadic(CXCursor C) {
8123 if (!clang_isDeclaration(C.kind))
8124 return 0;
8125
8126 const Decl *D = getCursorDecl(C);
8127 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8128 return FD->isVariadic();
8129 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8130 return MD->isVariadic();
8131
8132 return 0;
8133}
8134
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008135unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8136 CXString *language, CXString *definedIn,
8137 unsigned *isGenerated) {
8138 if (!clang_isDeclaration(C.kind))
8139 return 0;
8140
8141 const Decl *D = getCursorDecl(C);
8142
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008143 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008144 if (language)
8145 *language = cxstring::createDup(attr->getLanguage());
8146 if (definedIn)
8147 *definedIn = cxstring::createDup(attr->getDefinedIn());
8148 if (isGenerated)
8149 *isGenerated = attr->getGeneratedDeclaration();
8150 return 1;
8151 }
8152 return 0;
8153}
8154
Guy Benyei11169dd2012-12-18 14:30:41 +00008155CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8156 if (!clang_isDeclaration(C.kind))
8157 return clang_getNullRange();
8158
8159 const Decl *D = getCursorDecl(C);
8160 ASTContext &Context = getCursorContext(C);
8161 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8162 if (!RC)
8163 return clang_getNullRange();
8164
8165 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8166}
8167
8168CXString clang_Cursor_getRawCommentText(CXCursor C) {
8169 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008170 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008171
8172 const Decl *D = getCursorDecl(C);
8173 ASTContext &Context = getCursorContext(C);
8174 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8175 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8176 StringRef();
8177
8178 // Don't duplicate the string because RawText points directly into source
8179 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008180 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008181}
8182
8183CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8184 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008185 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008186
8187 const Decl *D = getCursorDecl(C);
8188 const ASTContext &Context = getCursorContext(C);
8189 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8190
8191 if (RC) {
8192 StringRef BriefText = RC->getBriefText(Context);
8193
8194 // Don't duplicate the string because RawComment ensures that this memory
8195 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008196 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008197 }
8198
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008199 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008200}
8201
Guy Benyei11169dd2012-12-18 14:30:41 +00008202CXModule clang_Cursor_getModule(CXCursor C) {
8203 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008204 if (const ImportDecl *ImportD =
8205 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008206 return ImportD->getImportedModule();
8207 }
8208
Craig Topper69186e72014-06-08 08:38:04 +00008209 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008210}
8211
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008212CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8213 if (isNotUsableTU(TU)) {
8214 LOG_BAD_TU(TU);
8215 return nullptr;
8216 }
8217 if (!File)
8218 return nullptr;
8219 FileEntry *FE = static_cast<FileEntry *>(File);
8220
8221 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8222 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8223 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8224
Richard Smithfeb54b62014-10-23 02:01:19 +00008225 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008226}
8227
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008228CXFile clang_Module_getASTFile(CXModule CXMod) {
8229 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008230 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008231 Module *Mod = static_cast<Module*>(CXMod);
8232 return const_cast<FileEntry *>(Mod->getASTFile());
8233}
8234
Guy Benyei11169dd2012-12-18 14:30:41 +00008235CXModule clang_Module_getParent(CXModule CXMod) {
8236 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008237 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 Module *Mod = static_cast<Module*>(CXMod);
8239 return Mod->Parent;
8240}
8241
8242CXString clang_Module_getName(CXModule CXMod) {
8243 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008244 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008245 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008246 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008247}
8248
8249CXString clang_Module_getFullName(CXModule CXMod) {
8250 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008251 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008252 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008253 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008254}
8255
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008256int clang_Module_isSystem(CXModule CXMod) {
8257 if (!CXMod)
8258 return 0;
8259 Module *Mod = static_cast<Module*>(CXMod);
8260 return Mod->IsSystem;
8261}
8262
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008263unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8264 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008265 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008266 LOG_BAD_TU(TU);
8267 return 0;
8268 }
8269 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008270 return 0;
8271 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008272 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8273 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8274 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008275}
8276
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008277CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8278 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008279 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008280 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008281 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008282 }
8283 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008284 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008285 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008286 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008287
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008288 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8289 if (Index < TopHeaders.size())
8290 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008291
Craig Topper69186e72014-06-08 08:38:04 +00008292 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008293}
8294
Guy Benyei11169dd2012-12-18 14:30:41 +00008295//===----------------------------------------------------------------------===//
8296// C++ AST instrospection.
8297//===----------------------------------------------------------------------===//
8298
Jonathan Coe29565352016-04-27 12:48:25 +00008299unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8300 if (!clang_isDeclaration(C.kind))
8301 return 0;
8302
8303 const Decl *D = cxcursor::getCursorDecl(C);
8304 const CXXConstructorDecl *Constructor =
8305 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8306 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8307}
8308
8309unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8310 if (!clang_isDeclaration(C.kind))
8311 return 0;
8312
8313 const Decl *D = cxcursor::getCursorDecl(C);
8314 const CXXConstructorDecl *Constructor =
8315 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8316 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8317}
8318
8319unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8320 if (!clang_isDeclaration(C.kind))
8321 return 0;
8322
8323 const Decl *D = cxcursor::getCursorDecl(C);
8324 const CXXConstructorDecl *Constructor =
8325 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8326 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8327}
8328
8329unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8330 if (!clang_isDeclaration(C.kind))
8331 return 0;
8332
8333 const Decl *D = cxcursor::getCursorDecl(C);
8334 const CXXConstructorDecl *Constructor =
8335 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8336 // Passing 'false' excludes constructors marked 'explicit'.
8337 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8338}
8339
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008340unsigned clang_CXXField_isMutable(CXCursor C) {
8341 if (!clang_isDeclaration(C.kind))
8342 return 0;
8343
8344 if (const auto D = cxcursor::getCursorDecl(C))
8345 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8346 return FD->isMutable() ? 1 : 0;
8347 return 0;
8348}
8349
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008350unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8351 if (!clang_isDeclaration(C.kind))
8352 return 0;
8353
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008354 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008355 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008356 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008357 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8358}
8359
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008360unsigned clang_CXXMethod_isConst(CXCursor C) {
8361 if (!clang_isDeclaration(C.kind))
8362 return 0;
8363
8364 const Decl *D = cxcursor::getCursorDecl(C);
8365 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008366 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008367 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
8368}
8369
Jonathan Coe29565352016-04-27 12:48:25 +00008370unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8371 if (!clang_isDeclaration(C.kind))
8372 return 0;
8373
8374 const Decl *D = cxcursor::getCursorDecl(C);
8375 const CXXMethodDecl *Method =
8376 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8377 return (Method && Method->isDefaulted()) ? 1 : 0;
8378}
8379
Guy Benyei11169dd2012-12-18 14:30:41 +00008380unsigned clang_CXXMethod_isStatic(CXCursor C) {
8381 if (!clang_isDeclaration(C.kind))
8382 return 0;
8383
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008384 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008385 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008386 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008387 return (Method && Method->isStatic()) ? 1 : 0;
8388}
8389
8390unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8391 if (!clang_isDeclaration(C.kind))
8392 return 0;
8393
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008394 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008395 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008396 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008397 return (Method && Method->isVirtual()) ? 1 : 0;
8398}
Guy Benyei11169dd2012-12-18 14:30:41 +00008399
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008400unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8401 if (!clang_isDeclaration(C.kind))
8402 return 0;
8403
8404 const auto *D = cxcursor::getCursorDecl(C);
8405 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8406 if (RD)
8407 RD = RD->getDefinition();
8408 return (RD && RD->isAbstract()) ? 1 : 0;
8409}
8410
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008411unsigned clang_EnumDecl_isScoped(CXCursor C) {
8412 if (!clang_isDeclaration(C.kind))
8413 return 0;
8414
8415 const Decl *D = cxcursor::getCursorDecl(C);
8416 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8417 return (Enum && Enum->isScoped()) ? 1 : 0;
8418}
8419
Guy Benyei11169dd2012-12-18 14:30:41 +00008420//===----------------------------------------------------------------------===//
8421// Attribute introspection.
8422//===----------------------------------------------------------------------===//
8423
Guy Benyei11169dd2012-12-18 14:30:41 +00008424CXType clang_getIBOutletCollectionType(CXCursor C) {
8425 if (C.kind != CXCursor_IBOutletCollectionAttr)
8426 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8427
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008428 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008429 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8430
8431 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8432}
Guy Benyei11169dd2012-12-18 14:30:41 +00008433
8434//===----------------------------------------------------------------------===//
8435// Inspecting memory usage.
8436//===----------------------------------------------------------------------===//
8437
8438typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8439
8440static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8441 enum CXTUResourceUsageKind k,
8442 unsigned long amount) {
8443 CXTUResourceUsageEntry entry = { k, amount };
8444 entries.push_back(entry);
8445}
8446
Guy Benyei11169dd2012-12-18 14:30:41 +00008447const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8448 const char *str = "";
8449 switch (kind) {
8450 case CXTUResourceUsage_AST:
8451 str = "ASTContext: expressions, declarations, and types";
8452 break;
8453 case CXTUResourceUsage_Identifiers:
8454 str = "ASTContext: identifiers";
8455 break;
8456 case CXTUResourceUsage_Selectors:
8457 str = "ASTContext: selectors";
8458 break;
8459 case CXTUResourceUsage_GlobalCompletionResults:
8460 str = "Code completion: cached global results";
8461 break;
8462 case CXTUResourceUsage_SourceManagerContentCache:
8463 str = "SourceManager: content cache allocator";
8464 break;
8465 case CXTUResourceUsage_AST_SideTables:
8466 str = "ASTContext: side tables";
8467 break;
8468 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8469 str = "SourceManager: malloc'ed memory buffers";
8470 break;
8471 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8472 str = "SourceManager: mmap'ed memory buffers";
8473 break;
8474 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8475 str = "ExternalASTSource: malloc'ed memory buffers";
8476 break;
8477 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8478 str = "ExternalASTSource: mmap'ed memory buffers";
8479 break;
8480 case CXTUResourceUsage_Preprocessor:
8481 str = "Preprocessor: malloc'ed memory";
8482 break;
8483 case CXTUResourceUsage_PreprocessingRecord:
8484 str = "Preprocessor: PreprocessingRecord";
8485 break;
8486 case CXTUResourceUsage_SourceManager_DataStructures:
8487 str = "SourceManager: data structures and tables";
8488 break;
8489 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8490 str = "Preprocessor: header search tables";
8491 break;
8492 }
8493 return str;
8494}
8495
8496CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008497 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008498 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008499 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008500 return usage;
8501 }
8502
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008503 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008504 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008505 ASTContext &astContext = astUnit->getASTContext();
8506
8507 // How much memory is used by AST nodes and types?
8508 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8509 (unsigned long) astContext.getASTAllocatedMemory());
8510
8511 // How much memory is used by identifiers?
8512 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8513 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8514
8515 // How much memory is used for selectors?
8516 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8517 (unsigned long) astContext.Selectors.getTotalMemory());
8518
8519 // How much memory is used by ASTContext's side tables?
8520 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8521 (unsigned long) astContext.getSideTableAllocatedMemory());
8522
8523 // How much memory is used for caching global code completion results?
8524 unsigned long completionBytes = 0;
8525 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008526 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008527 completionBytes = completionAllocator->getTotalMemory();
8528 }
8529 createCXTUResourceUsageEntry(*entries,
8530 CXTUResourceUsage_GlobalCompletionResults,
8531 completionBytes);
8532
8533 // How much memory is being used by SourceManager's content cache?
8534 createCXTUResourceUsageEntry(*entries,
8535 CXTUResourceUsage_SourceManagerContentCache,
8536 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8537
8538 // How much memory is being used by the MemoryBuffer's in SourceManager?
8539 const SourceManager::MemoryBufferSizes &srcBufs =
8540 astUnit->getSourceManager().getMemoryBufferSizes();
8541
8542 createCXTUResourceUsageEntry(*entries,
8543 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8544 (unsigned long) srcBufs.malloc_bytes);
8545 createCXTUResourceUsageEntry(*entries,
8546 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8547 (unsigned long) srcBufs.mmap_bytes);
8548 createCXTUResourceUsageEntry(*entries,
8549 CXTUResourceUsage_SourceManager_DataStructures,
8550 (unsigned long) astContext.getSourceManager()
8551 .getDataStructureSizes());
8552
8553 // How much memory is being used by the ExternalASTSource?
8554 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8555 const ExternalASTSource::MemoryBufferSizes &sizes =
8556 esrc->getMemoryBufferSizes();
8557
8558 createCXTUResourceUsageEntry(*entries,
8559 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8560 (unsigned long) sizes.malloc_bytes);
8561 createCXTUResourceUsageEntry(*entries,
8562 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8563 (unsigned long) sizes.mmap_bytes);
8564 }
8565
8566 // How much memory is being used by the Preprocessor?
8567 Preprocessor &pp = astUnit->getPreprocessor();
8568 createCXTUResourceUsageEntry(*entries,
8569 CXTUResourceUsage_Preprocessor,
8570 pp.getTotalMemory());
8571
8572 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8573 createCXTUResourceUsageEntry(*entries,
8574 CXTUResourceUsage_PreprocessingRecord,
8575 pRec->getTotalMemory());
8576 }
8577
8578 createCXTUResourceUsageEntry(*entries,
8579 CXTUResourceUsage_Preprocessor_HeaderSearch,
8580 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008581
Guy Benyei11169dd2012-12-18 14:30:41 +00008582 CXTUResourceUsage usage = { (void*) entries.get(),
8583 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008584 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008585 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008586 return usage;
8587}
8588
8589void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8590 if (usage.data)
8591 delete (MemUsageEntries*) usage.data;
8592}
8593
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008594CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8595 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008596 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008597 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008598
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008599 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008600 LOG_BAD_TU(TU);
8601 return skipped;
8602 }
8603
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008604 if (!file)
8605 return skipped;
8606
8607 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8608 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8609 if (!ppRec)
8610 return skipped;
8611
8612 ASTContext &Ctx = astUnit->getASTContext();
8613 SourceManager &sm = Ctx.getSourceManager();
8614 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8615 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008616 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008617
8618 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8619 std::vector<SourceRange> wantedRanges;
8620 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8621 i != ei; ++i) {
8622 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8623 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008624 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8625 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008626 }
8627
8628 skipped->count = wantedRanges.size();
8629 skipped->ranges = new CXSourceRange[skipped->count];
8630 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8631 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8632
8633 return skipped;
8634}
8635
Cameron Desrochersd8091282016-08-18 15:43:55 +00008636CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8637 CXSourceRangeList *skipped = new CXSourceRangeList;
8638 skipped->count = 0;
8639 skipped->ranges = nullptr;
8640
8641 if (isNotUsableTU(TU)) {
8642 LOG_BAD_TU(TU);
8643 return skipped;
8644 }
8645
8646 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8647 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8648 if (!ppRec)
8649 return skipped;
8650
8651 ASTContext &Ctx = astUnit->getASTContext();
8652
8653 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8654
8655 skipped->count = SkippedRanges.size();
8656 skipped->ranges = new CXSourceRange[skipped->count];
8657 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8658 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8659
8660 return skipped;
8661}
8662
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008663void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8664 if (ranges) {
8665 delete[] ranges->ranges;
8666 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008667 }
8668}
8669
Guy Benyei11169dd2012-12-18 14:30:41 +00008670void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8671 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8672 for (unsigned I = 0; I != Usage.numEntries; ++I)
8673 fprintf(stderr, " %s: %lu\n",
8674 clang_getTUResourceUsageName(Usage.entries[I].kind),
8675 Usage.entries[I].amount);
8676
8677 clang_disposeCXTUResourceUsage(Usage);
8678}
8679
8680//===----------------------------------------------------------------------===//
8681// Misc. utility functions.
8682//===----------------------------------------------------------------------===//
8683
Richard Smith0a7b2972018-07-03 21:34:13 +00008684/// Default to using our desired 8 MB stack size on "safety" threads.
8685static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008686
8687namespace clang {
8688
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008689bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008690 unsigned Size) {
8691 if (!Size)
8692 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008693 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008694 return CRC.RunSafelyOnThread(Fn, Size);
8695 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008696}
8697
8698unsigned GetSafetyThreadStackSize() {
8699 return SafetyStackThreadSize;
8700}
8701
8702void SetSafetyThreadStackSize(unsigned Value) {
8703 SafetyStackThreadSize = Value;
8704}
8705
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008706}
Guy Benyei11169dd2012-12-18 14:30:41 +00008707
8708void clang::setThreadBackgroundPriority() {
8709 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8710 return;
8711
Alp Toker1a86ad22014-07-06 06:24:00 +00008712#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008713 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8714#endif
8715}
8716
8717void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8718 if (!Unit)
8719 return;
8720
8721 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8722 DEnd = Unit->stored_diag_end();
8723 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008724 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008725 CXString Msg = clang_formatDiagnostic(&Diag,
8726 clang_defaultDiagnosticDisplayOptions());
8727 fprintf(stderr, "%s\n", clang_getCString(Msg));
8728 clang_disposeString(Msg);
8729 }
Nico Weber1865df42018-04-27 19:11:14 +00008730#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008731 // On Windows, force a flush, since there may be multiple copies of
8732 // stderr and stdout in the file system, all with different buffers
8733 // but writing to the same device.
8734 fflush(stderr);
8735#endif
8736}
8737
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008738MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8739 SourceLocation MacroDefLoc,
8740 CXTranslationUnit TU){
8741 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008742 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008743 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008744 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008745
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008746 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008747 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008748 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008749 if (MD) {
8750 for (MacroDirective::DefInfo
8751 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8752 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8753 return Def.getMacroInfo();
8754 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008755 }
8756
Craig Topper69186e72014-06-08 08:38:04 +00008757 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008758}
8759
Richard Smith66a81862015-05-04 02:25:31 +00008760const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008761 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008762 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008763 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008764 const IdentifierInfo *II = MacroDef->getName();
8765 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008766 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008767
8768 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8769}
8770
Richard Smith66a81862015-05-04 02:25:31 +00008771MacroDefinitionRecord *
8772cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8773 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008774 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008775 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008776 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008777 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008778
8779 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008780 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008781 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8782 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008783 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008784
8785 // Check that the token is inside the definition and not its argument list.
8786 SourceManager &SM = Unit->getSourceManager();
8787 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008788 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008789 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008790 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008791
8792 Preprocessor &PP = Unit->getPreprocessor();
8793 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8794 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008795 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008796
Alp Toker2d57cea2014-05-17 04:53:25 +00008797 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008798 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008799 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008800
8801 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008802 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008803 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008804
Richard Smith20e883e2015-04-29 23:20:19 +00008805 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008806 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008807 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008808
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008809 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008810}
8811
Richard Smith66a81862015-05-04 02:25:31 +00008812MacroDefinitionRecord *
8813cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8814 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008815 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008816 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008817
8818 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008819 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008820 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008821 Preprocessor &PP = Unit->getPreprocessor();
8822 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008823 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008824 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8825 Token Tok;
8826 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008827 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008828
8829 return checkForMacroInMacroDefinition(MI, Tok, TU);
8830}
8831
Guy Benyei11169dd2012-12-18 14:30:41 +00008832CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008833 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008834}
8835
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008836Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8837 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008838 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008839 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008840 if (Unit->isMainFileAST())
8841 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008842 return *this;
8843 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008844 } else {
8845 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008846 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008847 return *this;
8848}
8849
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008850Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8851 *this << FE->getName();
8852 return *this;
8853}
8854
8855Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8856 CXString cursorName = clang_getCursorDisplayName(cursor);
8857 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8858 clang_disposeString(cursorName);
8859 return *this;
8860}
8861
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008862Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8863 CXFile File;
8864 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008865 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008866 CXString FileName = clang_getFileName(File);
8867 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8868 clang_disposeString(FileName);
8869 return *this;
8870}
8871
8872Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8873 CXSourceLocation BLoc = clang_getRangeStart(range);
8874 CXSourceLocation ELoc = clang_getRangeEnd(range);
8875
8876 CXFile BFile;
8877 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008878 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008879
8880 CXFile EFile;
8881 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008882 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008883
8884 CXString BFileName = clang_getFileName(BFile);
8885 if (BFile == EFile) {
8886 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8887 BLine, BColumn, ELine, EColumn);
8888 } else {
8889 CXString EFileName = clang_getFileName(EFile);
8890 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8891 BLine, BColumn)
8892 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8893 ELine, EColumn);
8894 clang_disposeString(EFileName);
8895 }
8896 clang_disposeString(BFileName);
8897 return *this;
8898}
8899
8900Logger &cxindex::Logger::operator<<(CXString Str) {
8901 *this << clang_getCString(Str);
8902 return *this;
8903}
8904
8905Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8906 LogOS << Fmt;
8907 return *this;
8908}
8909
Chandler Carruth37ad2582014-06-27 15:14:39 +00008910static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8911
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008912cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008913 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008914
8915 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8916
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008917 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008918 OS << "[libclang:" << Name << ':';
8919
Alp Toker1a86ad22014-07-06 06:24:00 +00008920#ifdef USE_DARWIN_THREADS
8921 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008922 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8923 OS << tid << ':';
8924#endif
8925
8926 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8927 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008928 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008929
8930 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008931 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008932 OS << "--------------------------------------------------\n";
8933 }
8934}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008935
8936#ifdef CLANG_TOOL_EXTRA_BUILD
8937// This anchor is used to force the linker to link the clang-tidy plugin.
8938extern volatile int ClangTidyPluginAnchorSource;
8939static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8940 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008941
8942// This anchor is used to force the linker to link the clang-include-fixer
8943// plugin.
8944extern volatile int ClangIncludeFixerPluginAnchorSource;
8945static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8946 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008947#endif