blob: 62502720051967e1a2725cdcdacbc91ede0af06e [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
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002222void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2223 const OMPAtomicDefaultMemOrderClause *) {}
2224
Michael Wonge710d542015-08-07 16:16:36 +00002225void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2226 Visitor->AddStmt(C->getDevice());
2227}
2228
Kelvin Li099bb8c2015-11-24 20:50:12 +00002229void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002230 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002231 Visitor->AddStmt(C->getNumTeams());
2232}
2233
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002234void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002235 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002236 Visitor->AddStmt(C->getThreadLimit());
2237}
2238
Alexey Bataeva0569352015-12-01 10:17:31 +00002239void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2240 Visitor->AddStmt(C->getPriority());
2241}
2242
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002243void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2244 Visitor->AddStmt(C->getGrainsize());
2245}
2246
Alexey Bataev382967a2015-12-08 12:06:20 +00002247void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2248 Visitor->AddStmt(C->getNumTasks());
2249}
2250
Alexey Bataev28c75412015-12-15 08:19:24 +00002251void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2252 Visitor->AddStmt(C->getHint());
2253}
2254
Alexey Bataev756c1962013-09-24 03:17:45 +00002255template<typename T>
2256void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002257 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002258 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002259 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002260}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002261
2262void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002263 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002264 for (const auto *E : C->private_copies()) {
2265 Visitor->AddStmt(E);
2266 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002267}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002268void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2269 const OMPFirstprivateClause *C) {
2270 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002271 VisitOMPClauseWithPreInit(C);
2272 for (const auto *E : C->private_copies()) {
2273 Visitor->AddStmt(E);
2274 }
2275 for (const auto *E : C->inits()) {
2276 Visitor->AddStmt(E);
2277 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002278}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002279void OMPClauseEnqueue::VisitOMPLastprivateClause(
2280 const OMPLastprivateClause *C) {
2281 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002282 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002283 for (auto *E : C->private_copies()) {
2284 Visitor->AddStmt(E);
2285 }
2286 for (auto *E : C->source_exprs()) {
2287 Visitor->AddStmt(E);
2288 }
2289 for (auto *E : C->destination_exprs()) {
2290 Visitor->AddStmt(E);
2291 }
2292 for (auto *E : C->assignment_ops()) {
2293 Visitor->AddStmt(E);
2294 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002295}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002296void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002297 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002298}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002299void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2300 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002301 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002302 for (auto *E : C->privates()) {
2303 Visitor->AddStmt(E);
2304 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002305 for (auto *E : C->lhs_exprs()) {
2306 Visitor->AddStmt(E);
2307 }
2308 for (auto *E : C->rhs_exprs()) {
2309 Visitor->AddStmt(E);
2310 }
2311 for (auto *E : C->reduction_ops()) {
2312 Visitor->AddStmt(E);
2313 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002314}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002315void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2316 const OMPTaskReductionClause *C) {
2317 VisitOMPClauseList(C);
2318 VisitOMPClauseWithPostUpdate(C);
2319 for (auto *E : C->privates()) {
2320 Visitor->AddStmt(E);
2321 }
2322 for (auto *E : C->lhs_exprs()) {
2323 Visitor->AddStmt(E);
2324 }
2325 for (auto *E : C->rhs_exprs()) {
2326 Visitor->AddStmt(E);
2327 }
2328 for (auto *E : C->reduction_ops()) {
2329 Visitor->AddStmt(E);
2330 }
2331}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002332void OMPClauseEnqueue::VisitOMPInReductionClause(
2333 const OMPInReductionClause *C) {
2334 VisitOMPClauseList(C);
2335 VisitOMPClauseWithPostUpdate(C);
2336 for (auto *E : C->privates()) {
2337 Visitor->AddStmt(E);
2338 }
2339 for (auto *E : C->lhs_exprs()) {
2340 Visitor->AddStmt(E);
2341 }
2342 for (auto *E : C->rhs_exprs()) {
2343 Visitor->AddStmt(E);
2344 }
2345 for (auto *E : C->reduction_ops()) {
2346 Visitor->AddStmt(E);
2347 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002348 for (auto *E : C->taskgroup_descriptors())
2349 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002350}
Alexander Musman8dba6642014-04-22 13:09:42 +00002351void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2352 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002353 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002354 for (const auto *E : C->privates()) {
2355 Visitor->AddStmt(E);
2356 }
Alexander Musman3276a272015-03-21 10:12:56 +00002357 for (const auto *E : C->inits()) {
2358 Visitor->AddStmt(E);
2359 }
2360 for (const auto *E : C->updates()) {
2361 Visitor->AddStmt(E);
2362 }
2363 for (const auto *E : C->finals()) {
2364 Visitor->AddStmt(E);
2365 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002366 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002367 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002368}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002369void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2370 VisitOMPClauseList(C);
2371 Visitor->AddStmt(C->getAlignment());
2372}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002373void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2374 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002375 for (auto *E : C->source_exprs()) {
2376 Visitor->AddStmt(E);
2377 }
2378 for (auto *E : C->destination_exprs()) {
2379 Visitor->AddStmt(E);
2380 }
2381 for (auto *E : C->assignment_ops()) {
2382 Visitor->AddStmt(E);
2383 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002384}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002385void
2386OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2387 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002388 for (auto *E : C->source_exprs()) {
2389 Visitor->AddStmt(E);
2390 }
2391 for (auto *E : C->destination_exprs()) {
2392 Visitor->AddStmt(E);
2393 }
2394 for (auto *E : C->assignment_ops()) {
2395 Visitor->AddStmt(E);
2396 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002397}
Alexey Bataev6125da92014-07-21 11:26:11 +00002398void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2399 VisitOMPClauseList(C);
2400}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002401void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2402 VisitOMPClauseList(C);
2403}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002404void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2405 VisitOMPClauseList(C);
2406}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002407void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2408 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002409 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002410 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002411}
Alexey Bataev3392d762016-02-16 11:18:12 +00002412void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2413 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002414void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2415 VisitOMPClauseList(C);
2416}
Samuel Antaoec172c62016-05-26 17:49:04 +00002417void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2418 VisitOMPClauseList(C);
2419}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002420void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2421 VisitOMPClauseList(C);
2422}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002423void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2424 VisitOMPClauseList(C);
2425}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002426}
Alexey Bataev756c1962013-09-24 03:17:45 +00002427
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002428void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2429 unsigned size = WL.size();
2430 OMPClauseEnqueue Visitor(this);
2431 Visitor.Visit(S);
2432 if (size == WL.size())
2433 return;
2434 // Now reverse the entries we just added. This will match the DFS
2435 // ordering performed by the worklist.
2436 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2437 std::reverse(I, E);
2438}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002439void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2441}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002442void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 AddDecl(B->getBlockDecl());
2444}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002445void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 EnqueueChildren(E);
2447 AddTypeLoc(E->getTypeSourceInfo());
2448}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002449void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002450 for (auto &I : llvm::reverse(S->body()))
2451 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002452}
2453void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002454VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 AddStmt(S->getSubStmt());
2456 AddDeclarationNameInfo(S);
2457 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2458 AddNestedNameSpecifierLoc(QualifierLoc);
2459}
2460
2461void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002462VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002463 if (E->hasExplicitTemplateArgs())
2464 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 AddDeclarationNameInfo(E);
2466 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2467 AddNestedNameSpecifierLoc(QualifierLoc);
2468 if (!E->isImplicitAccess())
2469 AddStmt(E->getBase());
2470}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002471void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 // Enqueue the initializer , if any.
2473 AddStmt(E->getInitializer());
2474 // Enqueue the array size, if any.
2475 AddStmt(E->getArraySize());
2476 // Enqueue the allocated type.
2477 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2478 // Enqueue the placement arguments.
2479 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2480 AddStmt(E->getPlacementArg(I-1));
2481}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002482void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2484 AddStmt(CE->getArg(I-1));
2485 AddStmt(CE->getCallee());
2486 AddStmt(CE->getArg(0));
2487}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002488void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2489 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 // Visit the name of the type being destroyed.
2491 AddTypeLoc(E->getDestroyedTypeInfo());
2492 // Visit the scope type that looks disturbingly like the nested-name-specifier
2493 // but isn't.
2494 AddTypeLoc(E->getScopeTypeInfo());
2495 // Visit the nested-name-specifier.
2496 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2497 AddNestedNameSpecifierLoc(QualifierLoc);
2498 // Visit base expression.
2499 AddStmt(E->getBase());
2500}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002501void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2502 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 AddTypeLoc(E->getTypeSourceInfo());
2504}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002505void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2506 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 EnqueueChildren(E);
2508 AddTypeLoc(E->getTypeSourceInfo());
2509}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002510void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 EnqueueChildren(E);
2512 if (E->isTypeOperand())
2513 AddTypeLoc(E->getTypeOperandSourceInfo());
2514}
2515
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002516void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2517 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 EnqueueChildren(E);
2519 AddTypeLoc(E->getTypeSourceInfo());
2520}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002521void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 EnqueueChildren(E);
2523 if (E->isTypeOperand())
2524 AddTypeLoc(E->getTypeOperandSourceInfo());
2525}
2526
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002527void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 EnqueueChildren(S);
2529 AddDecl(S->getExceptionDecl());
2530}
2531
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002532void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002533 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002534 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002535 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002536}
2537
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002538void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002539 if (DR->hasExplicitTemplateArgs())
2540 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 WL.push_back(DeclRefExprParts(DR, Parent));
2542}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002543void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2544 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002545 if (E->hasExplicitTemplateArgs())
2546 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 AddDeclarationNameInfo(E);
2548 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2549}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002550void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 unsigned size = WL.size();
2552 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002553 for (const auto *D : S->decls()) {
2554 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 isFirst = false;
2556 }
2557 if (size == WL.size())
2558 return;
2559 // Now reverse the entries we just added. This will match the DFS
2560 // ordering performed by the worklist.
2561 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2562 std::reverse(I, E);
2563}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002564void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002566 for (const DesignatedInitExpr::Designator &D :
2567 llvm::reverse(E->designators())) {
2568 if (D.isFieldDesignator()) {
2569 if (FieldDecl *Field = D.getField())
2570 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 continue;
2572 }
David Majnemerf7e36092016-06-23 00:15:04 +00002573 if (D.isArrayDesignator()) {
2574 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 continue;
2576 }
David Majnemerf7e36092016-06-23 00:15:04 +00002577 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2578 AddStmt(E->getArrayRangeEnd(D));
2579 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 }
2581}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002582void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 EnqueueChildren(E);
2584 AddTypeLoc(E->getTypeInfoAsWritten());
2585}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002586void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 AddStmt(FS->getBody());
2588 AddStmt(FS->getInc());
2589 AddStmt(FS->getCond());
2590 AddDecl(FS->getConditionVariable());
2591 AddStmt(FS->getInit());
2592}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002593void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2595}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002596void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 AddStmt(If->getElse());
2598 AddStmt(If->getThen());
2599 AddStmt(If->getCond());
2600 AddDecl(If->getConditionVariable());
2601}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002602void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 // We care about the syntactic form of the initializer list, only.
2604 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2605 IE = Syntactic;
2606 EnqueueChildren(IE);
2607}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002608void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 WL.push_back(MemberExprParts(M, Parent));
2610
2611 // If the base of the member access expression is an implicit 'this', don't
2612 // visit it.
2613 // FIXME: If we ever want to show these implicit accesses, this will be
2614 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002615 if (M->isImplicitAccess())
2616 return;
2617
2618 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002619 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002620 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2621 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2622 if (FD->isAnonymousStructOrUnion()) {
2623 AddStmt(SubME->getBase());
2624 return;
2625 }
2626 }
2627 }
2628
2629 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002630}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002631void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002632 AddTypeLoc(E->getEncodedTypeSourceInfo());
2633}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002634void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 EnqueueChildren(M);
2636 AddTypeLoc(M->getClassReceiverTypeInfo());
2637}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002638void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 // Visit the components of the offsetof expression.
2640 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 const OffsetOfNode &Node = E->getComponent(I-1);
2642 switch (Node.getKind()) {
2643 case OffsetOfNode::Array:
2644 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2645 break;
2646 case OffsetOfNode::Field:
2647 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2648 break;
2649 case OffsetOfNode::Identifier:
2650 case OffsetOfNode::Base:
2651 continue;
2652 }
2653 }
2654 // Visit the type into which we're computing the offset.
2655 AddTypeLoc(E->getTypeSourceInfo());
2656}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002657void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002658 if (E->hasExplicitTemplateArgs())
2659 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 WL.push_back(OverloadExprParts(E, Parent));
2661}
2662void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002663 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 EnqueueChildren(E);
2665 if (E->isArgumentType())
2666 AddTypeLoc(E->getArgumentTypeInfo());
2667}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002668void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 EnqueueChildren(S);
2670}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002671void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 AddStmt(S->getBody());
2673 AddStmt(S->getCond());
2674 AddDecl(S->getConditionVariable());
2675}
2676
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002677void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 AddStmt(W->getBody());
2679 AddStmt(W->getCond());
2680 AddDecl(W->getConditionVariable());
2681}
2682
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002683void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 for (unsigned I = E->getNumArgs(); I > 0; --I)
2685 AddTypeLoc(E->getArg(I-1));
2686}
2687
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002688void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 AddTypeLoc(E->getQueriedTypeSourceInfo());
2690}
2691
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002692void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 EnqueueChildren(E);
2694}
2695
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002696void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 VisitOverloadExpr(U);
2698 if (!U->isImplicitAccess())
2699 AddStmt(U->getBase());
2700}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002701void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 AddStmt(E->getSubExpr());
2703 AddTypeLoc(E->getWrittenTypeInfo());
2704}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002705void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 WL.push_back(SizeOfPackExprParts(E, Parent));
2707}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002708void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 // If the opaque value has a source expression, just transparently
2710 // visit that. This is useful for (e.g.) pseudo-object expressions.
2711 if (Expr *SourceExpr = E->getSourceExpr())
2712 return Visit(SourceExpr);
2713}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002714void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 AddStmt(E->getBody());
2716 WL.push_back(LambdaExprParts(E, Parent));
2717}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002718void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 // Treat the expression like its syntactic form.
2720 Visit(E->getSyntacticForm());
2721}
2722
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002723void EnqueueVisitor::VisitOMPExecutableDirective(
2724 const OMPExecutableDirective *D) {
2725 EnqueueChildren(D);
2726 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2727 E = D->clauses().end();
2728 I != E; ++I)
2729 EnqueueChildren(*I);
2730}
2731
Alexander Musman3aaab662014-08-19 11:27:13 +00002732void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2733 VisitOMPExecutableDirective(D);
2734}
2735
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002736void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2737 VisitOMPExecutableDirective(D);
2738}
2739
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002740void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002741 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002742}
2743
Alexey Bataevf29276e2014-06-18 04:14:57 +00002744void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002745 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002746}
2747
Alexander Musmanf82886e2014-09-18 05:12:34 +00002748void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2749 VisitOMPLoopDirective(D);
2750}
2751
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002752void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2753 VisitOMPExecutableDirective(D);
2754}
2755
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002756void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2757 VisitOMPExecutableDirective(D);
2758}
2759
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002760void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2761 VisitOMPExecutableDirective(D);
2762}
2763
Alexander Musman80c22892014-07-17 08:54:58 +00002764void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2765 VisitOMPExecutableDirective(D);
2766}
2767
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002768void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2769 VisitOMPExecutableDirective(D);
2770 AddDeclarationNameInfo(D);
2771}
2772
Alexey Bataev4acb8592014-07-07 13:01:15 +00002773void
2774EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002775 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002776}
2777
Alexander Musmane4e893b2014-09-23 09:33:00 +00002778void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2779 const OMPParallelForSimdDirective *D) {
2780 VisitOMPLoopDirective(D);
2781}
2782
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002783void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2784 const OMPParallelSectionsDirective *D) {
2785 VisitOMPExecutableDirective(D);
2786}
2787
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002788void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2789 VisitOMPExecutableDirective(D);
2790}
2791
Alexey Bataev68446b72014-07-18 07:47:19 +00002792void
2793EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2794 VisitOMPExecutableDirective(D);
2795}
2796
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002797void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2798 VisitOMPExecutableDirective(D);
2799}
2800
Alexey Bataev2df347a2014-07-18 10:17:07 +00002801void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2802 VisitOMPExecutableDirective(D);
2803}
2804
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002805void EnqueueVisitor::VisitOMPTaskgroupDirective(
2806 const OMPTaskgroupDirective *D) {
2807 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002808 if (const Expr *E = D->getReductionRef())
2809 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002810}
2811
Alexey Bataev6125da92014-07-21 11:26:11 +00002812void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2813 VisitOMPExecutableDirective(D);
2814}
2815
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002816void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2817 VisitOMPExecutableDirective(D);
2818}
2819
Alexey Bataev0162e452014-07-22 10:10:35 +00002820void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2821 VisitOMPExecutableDirective(D);
2822}
2823
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002824void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2825 VisitOMPExecutableDirective(D);
2826}
2827
Michael Wong65f367f2015-07-21 13:44:28 +00002828void EnqueueVisitor::VisitOMPTargetDataDirective(const
2829 OMPTargetDataDirective *D) {
2830 VisitOMPExecutableDirective(D);
2831}
2832
Samuel Antaodf67fc42016-01-19 19:15:56 +00002833void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2834 const OMPTargetEnterDataDirective *D) {
2835 VisitOMPExecutableDirective(D);
2836}
2837
Samuel Antao72590762016-01-19 20:04:50 +00002838void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2839 const OMPTargetExitDataDirective *D) {
2840 VisitOMPExecutableDirective(D);
2841}
2842
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002843void EnqueueVisitor::VisitOMPTargetParallelDirective(
2844 const OMPTargetParallelDirective *D) {
2845 VisitOMPExecutableDirective(D);
2846}
2847
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002848void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2849 const OMPTargetParallelForDirective *D) {
2850 VisitOMPLoopDirective(D);
2851}
2852
Alexey Bataev13314bf2014-10-09 04:18:56 +00002853void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2854 VisitOMPExecutableDirective(D);
2855}
2856
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002857void EnqueueVisitor::VisitOMPCancellationPointDirective(
2858 const OMPCancellationPointDirective *D) {
2859 VisitOMPExecutableDirective(D);
2860}
2861
Alexey Bataev80909872015-07-02 11:25:17 +00002862void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2863 VisitOMPExecutableDirective(D);
2864}
2865
Alexey Bataev49f6e782015-12-01 04:18:41 +00002866void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2867 VisitOMPLoopDirective(D);
2868}
2869
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002870void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2871 const OMPTaskLoopSimdDirective *D) {
2872 VisitOMPLoopDirective(D);
2873}
2874
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002875void EnqueueVisitor::VisitOMPDistributeDirective(
2876 const OMPDistributeDirective *D) {
2877 VisitOMPLoopDirective(D);
2878}
2879
Carlo Bertolli9925f152016-06-27 14:55:37 +00002880void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2881 const OMPDistributeParallelForDirective *D) {
2882 VisitOMPLoopDirective(D);
2883}
2884
Kelvin Li4a39add2016-07-05 05:00:15 +00002885void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2886 const OMPDistributeParallelForSimdDirective *D) {
2887 VisitOMPLoopDirective(D);
2888}
2889
Kelvin Li787f3fc2016-07-06 04:45:38 +00002890void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2891 const OMPDistributeSimdDirective *D) {
2892 VisitOMPLoopDirective(D);
2893}
2894
Kelvin Lia579b912016-07-14 02:54:56 +00002895void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2896 const OMPTargetParallelForSimdDirective *D) {
2897 VisitOMPLoopDirective(D);
2898}
2899
Kelvin Li986330c2016-07-20 22:57:10 +00002900void EnqueueVisitor::VisitOMPTargetSimdDirective(
2901 const OMPTargetSimdDirective *D) {
2902 VisitOMPLoopDirective(D);
2903}
2904
Kelvin Li02532872016-08-05 14:37:37 +00002905void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2906 const OMPTeamsDistributeDirective *D) {
2907 VisitOMPLoopDirective(D);
2908}
2909
Kelvin Li4e325f72016-10-25 12:50:55 +00002910void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2911 const OMPTeamsDistributeSimdDirective *D) {
2912 VisitOMPLoopDirective(D);
2913}
2914
Kelvin Li579e41c2016-11-30 23:51:03 +00002915void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2916 const OMPTeamsDistributeParallelForSimdDirective *D) {
2917 VisitOMPLoopDirective(D);
2918}
2919
Kelvin Li7ade93f2016-12-09 03:24:30 +00002920void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2921 const OMPTeamsDistributeParallelForDirective *D) {
2922 VisitOMPLoopDirective(D);
2923}
2924
Kelvin Libf594a52016-12-17 05:48:59 +00002925void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2926 const OMPTargetTeamsDirective *D) {
2927 VisitOMPExecutableDirective(D);
2928}
2929
Kelvin Li83c451e2016-12-25 04:52:54 +00002930void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2931 const OMPTargetTeamsDistributeDirective *D) {
2932 VisitOMPLoopDirective(D);
2933}
2934
Kelvin Li80e8f562016-12-29 22:16:30 +00002935void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2936 const OMPTargetTeamsDistributeParallelForDirective *D) {
2937 VisitOMPLoopDirective(D);
2938}
2939
Kelvin Li1851df52017-01-03 05:23:48 +00002940void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2941 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2942 VisitOMPLoopDirective(D);
2943}
2944
Kelvin Lida681182017-01-10 18:08:18 +00002945void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2946 const OMPTargetTeamsDistributeSimdDirective *D) {
2947 VisitOMPLoopDirective(D);
2948}
2949
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002950void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2952}
2953
2954bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2955 if (RegionOfInterest.isValid()) {
2956 SourceRange Range = getRawCursorExtent(C);
2957 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2958 return false;
2959 }
2960 return true;
2961}
2962
2963bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2964 while (!WL.empty()) {
2965 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002966 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002967
2968 // Set the Parent field, then back to its old value once we're done.
2969 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2970
2971 switch (LI.getKind()) {
2972 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002973 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 if (!D)
2975 continue;
2976
2977 // For now, perform default visitation for Decls.
2978 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2979 cast<DeclVisit>(&LI)->isFirst())))
2980 return true;
2981
2982 continue;
2983 }
2984 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002985 for (const TemplateArgumentLoc &Arg :
2986 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2987 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 return true;
2989 }
2990 continue;
2991 }
2992 case VisitorJob::TypeLocVisitKind: {
2993 // Perform default visitation for TypeLocs.
2994 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2995 return true;
2996 continue;
2997 }
2998 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002999 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 if (LabelStmt *stmt = LS->getStmt()) {
3001 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3002 TU))) {
3003 return true;
3004 }
3005 }
3006 continue;
3007 }
3008
3009 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3010 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3011 if (VisitNestedNameSpecifierLoc(V->get()))
3012 return true;
3013 continue;
3014 }
3015
3016 case VisitorJob::DeclarationNameInfoVisitKind: {
3017 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3018 ->get()))
3019 return true;
3020 continue;
3021 }
3022 case VisitorJob::MemberRefVisitKind: {
3023 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3024 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3025 return true;
3026 continue;
3027 }
3028 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003029 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 if (!S)
3031 continue;
3032
3033 // Update the current cursor.
3034 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3035 if (!IsInRegionOfInterest(Cursor))
3036 continue;
3037 switch (Visitor(Cursor, Parent, ClientData)) {
3038 case CXChildVisit_Break: return true;
3039 case CXChildVisit_Continue: break;
3040 case CXChildVisit_Recurse:
3041 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003042 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 EnqueueWorkList(WL, S);
3044 break;
3045 }
3046 continue;
3047 }
3048 case VisitorJob::MemberExprPartsKind: {
3049 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003050 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003051
3052 // Visit the nested-name-specifier
3053 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3054 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3055 return true;
3056
3057 // Visit the declaration name.
3058 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3059 return true;
3060
3061 // Visit the explicitly-specified template arguments, if any.
3062 if (M->hasExplicitTemplateArgs()) {
3063 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3064 *ArgEnd = Arg + M->getNumTemplateArgs();
3065 Arg != ArgEnd; ++Arg) {
3066 if (VisitTemplateArgumentLoc(*Arg))
3067 return true;
3068 }
3069 }
3070 continue;
3071 }
3072 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003073 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 // Visit nested-name-specifier, if present.
3075 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3076 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3077 return true;
3078 // Visit declaration name.
3079 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3080 return true;
3081 continue;
3082 }
3083 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003084 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 // Visit the nested-name-specifier.
3086 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3087 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3088 return true;
3089 // Visit the declaration name.
3090 if (VisitDeclarationNameInfo(O->getNameInfo()))
3091 return true;
3092 // Visit the overloaded declaration reference.
3093 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3094 return true;
3095 continue;
3096 }
3097 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003098 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 NamedDecl *Pack = E->getPack();
3100 if (isa<TemplateTypeParmDecl>(Pack)) {
3101 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3102 E->getPackLoc(), TU)))
3103 return true;
3104
3105 continue;
3106 }
3107
3108 if (isa<TemplateTemplateParmDecl>(Pack)) {
3109 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3110 E->getPackLoc(), TU)))
3111 return true;
3112
3113 continue;
3114 }
3115
3116 // Non-type template parameter packs and function parameter packs are
3117 // treated like DeclRefExpr cursors.
3118 continue;
3119 }
3120
3121 case VisitorJob::LambdaExprPartsKind: {
3122 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003123 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3125 CEnd = E->explicit_capture_end();
3126 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003127 // FIXME: Lambda init-captures.
3128 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003130
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3132 C->getLocation(),
3133 TU)))
3134 return true;
3135 }
3136
3137 // Visit parameters and return type, if present.
3138 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3139 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3140 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3141 // Visit the whole type.
3142 if (Visit(TL))
3143 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003144 } else if (FunctionProtoTypeLoc Proto =
3145 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 if (E->hasExplicitParameters()) {
3147 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003148 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3149 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 return true;
3151 } else {
3152 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003153 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 return true;
3155 }
3156 }
3157 }
3158 break;
3159 }
3160
3161 case VisitorJob::PostChildrenVisitKind:
3162 if (PostChildrenVisitor(Parent, ClientData))
3163 return true;
3164 break;
3165 }
3166 }
3167 return false;
3168}
3169
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003170bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003171 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 if (!WorkListFreeList.empty()) {
3173 WL = WorkListFreeList.back();
3174 WL->clear();
3175 WorkListFreeList.pop_back();
3176 }
3177 else {
3178 WL = new VisitorWorkList();
3179 WorkListCache.push_back(WL);
3180 }
3181 EnqueueWorkList(*WL, S);
3182 bool result = RunVisitorWorkList(*WL);
3183 WorkListFreeList.push_back(WL);
3184 return result;
3185}
3186
3187namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003188typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003189RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3190 const DeclarationNameInfo &NI, SourceRange QLoc,
3191 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3193 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3194 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3195
3196 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3197
3198 RefNamePieces Pieces;
3199
3200 if (WantQualifier && QLoc.isValid())
3201 Pieces.push_back(QLoc);
3202
3203 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3204 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003205
3206 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3207 Pieces.push_back(*TemplateArgsLoc);
3208
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 if (Kind == DeclarationName::CXXOperatorName) {
3210 Pieces.push_back(SourceLocation::getFromRawEncoding(
3211 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3212 Pieces.push_back(SourceLocation::getFromRawEncoding(
3213 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3214 }
3215
3216 if (WantSinglePiece) {
3217 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3218 Pieces.clear();
3219 Pieces.push_back(R);
3220 }
3221
3222 return Pieces;
3223}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003224}
Guy Benyei11169dd2012-12-18 14:30:41 +00003225
3226//===----------------------------------------------------------------------===//
3227// Misc. API hooks.
3228//===----------------------------------------------------------------------===//
3229
Chad Rosier05c71aa2013-03-27 18:28:23 +00003230static void fatal_error_handler(void *user_data, const std::string& reason,
3231 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003232 // Write the result out to stderr avoiding errs() because raw_ostreams can
3233 // call report_fatal_error.
3234 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3235 ::abort();
3236}
3237
Chandler Carruth66660742014-06-27 16:37:27 +00003238namespace {
3239struct RegisterFatalErrorHandler {
3240 RegisterFatalErrorHandler() {
3241 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3242 }
3243};
3244}
3245
3246static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3247
Guy Benyei11169dd2012-12-18 14:30:41 +00003248CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3249 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 // We use crash recovery to make some of our APIs more reliable, implicitly
3251 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003252 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3253 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003254
Chandler Carruth66660742014-06-27 16:37:27 +00003255 // Look through the managed static to trigger construction of the managed
3256 // static which registers our fatal error handler. This ensures it is only
3257 // registered once.
3258 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003259
Adrian Prantlbc068582015-07-08 01:00:30 +00003260 // Initialize targets for clang module support.
3261 llvm::InitializeAllTargets();
3262 llvm::InitializeAllTargetMCs();
3263 llvm::InitializeAllAsmPrinters();
3264 llvm::InitializeAllAsmParsers();
3265
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003266 CIndexer *CIdxr = new CIndexer();
3267
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 if (excludeDeclarationsFromPCH)
3269 CIdxr->setOnlyLocalDecls();
3270 if (displayDiagnostics)
3271 CIdxr->setDisplayDiagnostics();
3272
3273 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3274 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3275 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3276 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3277 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3278 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3279
3280 return CIdxr;
3281}
3282
3283void clang_disposeIndex(CXIndex CIdx) {
3284 if (CIdx)
3285 delete static_cast<CIndexer *>(CIdx);
3286}
3287
3288void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3289 if (CIdx)
3290 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3291}
3292
3293unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3294 if (CIdx)
3295 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3296 return 0;
3297}
3298
Alex Lorenz08615792017-12-04 21:56:36 +00003299void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3300 const char *Path) {
3301 if (CIdx)
3302 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3303}
3304
Guy Benyei11169dd2012-12-18 14:30:41 +00003305void clang_toggleCrashRecovery(unsigned isEnabled) {
3306 if (isEnabled)
3307 llvm::CrashRecoveryContext::Enable();
3308 else
3309 llvm::CrashRecoveryContext::Disable();
3310}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003311
Guy Benyei11169dd2012-12-18 14:30:41 +00003312CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3313 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003314 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003315 enum CXErrorCode Result =
3316 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003317 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003318 assert((TU && Result == CXError_Success) ||
3319 (!TU && Result != CXError_Success));
3320 return TU;
3321}
3322
3323enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3324 const char *ast_filename,
3325 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003326 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003327 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003328
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003329 if (!CIdx || !ast_filename || !out_TU)
3330 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003331
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003332 LOG_FUNC_SECTION {
3333 *Log << ast_filename;
3334 }
3335
Guy Benyei11169dd2012-12-18 14:30:41 +00003336 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3337 FileSystemOptions FileSystemOpts;
3338
Justin Bognerd512c1e2014-10-15 00:33:06 +00003339 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3340 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003341 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003342 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3343 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003344 FileSystemOpts, /*UseDebugInfo=*/false,
3345 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003346 /*CaptureDiagnostics=*/true,
3347 /*AllowPCHWithCompilerErrors=*/true,
3348 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003349 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003350 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003351}
3352
3353unsigned clang_defaultEditingTranslationUnitOptions() {
3354 return CXTranslationUnit_PrecompiledPreamble |
3355 CXTranslationUnit_CacheCompletionResults;
3356}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003357
Guy Benyei11169dd2012-12-18 14:30:41 +00003358CXTranslationUnit
3359clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3360 const char *source_filename,
3361 int num_command_line_args,
3362 const char * const *command_line_args,
3363 unsigned num_unsaved_files,
3364 struct CXUnsavedFile *unsaved_files) {
3365 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3366 return clang_parseTranslationUnit(CIdx, source_filename,
3367 command_line_args, num_command_line_args,
3368 unsaved_files, num_unsaved_files,
3369 Options);
3370}
3371
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003372static CXErrorCode
3373clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3374 const char *const *command_line_args,
3375 int num_command_line_args,
3376 ArrayRef<CXUnsavedFile> unsaved_files,
3377 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003378 // Set up the initial return values.
3379 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003380 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003381
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003382 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003383 if (!CIdx || !out_TU)
3384 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003385
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3387
3388 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3389 setThreadBackgroundPriority();
3390
3391 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003392 bool CreatePreambleOnFirstParse =
3393 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 // FIXME: Add a flag for modules.
3395 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003396 = (options & (CXTranslationUnit_Incomplete |
3397 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003398 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003399 = options & CXTranslationUnit_CacheCompletionResults;
3400 bool IncludeBriefCommentsInCodeCompletion
3401 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003402 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3403 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003404 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3405 if (options & CXTranslationUnit_SkipFunctionBodies) {
3406 SkipFunctionBodies =
3407 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3408 ? SkipFunctionBodiesScope::Preamble
3409 : SkipFunctionBodiesScope::PreambleAndMainFile;
3410 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003411
3412 // Configure the diagnostics.
3413 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003414 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003415
Manuel Klimek016c0242016-03-01 10:56:19 +00003416 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003417 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003418
Guy Benyei11169dd2012-12-18 14:30:41 +00003419 // Recover resources if we crash before exiting this function.
3420 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3421 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003422 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003423
Ahmed Charlesb8984322014-03-07 20:03:18 +00003424 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3425 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003426
3427 // Recover resources if we crash before exiting this function.
3428 llvm::CrashRecoveryContextCleanupRegistrar<
3429 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3430
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003431 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003432 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003433 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003434 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003435 }
3436
Ahmed Charlesb8984322014-03-07 20:03:18 +00003437 std::unique_ptr<std::vector<const char *>> Args(
3438 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003439
3440 // Recover resources if we crash before exiting this method.
3441 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3442 ArgsCleanup(Args.get());
3443
3444 // Since the Clang C library is primarily used by batch tools dealing with
3445 // (often very broken) source code, where spell-checking can have a
3446 // significant negative impact on performance (particularly when
3447 // precompiled headers are involved), we disable it by default.
3448 // Only do this if we haven't found a spell-checking-related argument.
3449 bool FoundSpellCheckingArgument = false;
3450 for (int I = 0; I != num_command_line_args; ++I) {
3451 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3452 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3453 FoundSpellCheckingArgument = true;
3454 break;
3455 }
3456 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003457 Args->insert(Args->end(), command_line_args,
3458 command_line_args + num_command_line_args);
3459
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003460 if (!FoundSpellCheckingArgument)
3461 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3462
Guy Benyei11169dd2012-12-18 14:30:41 +00003463 // The 'source_filename' argument is optional. If the caller does not
3464 // specify it then it is assumed that the source file is specified
3465 // in the actual argument list.
3466 // Put the source file after command_line_args otherwise if '-x' flag is
3467 // present it will be unused.
3468 if (source_filename)
3469 Args->push_back(source_filename);
3470
3471 // Do we need the detailed preprocessing record?
3472 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3473 Args->push_back("-Xclang");
3474 Args->push_back("-detailed-preprocessing-record");
3475 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003476
3477 // Suppress any editor placeholder diagnostics.
3478 Args->push_back("-fallow-editor-placeholders");
3479
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003481 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003482 // Unless the user specified that they want the preamble on the first parse
3483 // set it up to be created on the first reparse. This makes the first parse
3484 // faster, trading for a slower (first) reparse.
3485 unsigned PrecompilePreambleAfterNParses =
3486 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003487
Alex Lorenz08615792017-12-04 21:56:36 +00003488 LibclangInvocationReporter InvocationReporter(
3489 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003490 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3491 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003492 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003493 Args->data(), Args->data() + Args->size(),
3494 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003495 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3496 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003497 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3498 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003499 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003500 /*UserFilesAreVolatile=*/true, ForSerialization,
3501 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3502 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003503
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003504 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003505 if (!Unit && !ErrUnit)
3506 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003507
Guy Benyei11169dd2012-12-18 14:30:41 +00003508 if (NumErrors != Diags->getClient()->getNumErrors()) {
3509 // Make sure to check that 'Unit' is non-NULL.
3510 if (CXXIdx->getDisplayDiagnostics())
3511 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3512 }
3513
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003514 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3515 return CXError_ASTReadError;
3516
David Blaikieea4395e2017-01-06 19:49:01 +00003517 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003518 if (CXTranslationUnitImpl *TU = *out_TU) {
3519 TU->ParsingOptions = options;
3520 TU->Arguments.reserve(Args->size());
3521 for (const char *Arg : *Args)
3522 TU->Arguments.push_back(Arg);
3523 return CXError_Success;
3524 }
3525 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003526}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003527
3528CXTranslationUnit
3529clang_parseTranslationUnit(CXIndex CIdx,
3530 const char *source_filename,
3531 const char *const *command_line_args,
3532 int num_command_line_args,
3533 struct CXUnsavedFile *unsaved_files,
3534 unsigned num_unsaved_files,
3535 unsigned options) {
3536 CXTranslationUnit TU;
3537 enum CXErrorCode Result = clang_parseTranslationUnit2(
3538 CIdx, source_filename, command_line_args, num_command_line_args,
3539 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003540 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003541 assert((TU && Result == CXError_Success) ||
3542 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003543 return TU;
3544}
3545
3546enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003547 CXIndex CIdx, const char *source_filename,
3548 const char *const *command_line_args, int num_command_line_args,
3549 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3550 unsigned options, CXTranslationUnit *out_TU) {
3551 SmallVector<const char *, 4> Args;
3552 Args.push_back("clang");
3553 Args.append(command_line_args, command_line_args + num_command_line_args);
3554 return clang_parseTranslationUnit2FullArgv(
3555 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3556 num_unsaved_files, options, out_TU);
3557}
3558
3559enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3560 CXIndex CIdx, const char *source_filename,
3561 const char *const *command_line_args, int num_command_line_args,
3562 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3563 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003564 LOG_FUNC_SECTION {
3565 *Log << source_filename << ": ";
3566 for (int i = 0; i != num_command_line_args; ++i)
3567 *Log << command_line_args[i] << " ";
3568 }
3569
Alp Toker9d85b182014-07-07 01:23:14 +00003570 if (num_unsaved_files && !unsaved_files)
3571 return CXError_InvalidArguments;
3572
Alp Toker5c532982014-07-07 22:42:03 +00003573 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003574 auto ParseTranslationUnitImpl = [=, &result] {
3575 result = clang_parseTranslationUnit_Impl(
3576 CIdx, source_filename, command_line_args, num_command_line_args,
3577 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3578 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003579
Guy Benyei11169dd2012-12-18 14:30:41 +00003580 llvm::CrashRecoveryContext CRC;
3581
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003582 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3584 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3585 fprintf(stderr, " 'command_line_args' : [");
3586 for (int i = 0; i != num_command_line_args; ++i) {
3587 if (i)
3588 fprintf(stderr, ", ");
3589 fprintf(stderr, "'%s'", command_line_args[i]);
3590 }
3591 fprintf(stderr, "],\n");
3592 fprintf(stderr, " 'unsaved_files' : [");
3593 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3594 if (i)
3595 fprintf(stderr, ", ");
3596 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3597 unsaved_files[i].Length);
3598 }
3599 fprintf(stderr, "],\n");
3600 fprintf(stderr, " 'options' : %d,\n", options);
3601 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003602
3603 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003604 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003605 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003606 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003607 }
Alp Toker5c532982014-07-07 22:42:03 +00003608
3609 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003610}
3611
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003612CXString clang_Type_getObjCEncoding(CXType CT) {
3613 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3614 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3615 std::string encoding;
3616 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3617 encoding);
3618
3619 return cxstring::createDup(encoding);
3620}
3621
3622static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3623 if (C.kind == CXCursor_MacroDefinition) {
3624 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3625 return MDR->getName();
3626 } else if (C.kind == CXCursor_MacroExpansion) {
3627 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3628 return ME.getName();
3629 }
3630 return nullptr;
3631}
3632
3633unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3634 const IdentifierInfo *II = getMacroIdentifier(C);
3635 if (!II) {
3636 return false;
3637 }
3638 ASTUnit *ASTU = getCursorASTUnit(C);
3639 Preprocessor &PP = ASTU->getPreprocessor();
3640 if (const MacroInfo *MI = PP.getMacroInfo(II))
3641 return MI->isFunctionLike();
3642 return false;
3643}
3644
3645unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3646 const IdentifierInfo *II = getMacroIdentifier(C);
3647 if (!II) {
3648 return false;
3649 }
3650 ASTUnit *ASTU = getCursorASTUnit(C);
3651 Preprocessor &PP = ASTU->getPreprocessor();
3652 if (const MacroInfo *MI = PP.getMacroInfo(II))
3653 return MI->isBuiltinMacro();
3654 return false;
3655}
3656
3657unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3658 const Decl *D = getCursorDecl(C);
3659 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3660 if (!FD) {
3661 return false;
3662 }
3663 return FD->isInlined();
3664}
3665
3666static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3667 if (callExpr->getNumArgs() != 1) {
3668 return nullptr;
3669 }
3670
3671 StringLiteral *S = nullptr;
3672 auto *arg = callExpr->getArg(0);
3673 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3674 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3675 auto *subExpr = I->getSubExprAsWritten();
3676
3677 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3678 return nullptr;
3679 }
3680
3681 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3682 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3683 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3684 } else {
3685 return nullptr;
3686 }
3687 return S;
3688}
3689
David Blaikie59272572016-04-13 18:23:33 +00003690struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003691 CXEvalResultKind EvalType;
3692 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003693 unsigned long long unsignedVal;
3694 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003695 double floatVal;
3696 char *stringVal;
3697 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003698 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003699 ~ExprEvalResult() {
3700 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3701 EvalType != CXEval_Int) {
3702 delete EvalData.stringVal;
3703 }
3704 }
3705};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003706
3707void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003708 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003709}
3710
3711CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3712 if (!E) {
3713 return CXEval_UnExposed;
3714 }
3715 return ((ExprEvalResult *)E)->EvalType;
3716}
3717
3718int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003719 return clang_EvalResult_getAsLongLong(E);
3720}
3721
3722long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003723 if (!E) {
3724 return 0;
3725 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003726 ExprEvalResult *Result = (ExprEvalResult*)E;
3727 if (Result->IsUnsignedInt)
3728 return Result->EvalData.unsignedVal;
3729 return Result->EvalData.intVal;
3730}
3731
3732unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3733 return ((ExprEvalResult *)E)->IsUnsignedInt;
3734}
3735
3736unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3737 if (!E) {
3738 return 0;
3739 }
3740
3741 ExprEvalResult *Result = (ExprEvalResult*)E;
3742 if (Result->IsUnsignedInt)
3743 return Result->EvalData.unsignedVal;
3744 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003745}
3746
3747double clang_EvalResult_getAsDouble(CXEvalResult E) {
3748 if (!E) {
3749 return 0;
3750 }
3751 return ((ExprEvalResult *)E)->EvalData.floatVal;
3752}
3753
3754const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3755 if (!E) {
3756 return nullptr;
3757 }
3758 return ((ExprEvalResult *)E)->EvalData.stringVal;
3759}
3760
3761static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3762 Expr::EvalResult ER;
3763 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003764 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003765 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003766
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003767 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003768 if (!expr->EvaluateAsRValue(ER, ctx))
3769 return nullptr;
3770
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003771 QualType rettype;
3772 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003773 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003774 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003775 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003776
David Blaikiebbc00882016-04-13 18:36:19 +00003777 if (ER.Val.isInt()) {
3778 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003779
3780 auto& val = ER.Val.getInt();
3781 if (val.isUnsigned()) {
3782 result->IsUnsignedInt = true;
3783 result->EvalData.unsignedVal = val.getZExtValue();
3784 } else {
3785 result->EvalData.intVal = val.getExtValue();
3786 }
3787
David Blaikiebbc00882016-04-13 18:36:19 +00003788 return result.release();
3789 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003790
David Blaikiebbc00882016-04-13 18:36:19 +00003791 if (ER.Val.isFloat()) {
3792 llvm::SmallVector<char, 100> Buffer;
3793 ER.Val.getFloat().toString(Buffer);
3794 std::string floatStr(Buffer.data(), Buffer.size());
3795 result->EvalType = CXEval_Float;
3796 bool ignored;
3797 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003798 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003799 llvm::APFloat::rmNearestTiesToEven, &ignored);
3800 result->EvalData.floatVal = apFloat.convertToDouble();
3801 return result.release();
3802 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003803
David Blaikiebbc00882016-04-13 18:36:19 +00003804 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3805 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3806 auto *subExpr = I->getSubExprAsWritten();
3807 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3808 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003809 const StringLiteral *StrE = nullptr;
3810 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003811 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003812
3813 if (ObjCExpr) {
3814 StrE = ObjCExpr->getString();
3815 result->EvalType = CXEval_ObjCStrLiteral;
3816 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003817 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003818 result->EvalType = CXEval_StrLiteral;
3819 }
3820
3821 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003822 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003823 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3824 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003825 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003826 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003827 }
3828 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3829 expr->getStmtClass() == Stmt::StringLiteralClass) {
3830 const StringLiteral *StrE = nullptr;
3831 const ObjCStringLiteral *ObjCExpr;
3832 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003833
David Blaikiebbc00882016-04-13 18:36:19 +00003834 if (ObjCExpr) {
3835 StrE = ObjCExpr->getString();
3836 result->EvalType = CXEval_ObjCStrLiteral;
3837 } else {
3838 StrE = cast<StringLiteral>(expr);
3839 result->EvalType = CXEval_StrLiteral;
3840 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003841
David Blaikiebbc00882016-04-13 18:36:19 +00003842 std::string strRef(StrE->getString().str());
3843 result->EvalData.stringVal = new char[strRef.size() + 1];
3844 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3845 result->EvalData.stringVal[strRef.size()] = '\0';
3846 return result.release();
3847 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003848
David Blaikiebbc00882016-04-13 18:36:19 +00003849 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3850 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003851
David Blaikiebbc00882016-04-13 18:36:19 +00003852 rettype = CC->getType();
3853 if (rettype.getAsString() == "CFStringRef" &&
3854 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003855
David Blaikiebbc00882016-04-13 18:36:19 +00003856 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3857 StringLiteral *S = getCFSTR_value(callExpr);
3858 if (S) {
3859 std::string strLiteral(S->getString().str());
3860 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003861
David Blaikiebbc00882016-04-13 18:36:19 +00003862 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3863 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3864 strLiteral.size());
3865 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003866 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003867 }
3868 }
3869
David Blaikiebbc00882016-04-13 18:36:19 +00003870 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3871 callExpr = static_cast<CallExpr *>(expr);
3872 rettype = callExpr->getCallReturnType(ctx);
3873
3874 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3875 return nullptr;
3876
3877 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3878 if (callExpr->getNumArgs() == 1 &&
3879 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3880 return nullptr;
3881 } else if (rettype.getAsString() == "CFStringRef") {
3882
3883 StringLiteral *S = getCFSTR_value(callExpr);
3884 if (S) {
3885 std::string strLiteral(S->getString().str());
3886 result->EvalType = CXEval_CFStr;
3887 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3888 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3889 strLiteral.size());
3890 result->EvalData.stringVal[strLiteral.size()] = '\0';
3891 return result.release();
3892 }
3893 }
3894 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3895 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3896 ValueDecl *V = D->getDecl();
3897 if (V->getKind() == Decl::Function) {
3898 std::string strName = V->getNameAsString();
3899 result->EvalType = CXEval_Other;
3900 result->EvalData.stringVal = new char[strName.size() + 1];
3901 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3902 result->EvalData.stringVal[strName.size()] = '\0';
3903 return result.release();
3904 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003905 }
3906
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003907 return nullptr;
3908}
3909
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003910CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003911 const Decl *D = getCursorDecl(C);
3912 if (D) {
3913 const Expr *expr = nullptr;
3914 if (auto *Var = dyn_cast<VarDecl>(D)) {
3915 expr = Var->getInit();
3916 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3917 expr = Field->getInClassInitializer();
3918 }
3919 if (expr)
3920 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3921 evaluateExpr(const_cast<Expr *>(expr), C)));
3922 return nullptr;
3923 }
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003924
3925 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3926 if (compoundStmt) {
3927 Expr *expr = nullptr;
3928 for (auto *bodyIterator : compoundStmt->body()) {
3929 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3930 break;
3931 }
3932 }
3933 if (expr)
3934 return const_cast<CXEvalResult>(
3935 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
3936 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003937 return nullptr;
3938}
3939
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003940unsigned clang_Cursor_hasAttrs(CXCursor C) {
3941 const Decl *D = getCursorDecl(C);
3942 if (!D) {
3943 return 0;
3944 }
3945
3946 if (D->hasAttrs()) {
3947 return 1;
3948 }
3949
3950 return 0;
3951}
Guy Benyei11169dd2012-12-18 14:30:41 +00003952unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3953 return CXSaveTranslationUnit_None;
3954}
3955
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003956static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3957 const char *FileName,
3958 unsigned options) {
3959 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003960 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3961 setThreadBackgroundPriority();
3962
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003963 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3964 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003965}
3966
3967int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3968 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003969 LOG_FUNC_SECTION {
3970 *Log << TU << ' ' << FileName;
3971 }
3972
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003973 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003974 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003975 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003976 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003977
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003978 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003979 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3980 if (!CXXUnit->hasSema())
3981 return CXSaveError_InvalidTU;
3982
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003983 CXSaveError result;
3984 auto SaveTranslationUnitImpl = [=, &result]() {
3985 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3986 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003987
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003988 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003989 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003990
3991 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3992 PrintLibclangResourceUsage(TU);
3993
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003994 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 }
3996
3997 // We have an AST that has invalid nodes due to compiler errors.
3998 // Use a crash recovery thread for protection.
3999
4000 llvm::CrashRecoveryContext CRC;
4001
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004002 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4004 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4005 fprintf(stderr, " 'options' : %d,\n", options);
4006 fprintf(stderr, "}\n");
4007
4008 return CXSaveError_Unknown;
4009
4010 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4011 PrintLibclangResourceUsage(TU);
4012 }
4013
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004014 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004015}
4016
4017void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4018 if (CTUnit) {
4019 // If the translation unit has been marked as unsafe to free, just discard
4020 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004021 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4022 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 return;
4024
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004025 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004026 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004027 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4028 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004029 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 delete CTUnit;
4031 }
4032}
4033
Erik Verbruggen346066b2017-05-30 14:25:54 +00004034unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4035 if (CTUnit) {
4036 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4037
4038 if (Unit && Unit->isUnsafeToFree())
4039 return false;
4040
4041 Unit->ResetForParse();
4042 return true;
4043 }
4044
4045 return false;
4046}
4047
Guy Benyei11169dd2012-12-18 14:30:41 +00004048unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4049 return CXReparse_None;
4050}
4051
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004052static CXErrorCode
4053clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4054 ArrayRef<CXUnsavedFile> unsaved_files,
4055 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004056 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004057 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004058 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004059 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004060 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004061
4062 // Reset the associated diagnostics.
4063 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004064 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004065
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004066 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4068 setThreadBackgroundPriority();
4069
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004070 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004071 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004072
4073 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4074 new std::vector<ASTUnit::RemappedFile>());
4075
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 // Recover resources if we crash before exiting this function.
4077 llvm::CrashRecoveryContextCleanupRegistrar<
4078 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004079
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004080 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004081 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004082 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004083 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004085
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004086 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4087 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004088 return CXError_Success;
4089 if (isASTReadError(CXXUnit))
4090 return CXError_ASTReadError;
4091 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004092}
4093
4094int clang_reparseTranslationUnit(CXTranslationUnit TU,
4095 unsigned num_unsaved_files,
4096 struct CXUnsavedFile *unsaved_files,
4097 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004098 LOG_FUNC_SECTION {
4099 *Log << TU;
4100 }
4101
Alp Toker9d85b182014-07-07 01:23:14 +00004102 if (num_unsaved_files && !unsaved_files)
4103 return CXError_InvalidArguments;
4104
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004105 CXErrorCode result;
4106 auto ReparseTranslationUnitImpl = [=, &result]() {
4107 result = clang_reparseTranslationUnit_Impl(
4108 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4109 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004110
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 llvm::CrashRecoveryContext CRC;
4112
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004113 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004115 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004116 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4118 PrintLibclangResourceUsage(TU);
4119
Alp Toker5c532982014-07-07 22:42:03 +00004120 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004121}
4122
4123
4124CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004125 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004126 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004127 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004128 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004129
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004130 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004131 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004132}
4133
4134CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004135 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004136 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004137 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004138 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004139
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004140 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004141 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4142}
4143
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004144CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4145 if (isNotUsableTU(CTUnit)) {
4146 LOG_BAD_TU(CTUnit);
4147 return nullptr;
4148 }
4149
4150 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4151 impl->TranslationUnit = CTUnit;
4152 return impl;
4153}
4154
4155CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4156 if (!TargetInfo)
4157 return cxstring::createEmpty();
4158
4159 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4160 assert(!isNotUsableTU(CTUnit) &&
4161 "Unexpected unusable translation unit in TargetInfo");
4162
4163 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4164 std::string Triple =
4165 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4166 return cxstring::createDup(Triple);
4167}
4168
4169int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4170 if (!TargetInfo)
4171 return -1;
4172
4173 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4174 assert(!isNotUsableTU(CTUnit) &&
4175 "Unexpected unusable translation unit in TargetInfo");
4176
4177 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4178 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4179}
4180
4181void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4182 if (!TargetInfo)
4183 return;
4184
4185 delete TargetInfo;
4186}
4187
Guy Benyei11169dd2012-12-18 14:30:41 +00004188//===----------------------------------------------------------------------===//
4189// CXFile Operations.
4190//===----------------------------------------------------------------------===//
4191
Guy Benyei11169dd2012-12-18 14:30:41 +00004192CXString clang_getFileName(CXFile SFile) {
4193 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004194 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004195
4196 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004197 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004198}
4199
4200time_t clang_getFileTime(CXFile SFile) {
4201 if (!SFile)
4202 return 0;
4203
4204 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4205 return FEnt->getModificationTime();
4206}
4207
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004208CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004209 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004210 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004211 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004212 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004213
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004214 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004215
4216 FileManager &FMgr = CXXUnit->getFileManager();
4217 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4218}
4219
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004220const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4221 size_t *size) {
4222 if (isNotUsableTU(TU)) {
4223 LOG_BAD_TU(TU);
4224 return nullptr;
4225 }
4226
4227 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4228 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4229 bool Invalid = true;
4230 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4231 if (Invalid) {
4232 if (size)
4233 *size = 0;
4234 return nullptr;
4235 }
4236 if (size)
4237 *size = buf->getBufferSize();
4238 return buf->getBufferStart();
4239}
4240
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004241unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4242 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004243 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004244 LOG_BAD_TU(TU);
4245 return 0;
4246 }
4247
4248 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 return 0;
4250
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004251 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 FileEntry *FEnt = static_cast<FileEntry *>(file);
4253 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4254 .isFileMultipleIncludeGuarded(FEnt);
4255}
4256
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004257int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4258 if (!file || !outID)
4259 return 1;
4260
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004261 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004262 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4263 outID->data[0] = ID.getDevice();
4264 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004265 outID->data[2] = FEnt->getModificationTime();
4266 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004267}
4268
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004269int clang_File_isEqual(CXFile file1, CXFile file2) {
4270 if (file1 == file2)
4271 return true;
4272
4273 if (!file1 || !file2)
4274 return false;
4275
4276 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4277 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4278 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4279}
4280
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004281CXString clang_File_tryGetRealPathName(CXFile SFile) {
4282 if (!SFile)
4283 return cxstring::createNull();
4284
4285 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4286 return cxstring::createRef(FEnt->tryGetRealPathName());
4287}
4288
Guy Benyei11169dd2012-12-18 14:30:41 +00004289//===----------------------------------------------------------------------===//
4290// CXCursor Operations.
4291//===----------------------------------------------------------------------===//
4292
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004293static const Decl *getDeclFromExpr(const Stmt *E) {
4294 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 return getDeclFromExpr(CE->getSubExpr());
4296
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004297 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004299 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004301 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004302 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004303 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 if (PRE->isExplicitProperty())
4305 return PRE->getExplicitProperty();
4306 // It could be messaging both getter and setter as in:
4307 // ++myobj.myprop;
4308 // in which case prefer to associate the setter since it is less obvious
4309 // from inspecting the source that the setter is going to get called.
4310 if (PRE->isMessagingSetter())
4311 return PRE->getImplicitPropertySetter();
4312 return PRE->getImplicitPropertyGetter();
4313 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004314 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004316 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 if (Expr *Src = OVE->getSourceExpr())
4318 return getDeclFromExpr(Src);
4319
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004320 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004322 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 if (!CE->isElidable())
4324 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004325 if (const CXXInheritedCtorInitExpr *CE =
4326 dyn_cast<CXXInheritedCtorInitExpr>(E))
4327 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004328 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 return OME->getMethodDecl();
4330
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004331 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004333 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4335 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004336 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4338 isa<ParmVarDecl>(SizeOfPack->getPack()))
4339 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004340
4341 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004342}
4343
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004344static SourceLocation getLocationFromExpr(const Expr *E) {
4345 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 return getLocationFromExpr(CE->getSubExpr());
4347
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004348 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004350 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004352 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004354 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004356 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004358 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004359 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004360
4361 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004362}
4363
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004364extern "C" {
4365
Guy Benyei11169dd2012-12-18 14:30:41 +00004366unsigned clang_visitChildren(CXCursor parent,
4367 CXCursorVisitor visitor,
4368 CXClientData client_data) {
4369 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4370 /*VisitPreprocessorLast=*/false);
4371 return CursorVis.VisitChildren(parent);
4372}
4373
4374#ifndef __has_feature
4375#define __has_feature(x) 0
4376#endif
4377#if __has_feature(blocks)
4378typedef enum CXChildVisitResult
4379 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4380
4381static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4382 CXClientData client_data) {
4383 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4384 return block(cursor, parent);
4385}
4386#else
4387// If we are compiled with a compiler that doesn't have native blocks support,
4388// define and call the block manually, so the
4389typedef struct _CXChildVisitResult
4390{
4391 void *isa;
4392 int flags;
4393 int reserved;
4394 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4395 CXCursor);
4396} *CXCursorVisitorBlock;
4397
4398static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4399 CXClientData client_data) {
4400 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4401 return block->invoke(block, cursor, parent);
4402}
4403#endif
4404
4405
4406unsigned clang_visitChildrenWithBlock(CXCursor parent,
4407 CXCursorVisitorBlock block) {
4408 return clang_visitChildren(parent, visitWithBlock, block);
4409}
4410
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004411static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004413 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004414
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004415 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004417 if (const ObjCPropertyImplDecl *PropImpl =
4418 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004420 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004421
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004422 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004424 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004425
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004426 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 }
4428
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004429 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004430 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004431
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004432 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4434 // and returns different names. NamedDecl returns the class name and
4435 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004436 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004437
4438 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004439 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004440
4441 SmallString<1024> S;
4442 llvm::raw_svector_ostream os(S);
4443 ND->printName(os);
4444
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004445 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004446}
4447
4448CXString clang_getCursorSpelling(CXCursor C) {
4449 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004450 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004451
4452 if (clang_isReference(C.kind)) {
4453 switch (C.kind) {
4454 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004455 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004456 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 }
4458 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004459 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004460 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 }
4462 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004463 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004465 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 }
4467 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004468 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004469 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 }
4471 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004472 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 assert(Type && "Missing type decl");
4474
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004475 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 getAsString());
4477 }
4478 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004479 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 assert(Template && "Missing template decl");
4481
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004482 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 }
4484
4485 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004486 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 assert(NS && "Missing namespace decl");
4488
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004489 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 }
4491
4492 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004493 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 assert(Field && "Missing member decl");
4495
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004496 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 }
4498
4499 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004500 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 assert(Label && "Missing label");
4502
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004503 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 }
4505
4506 case CXCursor_OverloadedDeclRef: {
4507 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004508 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4509 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004510 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004511 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004513 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004514 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 OverloadedTemplateStorage *Ovl
4516 = Storage.get<OverloadedTemplateStorage*>();
4517 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004518 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004519 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 }
4521
4522 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004523 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 assert(Var && "Missing variable decl");
4525
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004526 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 }
4528
4529 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004530 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 }
4532 }
4533
4534 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004535 const Expr *E = getCursorExpr(C);
4536
4537 if (C.kind == CXCursor_ObjCStringLiteral ||
4538 C.kind == CXCursor_StringLiteral) {
4539 const StringLiteral *SLit;
4540 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4541 SLit = OSL->getString();
4542 } else {
4543 SLit = cast<StringLiteral>(E);
4544 }
4545 SmallString<256> Buf;
4546 llvm::raw_svector_ostream OS(Buf);
4547 SLit->outputString(OS);
4548 return cxstring::createDup(OS.str());
4549 }
4550
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004551 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004552 if (D)
4553 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004554 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 }
4556
4557 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004558 const Stmt *S = getCursorStmt(C);
4559 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004560 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004561
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004562 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 }
4564
4565 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004566 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 ->getNameStart());
4568
4569 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004570 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 ->getNameStart());
4572
4573 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004574 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004575
4576 if (clang_isDeclaration(C.kind))
4577 return getDeclSpelling(getCursorDecl(C));
4578
4579 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004580 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004581 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 }
4583
4584 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004585 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004586 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 }
4588
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004589 if (C.kind == CXCursor_PackedAttr) {
4590 return cxstring::createRef("packed");
4591 }
4592
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004593 if (C.kind == CXCursor_VisibilityAttr) {
4594 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4595 switch (AA->getVisibility()) {
4596 case VisibilityAttr::VisibilityType::Default:
4597 return cxstring::createRef("default");
4598 case VisibilityAttr::VisibilityType::Hidden:
4599 return cxstring::createRef("hidden");
4600 case VisibilityAttr::VisibilityType::Protected:
4601 return cxstring::createRef("protected");
4602 }
4603 llvm_unreachable("unknown visibility type");
4604 }
4605
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004606 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004607}
4608
4609CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4610 unsigned pieceIndex,
4611 unsigned options) {
4612 if (clang_Cursor_isNull(C))
4613 return clang_getNullRange();
4614
4615 ASTContext &Ctx = getCursorContext(C);
4616
4617 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004618 const Stmt *S = getCursorStmt(C);
4619 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 if (pieceIndex > 0)
4621 return clang_getNullRange();
4622 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4623 }
4624
4625 return clang_getNullRange();
4626 }
4627
4628 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004629 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4631 if (pieceIndex >= ME->getNumSelectorLocs())
4632 return clang_getNullRange();
4633 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4634 }
4635 }
4636
4637 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4638 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004639 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4641 if (pieceIndex >= MD->getNumSelectorLocs())
4642 return clang_getNullRange();
4643 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4644 }
4645 }
4646
4647 if (C.kind == CXCursor_ObjCCategoryDecl ||
4648 C.kind == CXCursor_ObjCCategoryImplDecl) {
4649 if (pieceIndex > 0)
4650 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004651 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4653 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004654 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4656 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4657 }
4658
4659 if (C.kind == CXCursor_ModuleImportDecl) {
4660 if (pieceIndex > 0)
4661 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004662 if (const ImportDecl *ImportD =
4663 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4665 if (!Locs.empty())
4666 return cxloc::translateSourceRange(Ctx,
4667 SourceRange(Locs.front(), Locs.back()));
4668 }
4669 return clang_getNullRange();
4670 }
4671
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004672 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004673 C.kind == CXCursor_ConversionFunction ||
4674 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004675 if (pieceIndex > 0)
4676 return clang_getNullRange();
4677 if (const FunctionDecl *FD =
4678 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4679 DeclarationNameInfo FunctionName = FD->getNameInfo();
4680 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4681 }
4682 return clang_getNullRange();
4683 }
4684
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 // FIXME: A CXCursor_InclusionDirective should give the location of the
4686 // filename, but we don't keep track of this.
4687
4688 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4689 // but we don't keep track of this.
4690
4691 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4692 // but we don't keep track of this.
4693
4694 // Default handling, give the location of the cursor.
4695
4696 if (pieceIndex > 0)
4697 return clang_getNullRange();
4698
4699 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4700 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4701 return cxloc::translateSourceRange(Ctx, Loc);
4702}
4703
Eli Bendersky44a206f2014-07-31 18:04:56 +00004704CXString clang_Cursor_getMangling(CXCursor C) {
4705 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4706 return cxstring::createEmpty();
4707
Eli Bendersky44a206f2014-07-31 18:04:56 +00004708 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004709 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004710 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4711 return cxstring::createEmpty();
4712
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004713 ASTContext &Ctx = D->getASTContext();
4714 index::CodegenNameGenerator CGNameGen(Ctx);
4715 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004716}
4717
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004718CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4719 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4720 return nullptr;
4721
4722 const Decl *D = getCursorDecl(C);
4723 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4724 return nullptr;
4725
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004726 ASTContext &Ctx = D->getASTContext();
4727 index::CodegenNameGenerator CGNameGen(Ctx);
4728 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004729 return cxstring::createSet(Manglings);
4730}
4731
Dave Lee1a532c92017-09-22 16:58:57 +00004732CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4733 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4734 return nullptr;
4735
4736 const Decl *D = getCursorDecl(C);
4737 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4738 return nullptr;
4739
4740 ASTContext &Ctx = D->getASTContext();
4741 index::CodegenNameGenerator CGNameGen(Ctx);
4742 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4743 return cxstring::createSet(Manglings);
4744}
4745
Jonathan Coe45ef5032018-01-16 10:19:56 +00004746CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4747 if (clang_Cursor_isNull(C))
4748 return 0;
4749 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4750}
4751
4752void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4753 if (Policy)
4754 delete static_cast<PrintingPolicy *>(Policy);
4755}
4756
4757unsigned
4758clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4759 enum CXPrintingPolicyProperty Property) {
4760 if (!Policy)
4761 return 0;
4762
4763 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4764 switch (Property) {
4765 case CXPrintingPolicy_Indentation:
4766 return P->Indentation;
4767 case CXPrintingPolicy_SuppressSpecifiers:
4768 return P->SuppressSpecifiers;
4769 case CXPrintingPolicy_SuppressTagKeyword:
4770 return P->SuppressTagKeyword;
4771 case CXPrintingPolicy_IncludeTagDefinition:
4772 return P->IncludeTagDefinition;
4773 case CXPrintingPolicy_SuppressScope:
4774 return P->SuppressScope;
4775 case CXPrintingPolicy_SuppressUnwrittenScope:
4776 return P->SuppressUnwrittenScope;
4777 case CXPrintingPolicy_SuppressInitializers:
4778 return P->SuppressInitializers;
4779 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4780 return P->ConstantArraySizeAsWritten;
4781 case CXPrintingPolicy_AnonymousTagLocations:
4782 return P->AnonymousTagLocations;
4783 case CXPrintingPolicy_SuppressStrongLifetime:
4784 return P->SuppressStrongLifetime;
4785 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4786 return P->SuppressLifetimeQualifiers;
4787 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4788 return P->SuppressTemplateArgsInCXXConstructors;
4789 case CXPrintingPolicy_Bool:
4790 return P->Bool;
4791 case CXPrintingPolicy_Restrict:
4792 return P->Restrict;
4793 case CXPrintingPolicy_Alignof:
4794 return P->Alignof;
4795 case CXPrintingPolicy_UnderscoreAlignof:
4796 return P->UnderscoreAlignof;
4797 case CXPrintingPolicy_UseVoidForZeroParams:
4798 return P->UseVoidForZeroParams;
4799 case CXPrintingPolicy_TerseOutput:
4800 return P->TerseOutput;
4801 case CXPrintingPolicy_PolishForDeclaration:
4802 return P->PolishForDeclaration;
4803 case CXPrintingPolicy_Half:
4804 return P->Half;
4805 case CXPrintingPolicy_MSWChar:
4806 return P->MSWChar;
4807 case CXPrintingPolicy_IncludeNewlines:
4808 return P->IncludeNewlines;
4809 case CXPrintingPolicy_MSVCFormatting:
4810 return P->MSVCFormatting;
4811 case CXPrintingPolicy_ConstantsAsWritten:
4812 return P->ConstantsAsWritten;
4813 case CXPrintingPolicy_SuppressImplicitBase:
4814 return P->SuppressImplicitBase;
4815 case CXPrintingPolicy_FullyQualifiedName:
4816 return P->FullyQualifiedName;
4817 }
4818
4819 assert(false && "Invalid CXPrintingPolicyProperty");
4820 return 0;
4821}
4822
4823void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4824 enum CXPrintingPolicyProperty Property,
4825 unsigned Value) {
4826 if (!Policy)
4827 return;
4828
4829 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4830 switch (Property) {
4831 case CXPrintingPolicy_Indentation:
4832 P->Indentation = Value;
4833 return;
4834 case CXPrintingPolicy_SuppressSpecifiers:
4835 P->SuppressSpecifiers = Value;
4836 return;
4837 case CXPrintingPolicy_SuppressTagKeyword:
4838 P->SuppressTagKeyword = Value;
4839 return;
4840 case CXPrintingPolicy_IncludeTagDefinition:
4841 P->IncludeTagDefinition = Value;
4842 return;
4843 case CXPrintingPolicy_SuppressScope:
4844 P->SuppressScope = Value;
4845 return;
4846 case CXPrintingPolicy_SuppressUnwrittenScope:
4847 P->SuppressUnwrittenScope = Value;
4848 return;
4849 case CXPrintingPolicy_SuppressInitializers:
4850 P->SuppressInitializers = Value;
4851 return;
4852 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4853 P->ConstantArraySizeAsWritten = Value;
4854 return;
4855 case CXPrintingPolicy_AnonymousTagLocations:
4856 P->AnonymousTagLocations = Value;
4857 return;
4858 case CXPrintingPolicy_SuppressStrongLifetime:
4859 P->SuppressStrongLifetime = Value;
4860 return;
4861 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4862 P->SuppressLifetimeQualifiers = Value;
4863 return;
4864 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4865 P->SuppressTemplateArgsInCXXConstructors = Value;
4866 return;
4867 case CXPrintingPolicy_Bool:
4868 P->Bool = Value;
4869 return;
4870 case CXPrintingPolicy_Restrict:
4871 P->Restrict = Value;
4872 return;
4873 case CXPrintingPolicy_Alignof:
4874 P->Alignof = Value;
4875 return;
4876 case CXPrintingPolicy_UnderscoreAlignof:
4877 P->UnderscoreAlignof = Value;
4878 return;
4879 case CXPrintingPolicy_UseVoidForZeroParams:
4880 P->UseVoidForZeroParams = Value;
4881 return;
4882 case CXPrintingPolicy_TerseOutput:
4883 P->TerseOutput = Value;
4884 return;
4885 case CXPrintingPolicy_PolishForDeclaration:
4886 P->PolishForDeclaration = Value;
4887 return;
4888 case CXPrintingPolicy_Half:
4889 P->Half = Value;
4890 return;
4891 case CXPrintingPolicy_MSWChar:
4892 P->MSWChar = Value;
4893 return;
4894 case CXPrintingPolicy_IncludeNewlines:
4895 P->IncludeNewlines = Value;
4896 return;
4897 case CXPrintingPolicy_MSVCFormatting:
4898 P->MSVCFormatting = Value;
4899 return;
4900 case CXPrintingPolicy_ConstantsAsWritten:
4901 P->ConstantsAsWritten = Value;
4902 return;
4903 case CXPrintingPolicy_SuppressImplicitBase:
4904 P->SuppressImplicitBase = Value;
4905 return;
4906 case CXPrintingPolicy_FullyQualifiedName:
4907 P->FullyQualifiedName = Value;
4908 return;
4909 }
4910
4911 assert(false && "Invalid CXPrintingPolicyProperty");
4912}
4913
4914CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4915 if (clang_Cursor_isNull(C))
4916 return cxstring::createEmpty();
4917
4918 if (clang_isDeclaration(C.kind)) {
4919 const Decl *D = getCursorDecl(C);
4920 if (!D)
4921 return cxstring::createEmpty();
4922
4923 SmallString<128> Str;
4924 llvm::raw_svector_ostream OS(Str);
4925 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4926 D->print(OS, UserPolicy ? *UserPolicy
4927 : getCursorContext(C).getPrintingPolicy());
4928
4929 return cxstring::createDup(OS.str());
4930 }
4931
4932 return cxstring::createEmpty();
4933}
4934
Guy Benyei11169dd2012-12-18 14:30:41 +00004935CXString clang_getCursorDisplayName(CXCursor C) {
4936 if (!clang_isDeclaration(C.kind))
4937 return clang_getCursorSpelling(C);
4938
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004939 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004941 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004942
4943 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004944 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 D = FunTmpl->getTemplatedDecl();
4946
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004947 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004948 SmallString<64> Str;
4949 llvm::raw_svector_ostream OS(Str);
4950 OS << *Function;
4951 if (Function->getPrimaryTemplate())
4952 OS << "<>";
4953 OS << "(";
4954 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4955 if (I)
4956 OS << ", ";
4957 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4958 }
4959
4960 if (Function->isVariadic()) {
4961 if (Function->getNumParams())
4962 OS << ", ";
4963 OS << "...";
4964 }
4965 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004966 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 }
4968
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004969 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004970 SmallString<64> Str;
4971 llvm::raw_svector_ostream OS(Str);
4972 OS << *ClassTemplate;
4973 OS << "<";
4974 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4975 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4976 if (I)
4977 OS << ", ";
4978
4979 NamedDecl *Param = Params->getParam(I);
4980 if (Param->getIdentifier()) {
4981 OS << Param->getIdentifier()->getName();
4982 continue;
4983 }
4984
4985 // There is no parameter name, which makes this tricky. Try to come up
4986 // with something useful that isn't too long.
4987 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4988 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4989 else if (NonTypeTemplateParmDecl *NTTP
4990 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4991 OS << NTTP->getType().getAsString(Policy);
4992 else
4993 OS << "template<...> class";
4994 }
4995
4996 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004997 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 }
4999
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005000 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5002 // If the type was explicitly written, use that.
5003 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005004 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005005
Benjamin Kramer9170e912013-02-22 15:46:01 +00005006 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 llvm::raw_svector_ostream OS(Str);
5008 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005009 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5010 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005011 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 }
5013
5014 return clang_getCursorSpelling(C);
5015}
5016
5017CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5018 switch (Kind) {
5019 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005020 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005022 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005024 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005026 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005028 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005030 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005032 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005034 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005036 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005038 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005040 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005042 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005083 case CXCursor_FixedPointLiteral:
5084 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005094 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005099 case CXCursor_OMPArraySectionExpr:
5100 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005151 case CXCursor_ObjCAvailabilityCheckExpr:
5152 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005153 case CXCursor_ObjCSelfExpr:
5154 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005243 case CXCursor_SEHLeaveStmt:
5244 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005262 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005268 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005270 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005272 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005273 case CXCursor_PackedAttr:
5274 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005275 case CXCursor_PureAttr:
5276 return cxstring::createRef("attribute(pure)");
5277 case CXCursor_ConstAttr:
5278 return cxstring::createRef("attribute(const)");
5279 case CXCursor_NoDuplicateAttr:
5280 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005281 case CXCursor_CUDAConstantAttr:
5282 return cxstring::createRef("attribute(constant)");
5283 case CXCursor_CUDADeviceAttr:
5284 return cxstring::createRef("attribute(device)");
5285 case CXCursor_CUDAGlobalAttr:
5286 return cxstring::createRef("attribute(global)");
5287 case CXCursor_CUDAHostAttr:
5288 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005289 case CXCursor_CUDASharedAttr:
5290 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005291 case CXCursor_VisibilityAttr:
5292 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005293 case CXCursor_DLLExport:
5294 return cxstring::createRef("attribute(dllexport)");
5295 case CXCursor_DLLImport:
5296 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005297 case CXCursor_NSReturnsRetained:
5298 return cxstring::createRef("attribute(ns_returns_retained)");
5299 case CXCursor_NSReturnsNotRetained:
5300 return cxstring::createRef("attribute(ns_returns_not_retained)");
5301 case CXCursor_NSReturnsAutoreleased:
5302 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5303 case CXCursor_NSConsumesSelf:
5304 return cxstring::createRef("attribute(ns_consumes_self)");
5305 case CXCursor_NSConsumed:
5306 return cxstring::createRef("attribute(ns_consumed)");
5307 case CXCursor_ObjCException:
5308 return cxstring::createRef("attribute(objc_exception)");
5309 case CXCursor_ObjCNSObject:
5310 return cxstring::createRef("attribute(NSObject)");
5311 case CXCursor_ObjCIndependentClass:
5312 return cxstring::createRef("attribute(objc_independent_class)");
5313 case CXCursor_ObjCPreciseLifetime:
5314 return cxstring::createRef("attribute(objc_precise_lifetime)");
5315 case CXCursor_ObjCReturnsInnerPointer:
5316 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5317 case CXCursor_ObjCRequiresSuper:
5318 return cxstring::createRef("attribute(objc_requires_super)");
5319 case CXCursor_ObjCRootClass:
5320 return cxstring::createRef("attribute(objc_root_class)");
5321 case CXCursor_ObjCSubclassingRestricted:
5322 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5323 case CXCursor_ObjCExplicitProtocolImpl:
5324 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5325 case CXCursor_ObjCDesignatedInitializer:
5326 return cxstring::createRef("attribute(objc_designated_initializer)");
5327 case CXCursor_ObjCRuntimeVisible:
5328 return cxstring::createRef("attribute(objc_runtime_visible)");
5329 case CXCursor_ObjCBoxable:
5330 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005331 case CXCursor_FlagEnum:
5332 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005334 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005336 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005338 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005340 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005342 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005344 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005346 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005348 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005350 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005354 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005355 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005356 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005358 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005360 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005362 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005364 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005365 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005366 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005368 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005369 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005370 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005371 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005372 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005374 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005375 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005376 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005378 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005379 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005380 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005381 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005382 return cxstring::createRef("OMPParallelDirective");
5383 case CXCursor_OMPSimdDirective:
5384 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005385 case CXCursor_OMPForDirective:
5386 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005387 case CXCursor_OMPForSimdDirective:
5388 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005389 case CXCursor_OMPSectionsDirective:
5390 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005391 case CXCursor_OMPSectionDirective:
5392 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005393 case CXCursor_OMPSingleDirective:
5394 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005395 case CXCursor_OMPMasterDirective:
5396 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005397 case CXCursor_OMPCriticalDirective:
5398 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005399 case CXCursor_OMPParallelForDirective:
5400 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005401 case CXCursor_OMPParallelForSimdDirective:
5402 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005403 case CXCursor_OMPParallelSectionsDirective:
5404 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005405 case CXCursor_OMPTaskDirective:
5406 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005407 case CXCursor_OMPTaskyieldDirective:
5408 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005409 case CXCursor_OMPBarrierDirective:
5410 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005411 case CXCursor_OMPTaskwaitDirective:
5412 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005413 case CXCursor_OMPTaskgroupDirective:
5414 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005415 case CXCursor_OMPFlushDirective:
5416 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005417 case CXCursor_OMPOrderedDirective:
5418 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005419 case CXCursor_OMPAtomicDirective:
5420 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005421 case CXCursor_OMPTargetDirective:
5422 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005423 case CXCursor_OMPTargetDataDirective:
5424 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005425 case CXCursor_OMPTargetEnterDataDirective:
5426 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005427 case CXCursor_OMPTargetExitDataDirective:
5428 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005429 case CXCursor_OMPTargetParallelDirective:
5430 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005431 case CXCursor_OMPTargetParallelForDirective:
5432 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005433 case CXCursor_OMPTargetUpdateDirective:
5434 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005435 case CXCursor_OMPTeamsDirective:
5436 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005437 case CXCursor_OMPCancellationPointDirective:
5438 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005439 case CXCursor_OMPCancelDirective:
5440 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005441 case CXCursor_OMPTaskLoopDirective:
5442 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005443 case CXCursor_OMPTaskLoopSimdDirective:
5444 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005445 case CXCursor_OMPDistributeDirective:
5446 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005447 case CXCursor_OMPDistributeParallelForDirective:
5448 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005449 case CXCursor_OMPDistributeParallelForSimdDirective:
5450 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005451 case CXCursor_OMPDistributeSimdDirective:
5452 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005453 case CXCursor_OMPTargetParallelForSimdDirective:
5454 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005455 case CXCursor_OMPTargetSimdDirective:
5456 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005457 case CXCursor_OMPTeamsDistributeDirective:
5458 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005459 case CXCursor_OMPTeamsDistributeSimdDirective:
5460 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005461 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5462 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005463 case CXCursor_OMPTeamsDistributeParallelForDirective:
5464 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005465 case CXCursor_OMPTargetTeamsDirective:
5466 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005467 case CXCursor_OMPTargetTeamsDistributeDirective:
5468 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005469 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5470 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005471 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5472 return cxstring::createRef(
5473 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005474 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5475 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005476 case CXCursor_OverloadCandidate:
5477 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005478 case CXCursor_TypeAliasTemplateDecl:
5479 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005480 case CXCursor_StaticAssert:
5481 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005482 case CXCursor_FriendDecl:
5483 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005484 }
5485
5486 llvm_unreachable("Unhandled CXCursorKind");
5487}
5488
5489struct GetCursorData {
5490 SourceLocation TokenBeginLoc;
5491 bool PointsAtMacroArgExpansion;
5492 bool VisitedObjCPropertyImplDecl;
5493 SourceLocation VisitedDeclaratorDeclStartLoc;
5494 CXCursor &BestCursor;
5495
5496 GetCursorData(SourceManager &SM,
5497 SourceLocation tokenBegin, CXCursor &outputCursor)
5498 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5499 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5500 VisitedObjCPropertyImplDecl = false;
5501 }
5502};
5503
5504static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5505 CXCursor parent,
5506 CXClientData client_data) {
5507 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5508 CXCursor *BestCursor = &Data->BestCursor;
5509
5510 // If we point inside a macro argument we should provide info of what the
5511 // token is so use the actual cursor, don't replace it with a macro expansion
5512 // cursor.
5513 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5514 return CXChildVisit_Recurse;
5515
5516 if (clang_isDeclaration(cursor.kind)) {
5517 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005518 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5520 if (MD->isImplicit())
5521 return CXChildVisit_Break;
5522
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005523 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005524 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5525 // Check that when we have multiple @class references in the same line,
5526 // that later ones do not override the previous ones.
5527 // If we have:
5528 // @class Foo, Bar;
5529 // source ranges for both start at '@', so 'Bar' will end up overriding
5530 // 'Foo' even though the cursor location was at 'Foo'.
5531 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5532 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005533 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005534 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5535 if (PrevID != ID &&
5536 !PrevID->isThisDeclarationADefinition() &&
5537 !ID->isThisDeclarationADefinition())
5538 return CXChildVisit_Break;
5539 }
5540
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005541 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005542 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5543 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5544 // Check that when we have multiple declarators in the same line,
5545 // that later ones do not override the previous ones.
5546 // If we have:
5547 // int Foo, Bar;
5548 // source ranges for both start at 'int', so 'Bar' will end up overriding
5549 // 'Foo' even though the cursor location was at 'Foo'.
5550 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5551 return CXChildVisit_Break;
5552 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5553
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005554 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005555 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5556 (void)PropImp;
5557 // Check that when we have multiple @synthesize in the same line,
5558 // that later ones do not override the previous ones.
5559 // If we have:
5560 // @synthesize Foo, Bar;
5561 // source ranges for both start at '@', so 'Bar' will end up overriding
5562 // 'Foo' even though the cursor location was at 'Foo'.
5563 if (Data->VisitedObjCPropertyImplDecl)
5564 return CXChildVisit_Break;
5565 Data->VisitedObjCPropertyImplDecl = true;
5566 }
5567 }
5568
5569 if (clang_isExpression(cursor.kind) &&
5570 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005571 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005572 // Avoid having the cursor of an expression replace the declaration cursor
5573 // when the expression source range overlaps the declaration range.
5574 // This can happen for C++ constructor expressions whose range generally
5575 // include the variable declaration, e.g.:
5576 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5577 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5578 D->getLocation() == Data->TokenBeginLoc)
5579 return CXChildVisit_Break;
5580 }
5581 }
5582
5583 // If our current best cursor is the construction of a temporary object,
5584 // don't replace that cursor with a type reference, because we want
5585 // clang_getCursor() to point at the constructor.
5586 if (clang_isExpression(BestCursor->kind) &&
5587 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5588 cursor.kind == CXCursor_TypeRef) {
5589 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5590 // as having the actual point on the type reference.
5591 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5592 return CXChildVisit_Recurse;
5593 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005594
5595 // If we already have an Objective-C superclass reference, don't
5596 // update it further.
5597 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5598 return CXChildVisit_Break;
5599
Guy Benyei11169dd2012-12-18 14:30:41 +00005600 *BestCursor = cursor;
5601 return CXChildVisit_Recurse;
5602}
5603
5604CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005605 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005606 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005607 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005608 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005609
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005610 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005611 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5612
5613 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5614 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5615
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005616 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005617 CXFile SearchFile;
5618 unsigned SearchLine, SearchColumn;
5619 CXFile ResultFile;
5620 unsigned ResultLine, ResultColumn;
5621 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5622 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5623 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005624
5625 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5626 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005627 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005628 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 SearchFileName = clang_getFileName(SearchFile);
5630 ResultFileName = clang_getFileName(ResultFile);
5631 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5632 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005633 *Log << llvm::format("(%s:%d:%d) = %s",
5634 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5635 clang_getCString(KindSpelling))
5636 << llvm::format("(%s:%d:%d):%s%s",
5637 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5638 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005639 clang_disposeString(SearchFileName);
5640 clang_disposeString(ResultFileName);
5641 clang_disposeString(KindSpelling);
5642 clang_disposeString(USR);
5643
5644 CXCursor Definition = clang_getCursorDefinition(Result);
5645 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5646 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5647 CXString DefinitionKindSpelling
5648 = clang_getCursorKindSpelling(Definition.kind);
5649 CXFile DefinitionFile;
5650 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005651 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005652 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005653 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005654 *Log << llvm::format(" -> %s(%s:%d:%d)",
5655 clang_getCString(DefinitionKindSpelling),
5656 clang_getCString(DefinitionFileName),
5657 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 clang_disposeString(DefinitionFileName);
5659 clang_disposeString(DefinitionKindSpelling);
5660 }
5661 }
5662
5663 return Result;
5664}
5665
5666CXCursor clang_getNullCursor(void) {
5667 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5668}
5669
5670unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005671 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5672 // can't set consistently. For example, when visiting a DeclStmt we will set
5673 // it but we don't set it on the result of clang_getCursorDefinition for
5674 // a reference of the same declaration.
5675 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5676 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5677 // to provide that kind of info.
5678 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005679 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005680 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005681 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005682
Guy Benyei11169dd2012-12-18 14:30:41 +00005683 return X == Y;
5684}
5685
5686unsigned clang_hashCursor(CXCursor C) {
5687 unsigned Index = 0;
5688 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5689 Index = 1;
5690
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005691 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005692 std::make_pair(C.kind, C.data[Index]));
5693}
5694
5695unsigned clang_isInvalid(enum CXCursorKind K) {
5696 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5697}
5698
5699unsigned clang_isDeclaration(enum CXCursorKind K) {
5700 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005701 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5702}
5703
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005704unsigned clang_isInvalidDeclaration(CXCursor C) {
5705 if (clang_isDeclaration(C.kind)) {
5706 if (const Decl *D = getCursorDecl(C))
5707 return D->isInvalidDecl();
5708 }
5709
5710 return 0;
5711}
5712
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005713unsigned clang_isReference(enum CXCursorKind K) {
5714 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5715}
Guy Benyei11169dd2012-12-18 14:30:41 +00005716
5717unsigned clang_isExpression(enum CXCursorKind K) {
5718 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5719}
5720
5721unsigned clang_isStatement(enum CXCursorKind K) {
5722 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5723}
5724
5725unsigned clang_isAttribute(enum CXCursorKind K) {
5726 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5727}
5728
5729unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5730 return K == CXCursor_TranslationUnit;
5731}
5732
5733unsigned clang_isPreprocessing(enum CXCursorKind K) {
5734 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5735}
5736
5737unsigned clang_isUnexposed(enum CXCursorKind K) {
5738 switch (K) {
5739 case CXCursor_UnexposedDecl:
5740 case CXCursor_UnexposedExpr:
5741 case CXCursor_UnexposedStmt:
5742 case CXCursor_UnexposedAttr:
5743 return true;
5744 default:
5745 return false;
5746 }
5747}
5748
5749CXCursorKind clang_getCursorKind(CXCursor C) {
5750 return C.kind;
5751}
5752
5753CXSourceLocation clang_getCursorLocation(CXCursor C) {
5754 if (clang_isReference(C.kind)) {
5755 switch (C.kind) {
5756 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005757 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005758 = getCursorObjCSuperClassRef(C);
5759 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5760 }
5761
5762 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005763 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 = getCursorObjCProtocolRef(C);
5765 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5766 }
5767
5768 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005769 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005770 = getCursorObjCClassRef(C);
5771 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5772 }
5773
5774 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005775 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005776 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5777 }
5778
5779 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005780 std::pair<const TemplateDecl *, SourceLocation> P =
5781 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005782 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5783 }
5784
5785 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005786 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005787 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5788 }
5789
5790 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005791 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5793 }
5794
5795 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005796 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005797 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5798 }
5799
5800 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005801 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005802 if (!BaseSpec)
5803 return clang_getNullLocation();
5804
5805 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5806 return cxloc::translateSourceLocation(getCursorContext(C),
5807 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005808
Guy Benyei11169dd2012-12-18 14:30:41 +00005809 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005810 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005811 }
5812
5813 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005814 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005815 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5816 }
5817
5818 case CXCursor_OverloadedDeclRef:
5819 return cxloc::translateSourceLocation(getCursorContext(C),
5820 getCursorOverloadedDeclRef(C).second);
5821
5822 default:
5823 // FIXME: Need a way to enumerate all non-reference cases.
5824 llvm_unreachable("Missed a reference kind");
5825 }
5826 }
5827
5828 if (clang_isExpression(C.kind))
5829 return cxloc::translateSourceLocation(getCursorContext(C),
5830 getLocationFromExpr(getCursorExpr(C)));
5831
5832 if (clang_isStatement(C.kind))
5833 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005834 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005835
5836 if (C.kind == CXCursor_PreprocessingDirective) {
5837 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5838 return cxloc::translateSourceLocation(getCursorContext(C), L);
5839 }
5840
5841 if (C.kind == CXCursor_MacroExpansion) {
5842 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005843 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005844 return cxloc::translateSourceLocation(getCursorContext(C), L);
5845 }
5846
5847 if (C.kind == CXCursor_MacroDefinition) {
5848 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5849 return cxloc::translateSourceLocation(getCursorContext(C), L);
5850 }
5851
5852 if (C.kind == CXCursor_InclusionDirective) {
5853 SourceLocation L
5854 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5855 return cxloc::translateSourceLocation(getCursorContext(C), L);
5856 }
5857
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005858 if (clang_isAttribute(C.kind)) {
5859 SourceLocation L
5860 = cxcursor::getCursorAttr(C)->getLocation();
5861 return cxloc::translateSourceLocation(getCursorContext(C), L);
5862 }
5863
Guy Benyei11169dd2012-12-18 14:30:41 +00005864 if (!clang_isDeclaration(C.kind))
5865 return clang_getNullLocation();
5866
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005867 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005868 if (!D)
5869 return clang_getNullLocation();
5870
5871 SourceLocation Loc = D->getLocation();
5872 // FIXME: Multiple variables declared in a single declaration
5873 // currently lack the information needed to correctly determine their
5874 // ranges when accounting for the type-specifier. We use context
5875 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5876 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005877 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005878 if (!cxcursor::isFirstInDeclGroup(C))
5879 Loc = VD->getLocation();
5880 }
5881
5882 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005883 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005884 Loc = MD->getSelectorStartLoc();
5885
5886 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5887}
5888
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005889} // end extern "C"
5890
Guy Benyei11169dd2012-12-18 14:30:41 +00005891CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5892 assert(TU);
5893
5894 // Guard against an invalid SourceLocation, or we may assert in one
5895 // of the following calls.
5896 if (SLoc.isInvalid())
5897 return clang_getNullCursor();
5898
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005899 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005900
5901 // Translate the given source location to make it point at the beginning of
5902 // the token under the cursor.
5903 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5904 CXXUnit->getASTContext().getLangOpts());
5905
5906 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5907 if (SLoc.isValid()) {
5908 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5909 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5910 /*VisitPreprocessorLast=*/true,
5911 /*VisitIncludedEntities=*/false,
5912 SourceLocation(SLoc));
5913 CursorVis.visitFileRegion();
5914 }
5915
5916 return Result;
5917}
5918
5919static SourceRange getRawCursorExtent(CXCursor C) {
5920 if (clang_isReference(C.kind)) {
5921 switch (C.kind) {
5922 case CXCursor_ObjCSuperClassRef:
5923 return getCursorObjCSuperClassRef(C).second;
5924
5925 case CXCursor_ObjCProtocolRef:
5926 return getCursorObjCProtocolRef(C).second;
5927
5928 case CXCursor_ObjCClassRef:
5929 return getCursorObjCClassRef(C).second;
5930
5931 case CXCursor_TypeRef:
5932 return getCursorTypeRef(C).second;
5933
5934 case CXCursor_TemplateRef:
5935 return getCursorTemplateRef(C).second;
5936
5937 case CXCursor_NamespaceRef:
5938 return getCursorNamespaceRef(C).second;
5939
5940 case CXCursor_MemberRef:
5941 return getCursorMemberRef(C).second;
5942
5943 case CXCursor_CXXBaseSpecifier:
5944 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5945
5946 case CXCursor_LabelRef:
5947 return getCursorLabelRef(C).second;
5948
5949 case CXCursor_OverloadedDeclRef:
5950 return getCursorOverloadedDeclRef(C).second;
5951
5952 case CXCursor_VariableRef:
5953 return getCursorVariableRef(C).second;
5954
5955 default:
5956 // FIXME: Need a way to enumerate all non-reference cases.
5957 llvm_unreachable("Missed a reference kind");
5958 }
5959 }
5960
5961 if (clang_isExpression(C.kind))
5962 return getCursorExpr(C)->getSourceRange();
5963
5964 if (clang_isStatement(C.kind))
5965 return getCursorStmt(C)->getSourceRange();
5966
5967 if (clang_isAttribute(C.kind))
5968 return getCursorAttr(C)->getRange();
5969
5970 if (C.kind == CXCursor_PreprocessingDirective)
5971 return cxcursor::getCursorPreprocessingDirective(C);
5972
5973 if (C.kind == CXCursor_MacroExpansion) {
5974 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005975 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 return TU->mapRangeFromPreamble(Range);
5977 }
5978
5979 if (C.kind == CXCursor_MacroDefinition) {
5980 ASTUnit *TU = getCursorASTUnit(C);
5981 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5982 return TU->mapRangeFromPreamble(Range);
5983 }
5984
5985 if (C.kind == CXCursor_InclusionDirective) {
5986 ASTUnit *TU = getCursorASTUnit(C);
5987 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5988 return TU->mapRangeFromPreamble(Range);
5989 }
5990
5991 if (C.kind == CXCursor_TranslationUnit) {
5992 ASTUnit *TU = getCursorASTUnit(C);
5993 FileID MainID = TU->getSourceManager().getMainFileID();
5994 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5995 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5996 return SourceRange(Start, End);
5997 }
5998
5999 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006000 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006001 if (!D)
6002 return SourceRange();
6003
6004 SourceRange R = D->getSourceRange();
6005 // FIXME: Multiple variables declared in a single declaration
6006 // currently lack the information needed to correctly determine their
6007 // ranges when accounting for the type-specifier. We use context
6008 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6009 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006010 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006011 if (!cxcursor::isFirstInDeclGroup(C))
6012 R.setBegin(VD->getLocation());
6013 }
6014 return R;
6015 }
6016 return SourceRange();
6017}
6018
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006019/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006020/// the decl-specifier-seq for declarations.
6021static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6022 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006023 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006024 if (!D)
6025 return SourceRange();
6026
6027 SourceRange R = D->getSourceRange();
6028
6029 // Adjust the start of the location for declarations preceded by
6030 // declaration specifiers.
6031 SourceLocation StartLoc;
6032 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6033 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006034 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006035 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006036 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006037 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006038 }
6039
6040 if (StartLoc.isValid() && R.getBegin().isValid() &&
6041 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6042 R.setBegin(StartLoc);
6043
6044 // FIXME: Multiple variables declared in a single declaration
6045 // currently lack the information needed to correctly determine their
6046 // ranges when accounting for the type-specifier. We use context
6047 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6048 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006049 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 if (!cxcursor::isFirstInDeclGroup(C))
6051 R.setBegin(VD->getLocation());
6052 }
6053
6054 return R;
6055 }
6056
6057 return getRawCursorExtent(C);
6058}
6059
Guy Benyei11169dd2012-12-18 14:30:41 +00006060CXSourceRange clang_getCursorExtent(CXCursor C) {
6061 SourceRange R = getRawCursorExtent(C);
6062 if (R.isInvalid())
6063 return clang_getNullRange();
6064
6065 return cxloc::translateSourceRange(getCursorContext(C), R);
6066}
6067
6068CXCursor clang_getCursorReferenced(CXCursor C) {
6069 if (clang_isInvalid(C.kind))
6070 return clang_getNullCursor();
6071
6072 CXTranslationUnit tu = getCursorTU(C);
6073 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006074 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 if (!D)
6076 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006077 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006078 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006079 if (const ObjCPropertyImplDecl *PropImpl =
6080 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6082 return MakeCXCursor(Property, tu);
6083
6084 return C;
6085 }
6086
6087 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006088 const Expr *E = getCursorExpr(C);
6089 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006090 if (D) {
6091 CXCursor declCursor = MakeCXCursor(D, tu);
6092 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6093 declCursor);
6094 return declCursor;
6095 }
6096
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006097 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006098 return MakeCursorOverloadedDeclRef(Ovl, tu);
6099
6100 return clang_getNullCursor();
6101 }
6102
6103 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006104 const Stmt *S = getCursorStmt(C);
6105 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 if (LabelDecl *label = Goto->getLabel())
6107 if (LabelStmt *labelS = label->getStmt())
6108 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6109
6110 return clang_getNullCursor();
6111 }
Richard Smith66a81862015-05-04 02:25:31 +00006112
Guy Benyei11169dd2012-12-18 14:30:41 +00006113 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006114 if (const MacroDefinitionRecord *Def =
6115 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006116 return MakeMacroDefinitionCursor(Def, tu);
6117 }
6118
6119 if (!clang_isReference(C.kind))
6120 return clang_getNullCursor();
6121
6122 switch (C.kind) {
6123 case CXCursor_ObjCSuperClassRef:
6124 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6125
6126 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006127 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6128 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006129 return MakeCXCursor(Def, tu);
6130
6131 return MakeCXCursor(Prot, tu);
6132 }
6133
6134 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006135 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6136 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006137 return MakeCXCursor(Def, tu);
6138
6139 return MakeCXCursor(Class, tu);
6140 }
6141
6142 case CXCursor_TypeRef:
6143 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6144
6145 case CXCursor_TemplateRef:
6146 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6147
6148 case CXCursor_NamespaceRef:
6149 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6150
6151 case CXCursor_MemberRef:
6152 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6153
6154 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006155 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006156 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6157 tu ));
6158 }
6159
6160 case CXCursor_LabelRef:
6161 // FIXME: We end up faking the "parent" declaration here because we
6162 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006163 return MakeCXCursor(getCursorLabelRef(C).first,
6164 cxtu::getASTUnit(tu)->getASTContext()
6165 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 tu);
6167
6168 case CXCursor_OverloadedDeclRef:
6169 return C;
6170
6171 case CXCursor_VariableRef:
6172 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6173
6174 default:
6175 // We would prefer to enumerate all non-reference cursor kinds here.
6176 llvm_unreachable("Unhandled reference cursor kind");
6177 }
6178}
6179
6180CXCursor clang_getCursorDefinition(CXCursor C) {
6181 if (clang_isInvalid(C.kind))
6182 return clang_getNullCursor();
6183
6184 CXTranslationUnit TU = getCursorTU(C);
6185
6186 bool WasReference = false;
6187 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6188 C = clang_getCursorReferenced(C);
6189 WasReference = true;
6190 }
6191
6192 if (C.kind == CXCursor_MacroExpansion)
6193 return clang_getCursorReferenced(C);
6194
6195 if (!clang_isDeclaration(C.kind))
6196 return clang_getNullCursor();
6197
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006198 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006199 if (!D)
6200 return clang_getNullCursor();
6201
6202 switch (D->getKind()) {
6203 // Declaration kinds that don't really separate the notions of
6204 // declaration and definition.
6205 case Decl::Namespace:
6206 case Decl::Typedef:
6207 case Decl::TypeAlias:
6208 case Decl::TypeAliasTemplate:
6209 case Decl::TemplateTypeParm:
6210 case Decl::EnumConstant:
6211 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006212 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006213 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 case Decl::IndirectField:
6215 case Decl::ObjCIvar:
6216 case Decl::ObjCAtDefsField:
6217 case Decl::ImplicitParam:
6218 case Decl::ParmVar:
6219 case Decl::NonTypeTemplateParm:
6220 case Decl::TemplateTemplateParm:
6221 case Decl::ObjCCategoryImpl:
6222 case Decl::ObjCImplementation:
6223 case Decl::AccessSpec:
6224 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006225 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006226 case Decl::ObjCPropertyImpl:
6227 case Decl::FileScopeAsm:
6228 case Decl::StaticAssert:
6229 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006230 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006231 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 case Decl::Label: // FIXME: Is this right??
6233 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006234 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006236 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006237 case Decl::OMPDeclareReduction:
Kelvin Li1408f912018-09-26 04:28:39 +00006238 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006239 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006240 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006241 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006242 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006243 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006244 return C;
6245
6246 // Declaration kinds that don't make any sense here, but are
6247 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006248 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006249 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006250 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006251 break;
6252
6253 // Declaration kinds for which the definition is not resolvable.
6254 case Decl::UnresolvedUsingTypename:
6255 case Decl::UnresolvedUsingValue:
6256 break;
6257
6258 case Decl::UsingDirective:
6259 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6260 TU);
6261
6262 case Decl::NamespaceAlias:
6263 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6264
6265 case Decl::Enum:
6266 case Decl::Record:
6267 case Decl::CXXRecord:
6268 case Decl::ClassTemplateSpecialization:
6269 case Decl::ClassTemplatePartialSpecialization:
6270 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6271 return MakeCXCursor(Def, TU);
6272 return clang_getNullCursor();
6273
6274 case Decl::Function:
6275 case Decl::CXXMethod:
6276 case Decl::CXXConstructor:
6277 case Decl::CXXDestructor:
6278 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006279 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006280 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006281 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006282 return clang_getNullCursor();
6283 }
6284
Larisse Voufo39a1e502013-08-06 01:03:05 +00006285 case Decl::Var:
6286 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006287 case Decl::VarTemplatePartialSpecialization:
6288 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006289 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006290 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006291 return MakeCXCursor(Def, TU);
6292 return clang_getNullCursor();
6293 }
6294
6295 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006296 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006297 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6298 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6299 return clang_getNullCursor();
6300 }
6301
6302 case Decl::ClassTemplate: {
6303 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6304 ->getDefinition())
6305 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6306 TU);
6307 return clang_getNullCursor();
6308 }
6309
Larisse Voufo39a1e502013-08-06 01:03:05 +00006310 case Decl::VarTemplate: {
6311 if (VarDecl *Def =
6312 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6313 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6314 return clang_getNullCursor();
6315 }
6316
Guy Benyei11169dd2012-12-18 14:30:41 +00006317 case Decl::Using:
6318 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6319 D->getLocation(), TU);
6320
6321 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006322 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006323 return clang_getCursorDefinition(
6324 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6325 TU));
6326
6327 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006328 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006329 if (Method->isThisDeclarationADefinition())
6330 return C;
6331
6332 // Dig out the method definition in the associated
6333 // @implementation, if we have it.
6334 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006335 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006336 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6337 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6338 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6339 Method->isInstanceMethod()))
6340 if (Def->isThisDeclarationADefinition())
6341 return MakeCXCursor(Def, TU);
6342
6343 return clang_getNullCursor();
6344 }
6345
6346 case Decl::ObjCCategory:
6347 if (ObjCCategoryImplDecl *Impl
6348 = cast<ObjCCategoryDecl>(D)->getImplementation())
6349 return MakeCXCursor(Impl, TU);
6350 return clang_getNullCursor();
6351
6352 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006353 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006354 return MakeCXCursor(Def, TU);
6355 return clang_getNullCursor();
6356
6357 case Decl::ObjCInterface: {
6358 // There are two notions of a "definition" for an Objective-C
6359 // class: the interface and its implementation. When we resolved a
6360 // reference to an Objective-C class, produce the @interface as
6361 // the definition; when we were provided with the interface,
6362 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006363 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006364 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006365 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006366 return MakeCXCursor(Def, TU);
6367 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6368 return MakeCXCursor(Impl, TU);
6369 return clang_getNullCursor();
6370 }
6371
6372 case Decl::ObjCProperty:
6373 // FIXME: We don't really know where to find the
6374 // ObjCPropertyImplDecls that implement this property.
6375 return clang_getNullCursor();
6376
6377 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006378 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006379 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006380 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 return MakeCXCursor(Def, TU);
6382
6383 return clang_getNullCursor();
6384
6385 case Decl::Friend:
6386 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6387 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6388 return clang_getNullCursor();
6389
6390 case Decl::FriendTemplate:
6391 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6392 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6393 return clang_getNullCursor();
6394 }
6395
6396 return clang_getNullCursor();
6397}
6398
6399unsigned clang_isCursorDefinition(CXCursor C) {
6400 if (!clang_isDeclaration(C.kind))
6401 return 0;
6402
6403 return clang_getCursorDefinition(C) == C;
6404}
6405
6406CXCursor clang_getCanonicalCursor(CXCursor C) {
6407 if (!clang_isDeclaration(C.kind))
6408 return C;
6409
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006410 if (const Decl *D = getCursorDecl(C)) {
6411 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6413 return MakeCXCursor(CatD, getCursorTU(C));
6414
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006415 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6416 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006417 return MakeCXCursor(IFD, getCursorTU(C));
6418
6419 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6420 }
6421
6422 return C;
6423}
6424
6425int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6426 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6427}
6428
6429unsigned clang_getNumOverloadedDecls(CXCursor C) {
6430 if (C.kind != CXCursor_OverloadedDeclRef)
6431 return 0;
6432
6433 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006434 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006435 return E->getNumDecls();
6436
6437 if (OverloadedTemplateStorage *S
6438 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6439 return S->size();
6440
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006441 const Decl *D = Storage.get<const Decl *>();
6442 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006443 return Using->shadow_size();
6444
6445 return 0;
6446}
6447
6448CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6449 if (cursor.kind != CXCursor_OverloadedDeclRef)
6450 return clang_getNullCursor();
6451
6452 if (index >= clang_getNumOverloadedDecls(cursor))
6453 return clang_getNullCursor();
6454
6455 CXTranslationUnit TU = getCursorTU(cursor);
6456 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006457 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006458 return MakeCXCursor(E->decls_begin()[index], TU);
6459
6460 if (OverloadedTemplateStorage *S
6461 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6462 return MakeCXCursor(S->begin()[index], TU);
6463
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006464 const Decl *D = Storage.get<const Decl *>();
6465 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006466 // FIXME: This is, unfortunately, linear time.
6467 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6468 std::advance(Pos, index);
6469 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6470 }
6471
6472 return clang_getNullCursor();
6473}
6474
6475void clang_getDefinitionSpellingAndExtent(CXCursor C,
6476 const char **startBuf,
6477 const char **endBuf,
6478 unsigned *startLine,
6479 unsigned *startColumn,
6480 unsigned *endLine,
6481 unsigned *endColumn) {
6482 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006483 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6485
6486 SourceManager &SM = FD->getASTContext().getSourceManager();
6487 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6488 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6489 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6490 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6491 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6492 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6493}
6494
6495
6496CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6497 unsigned PieceIndex) {
6498 RefNamePieces Pieces;
6499
6500 switch (C.kind) {
6501 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006502 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006503 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6504 E->getQualifierLoc().getSourceRange());
6505 break;
6506
6507 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006508 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6509 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6510 Pieces =
6511 buildPieces(NameFlags, false, E->getNameInfo(),
6512 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6513 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006514 break;
6515
6516 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006517 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006518 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006519 const Expr *Callee = OCE->getCallee();
6520 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 Callee = ICE->getSubExpr();
6522
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006523 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006524 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6525 DRE->getQualifierLoc().getSourceRange());
6526 }
6527 break;
6528
6529 default:
6530 break;
6531 }
6532
6533 if (Pieces.empty()) {
6534 if (PieceIndex == 0)
6535 return clang_getCursorExtent(C);
6536 } else if (PieceIndex < Pieces.size()) {
6537 SourceRange R = Pieces[PieceIndex];
6538 if (R.isValid())
6539 return cxloc::translateSourceRange(getCursorContext(C), R);
6540 }
6541
6542 return clang_getNullRange();
6543}
6544
6545void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006546 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6547 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006548}
6549
6550void clang_executeOnThread(void (*fn)(void*), void *user_data,
6551 unsigned stack_size) {
6552 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6553}
6554
Guy Benyei11169dd2012-12-18 14:30:41 +00006555//===----------------------------------------------------------------------===//
6556// Token-based Operations.
6557//===----------------------------------------------------------------------===//
6558
6559/* CXToken layout:
6560 * int_data[0]: a CXTokenKind
6561 * int_data[1]: starting token location
6562 * int_data[2]: token length
6563 * int_data[3]: reserved
6564 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6565 * otherwise unused.
6566 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006567CXTokenKind clang_getTokenKind(CXToken CXTok) {
6568 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6569}
6570
6571CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6572 switch (clang_getTokenKind(CXTok)) {
6573 case CXToken_Identifier:
6574 case CXToken_Keyword:
6575 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006576 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006577 ->getNameStart());
6578
6579 case CXToken_Literal: {
6580 // We have stashed the starting pointer in the ptr_data field. Use it.
6581 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006582 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 }
6584
6585 case CXToken_Punctuation:
6586 case CXToken_Comment:
6587 break;
6588 }
6589
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006590 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006591 LOG_BAD_TU(TU);
6592 return cxstring::createEmpty();
6593 }
6594
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 // We have to find the starting buffer pointer the hard way, by
6596 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006597 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006598 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006599 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006600
6601 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6602 std::pair<FileID, unsigned> LocInfo
6603 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6604 bool Invalid = false;
6605 StringRef Buffer
6606 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6607 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006608 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006609
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006610 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006611}
6612
6613CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006614 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006615 LOG_BAD_TU(TU);
6616 return clang_getNullLocation();
6617 }
6618
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006619 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006620 if (!CXXUnit)
6621 return clang_getNullLocation();
6622
6623 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6624 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6625}
6626
6627CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006628 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006629 LOG_BAD_TU(TU);
6630 return clang_getNullRange();
6631 }
6632
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006633 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006634 if (!CXXUnit)
6635 return clang_getNullRange();
6636
6637 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6638 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6639}
6640
6641static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6642 SmallVectorImpl<CXToken> &CXTokens) {
6643 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6644 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006645 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006646 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006647 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006648
6649 // Cannot tokenize across files.
6650 if (BeginLocInfo.first != EndLocInfo.first)
6651 return;
6652
6653 // Create a lexer
6654 bool Invalid = false;
6655 StringRef Buffer
6656 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6657 if (Invalid)
6658 return;
6659
6660 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6661 CXXUnit->getASTContext().getLangOpts(),
6662 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6663 Lex.SetCommentRetentionState(true);
6664
6665 // Lex tokens until we hit the end of the range.
6666 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6667 Token Tok;
6668 bool previousWasAt = false;
6669 do {
6670 // Lex the next token
6671 Lex.LexFromRawLexer(Tok);
6672 if (Tok.is(tok::eof))
6673 break;
6674
6675 // Initialize the CXToken.
6676 CXToken CXTok;
6677
6678 // - Common fields
6679 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6680 CXTok.int_data[2] = Tok.getLength();
6681 CXTok.int_data[3] = 0;
6682
6683 // - Kind-specific fields
6684 if (Tok.isLiteral()) {
6685 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006686 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006687 } else if (Tok.is(tok::raw_identifier)) {
6688 // Lookup the identifier to determine whether we have a keyword.
6689 IdentifierInfo *II
6690 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6691
6692 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6693 CXTok.int_data[0] = CXToken_Keyword;
6694 }
6695 else {
6696 CXTok.int_data[0] = Tok.is(tok::identifier)
6697 ? CXToken_Identifier
6698 : CXToken_Keyword;
6699 }
6700 CXTok.ptr_data = II;
6701 } else if (Tok.is(tok::comment)) {
6702 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006703 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006704 } else {
6705 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006706 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006707 }
6708 CXTokens.push_back(CXTok);
6709 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006710 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006711}
6712
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006713CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6714 LOG_FUNC_SECTION {
6715 *Log << TU << ' ' << Location;
6716 }
6717
6718 if (isNotUsableTU(TU)) {
6719 LOG_BAD_TU(TU);
6720 return NULL;
6721 }
6722
6723 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6724 if (!CXXUnit)
6725 return NULL;
6726
6727 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6728 if (Begin.isInvalid())
6729 return NULL;
6730 SourceManager &SM = CXXUnit->getSourceManager();
6731 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6732 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6733
6734 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6735
6736 SmallVector<CXToken, 32> CXTokens;
6737 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6738
6739 if (CXTokens.empty())
6740 return NULL;
6741
6742 CXTokens.resize(1);
6743 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6744
6745 memmove(Token, CXTokens.data(), sizeof(CXToken));
6746 return Token;
6747}
6748
Guy Benyei11169dd2012-12-18 14:30:41 +00006749void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6750 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006751 LOG_FUNC_SECTION {
6752 *Log << TU << ' ' << Range;
6753 }
6754
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006756 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006757 if (NumTokens)
6758 *NumTokens = 0;
6759
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006760 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006761 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006762 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006763 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006764
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006765 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 if (!CXXUnit || !Tokens || !NumTokens)
6767 return;
6768
6769 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6770
6771 SourceRange R = cxloc::translateCXSourceRange(Range);
6772 if (R.isInvalid())
6773 return;
6774
6775 SmallVector<CXToken, 32> CXTokens;
6776 getTokens(CXXUnit, R, CXTokens);
6777
6778 if (CXTokens.empty())
6779 return;
6780
Serge Pavlov52525732018-02-21 02:02:39 +00006781 *Tokens = static_cast<CXToken *>(
6782 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006783 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6784 *NumTokens = CXTokens.size();
6785}
6786
6787void clang_disposeTokens(CXTranslationUnit TU,
6788 CXToken *Tokens, unsigned NumTokens) {
6789 free(Tokens);
6790}
6791
Guy Benyei11169dd2012-12-18 14:30:41 +00006792//===----------------------------------------------------------------------===//
6793// Token annotation APIs.
6794//===----------------------------------------------------------------------===//
6795
Guy Benyei11169dd2012-12-18 14:30:41 +00006796static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6797 CXCursor parent,
6798 CXClientData client_data);
6799static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6800 CXClientData client_data);
6801
6802namespace {
6803class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006804 CXToken *Tokens;
6805 CXCursor *Cursors;
6806 unsigned NumTokens;
6807 unsigned TokIdx;
6808 unsigned PreprocessingTokIdx;
6809 CursorVisitor AnnotateVis;
6810 SourceManager &SrcMgr;
6811 bool HasContextSensitiveKeywords;
6812
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006813 struct PostChildrenAction {
6814 CXCursor cursor;
6815 enum Action { Invalid, Ignore, Postpone } action;
6816 };
6817 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6818
Guy Benyei11169dd2012-12-18 14:30:41 +00006819 struct PostChildrenInfo {
6820 CXCursor Cursor;
6821 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006822 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006823 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006824 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006825 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006826 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006827
6828 CXToken &getTok(unsigned Idx) {
6829 assert(Idx < NumTokens);
6830 return Tokens[Idx];
6831 }
6832 const CXToken &getTok(unsigned Idx) const {
6833 assert(Idx < NumTokens);
6834 return Tokens[Idx];
6835 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006836 bool MoreTokens() const { return TokIdx < NumTokens; }
6837 unsigned NextToken() const { return TokIdx; }
6838 void AdvanceToken() { ++TokIdx; }
6839 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006840 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006841 }
6842 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006843 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006844 }
6845 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006846 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006847 }
6848
6849 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006850 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006851 SourceRange);
6852
6853public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006854 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006855 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006856 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006858 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006859 AnnotateTokensVisitor, this,
6860 /*VisitPreprocessorLast=*/true,
6861 /*VisitIncludedEntities=*/false,
6862 RegionOfInterest,
6863 /*VisitDeclsOnly=*/false,
6864 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006865 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006866 HasContextSensitiveKeywords(false) { }
6867
6868 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6869 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006870 bool IsIgnoredChildCursor(CXCursor cursor) const;
6871 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6872
Guy Benyei11169dd2012-12-18 14:30:41 +00006873 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006874 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6875 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6876
Guy Benyei11169dd2012-12-18 14:30:41 +00006877 void AnnotateTokens();
6878
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006879 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 /// context-sensitive keywords.
6881 bool hasContextSensitiveKeywords() const {
6882 return HasContextSensitiveKeywords;
6883 }
6884
6885 ~AnnotateTokensWorker() {
6886 assert(PostChildrenInfos.empty());
6887 }
6888};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006889}
Guy Benyei11169dd2012-12-18 14:30:41 +00006890
6891void AnnotateTokensWorker::AnnotateTokens() {
6892 // Walk the AST within the region of interest, annotating tokens
6893 // along the way.
6894 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006895}
Guy Benyei11169dd2012-12-18 14:30:41 +00006896
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006897bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6898 if (PostChildrenInfos.empty())
6899 return false;
6900
6901 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6902 if (ChildAction.cursor == cursor &&
6903 ChildAction.action == PostChildrenAction::Ignore) {
6904 return true;
6905 }
6906 }
6907
6908 return false;
6909}
6910
6911const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6912 if (!clang_isExpression(Cursor.kind))
6913 return nullptr;
6914
6915 const Expr *E = getCursorExpr(Cursor);
6916 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6917 const OverloadedOperatorKind Kind = OCE->getOperator();
6918 if (Kind == OO_Call || Kind == OO_Subscript)
6919 return OCE;
6920 }
6921
6922 return nullptr;
6923}
6924
6925AnnotateTokensWorker::PostChildrenActions
6926AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6927 PostChildrenActions actions;
6928
6929 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6930 // visited before the arguments to the operator call. For the Call and
6931 // Subscript operator the range of this DeclRefExpr includes the whole call
6932 // expression, so that all tokens in that range would be mapped to the
6933 // operator function, including the tokens of the arguments. To avoid that,
6934 // ensure to visit this DeclRefExpr as last node.
6935 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6936 const Expr *Callee = OCE->getCallee();
6937 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6938 const Expr *SubExpr = ICE->getSubExpr();
6939 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6940 const Decl *parentDecl = getCursorParentDecl(Cursor);
6941 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6942
6943 // Visit the DeclRefExpr as last.
6944 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6945 actions.push_back({cxChild, PostChildrenAction::Postpone});
6946
6947 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6948 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6949 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6950 actions.push_back({cxChild, PostChildrenAction::Ignore});
6951 }
6952 }
6953 }
6954
6955 return actions;
6956}
6957
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006958static inline void updateCursorAnnotation(CXCursor &Cursor,
6959 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006960 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006961 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006962 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006963}
6964
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006965/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006966//// between the cursor location and the source range is the same as
6967/// \arg compResult.
6968///
6969/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6970/// Pass RangeOverlap to annotate tokens inside a range.
6971void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6972 RangeComparisonResult compResult,
6973 SourceRange range) {
6974 while (MoreTokens()) {
6975 const unsigned I = NextToken();
6976 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006977 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6978 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006979
6980 SourceLocation TokLoc = GetTokenLoc(I);
6981 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006982 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 AdvanceToken();
6984 continue;
6985 }
6986 break;
6987 }
6988}
6989
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006990/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006991/// \returns true if it advanced beyond all macro tokens, false otherwise.
6992bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006993 CXCursor updateC,
6994 RangeComparisonResult compResult,
6995 SourceRange range) {
6996 assert(MoreTokens());
6997 assert(isFunctionMacroToken(NextToken()) &&
6998 "Should be called only for macro arg tokens");
6999
7000 // This works differently than annotateAndAdvanceTokens; because expanded
7001 // macro arguments can have arbitrary translation-unit source order, we do not
7002 // advance the token index one by one until a token fails the range test.
7003 // We only advance once past all of the macro arg tokens if all of them
7004 // pass the range test. If one of them fails we keep the token index pointing
7005 // at the start of the macro arg tokens so that the failing token will be
7006 // annotated by a subsequent annotation try.
7007
7008 bool atLeastOneCompFail = false;
7009
7010 unsigned I = NextToken();
7011 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7012 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7013 if (TokLoc.isFileID())
7014 continue; // not macro arg token, it's parens or comma.
7015 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7016 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7017 Cursors[I] = updateC;
7018 } else
7019 atLeastOneCompFail = true;
7020 }
7021
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007022 if (atLeastOneCompFail)
7023 return false;
7024
7025 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7026 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007027}
7028
7029enum CXChildVisitResult
7030AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007031 SourceRange cursorRange = getRawCursorExtent(cursor);
7032 if (cursorRange.isInvalid())
7033 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007034
7035 if (IsIgnoredChildCursor(cursor))
7036 return CXChildVisit_Continue;
7037
Guy Benyei11169dd2012-12-18 14:30:41 +00007038 if (!HasContextSensitiveKeywords) {
7039 // Objective-C properties can have context-sensitive keywords.
7040 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007041 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007042 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7043 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7044 }
7045 // Objective-C methods can have context-sensitive keywords.
7046 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7047 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007048 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007049 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7050 if (Method->getObjCDeclQualifier())
7051 HasContextSensitiveKeywords = true;
7052 else {
David Majnemer59f77922016-06-24 04:05:48 +00007053 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007054 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007055 HasContextSensitiveKeywords = true;
7056 break;
7057 }
7058 }
7059 }
7060 }
7061 }
7062 // C++ methods can have context-sensitive keywords.
7063 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007064 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007065 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7066 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7067 HasContextSensitiveKeywords = true;
7068 }
7069 }
7070 // C++ classes can have context-sensitive keywords.
7071 else if (cursor.kind == CXCursor_StructDecl ||
7072 cursor.kind == CXCursor_ClassDecl ||
7073 cursor.kind == CXCursor_ClassTemplate ||
7074 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007075 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007076 if (D->hasAttr<FinalAttr>())
7077 HasContextSensitiveKeywords = true;
7078 }
7079 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007080
7081 // Don't override a property annotation with its getter/setter method.
7082 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7083 parent.kind == CXCursor_ObjCPropertyDecl)
7084 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007085
7086 if (clang_isPreprocessing(cursor.kind)) {
7087 // Items in the preprocessing record are kept separate from items in
7088 // declarations, so we keep a separate token index.
7089 unsigned SavedTokIdx = TokIdx;
7090 TokIdx = PreprocessingTokIdx;
7091
7092 // Skip tokens up until we catch up to the beginning of the preprocessing
7093 // entry.
7094 while (MoreTokens()) {
7095 const unsigned I = NextToken();
7096 SourceLocation TokLoc = GetTokenLoc(I);
7097 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7098 case RangeBefore:
7099 AdvanceToken();
7100 continue;
7101 case RangeAfter:
7102 case RangeOverlap:
7103 break;
7104 }
7105 break;
7106 }
7107
7108 // Look at all of the tokens within this range.
7109 while (MoreTokens()) {
7110 const unsigned I = NextToken();
7111 SourceLocation TokLoc = GetTokenLoc(I);
7112 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7113 case RangeBefore:
7114 llvm_unreachable("Infeasible");
7115 case RangeAfter:
7116 break;
7117 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007118 // For macro expansions, just note where the beginning of the macro
7119 // expansion occurs.
7120 if (cursor.kind == CXCursor_MacroExpansion) {
7121 if (TokLoc == cursorRange.getBegin())
7122 Cursors[I] = cursor;
7123 AdvanceToken();
7124 break;
7125 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007126 // We may have already annotated macro names inside macro definitions.
7127 if (Cursors[I].kind != CXCursor_MacroExpansion)
7128 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007129 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007130 continue;
7131 }
7132 break;
7133 }
7134
7135 // Save the preprocessing token index; restore the non-preprocessing
7136 // token index.
7137 PreprocessingTokIdx = TokIdx;
7138 TokIdx = SavedTokIdx;
7139 return CXChildVisit_Recurse;
7140 }
7141
7142 if (cursorRange.isInvalid())
7143 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007144
7145 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007146 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007147 const enum CXCursorKind K = clang_getCursorKind(parent);
7148 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007149 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7150 // Attributes are annotated out-of-order, skip tokens until we reach it.
7151 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007152 ? clang_getNullCursor() : parent;
7153
7154 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7155
7156 // Avoid having the cursor of an expression "overwrite" the annotation of the
7157 // variable declaration that it belongs to.
7158 // This can happen for C++ constructor expressions whose range generally
7159 // include the variable declaration, e.g.:
7160 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007161 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007162 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00007163 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007164 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007165 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7166 E->getBeginLoc() == D->getLocation() &&
7167 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007168 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007169 AdvanceToken();
7170 }
7171 }
7172 }
7173
7174 // Before recursing into the children keep some state that we are going
7175 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7176 // extra work after the child nodes are visited.
7177 // Note that we don't call VisitChildren here to avoid traversing statements
7178 // code-recursively which can blow the stack.
7179
7180 PostChildrenInfo Info;
7181 Info.Cursor = cursor;
7182 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007183 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007184 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007185 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007186 PostChildrenInfos.push_back(Info);
7187
7188 return CXChildVisit_Recurse;
7189}
7190
7191bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7192 if (PostChildrenInfos.empty())
7193 return false;
7194 const PostChildrenInfo &Info = PostChildrenInfos.back();
7195 if (!clang_equalCursors(Info.Cursor, cursor))
7196 return false;
7197
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007198 HandlePostPonedChildCursors(Info);
7199
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7201 const unsigned AfterChildren = NextToken();
7202 SourceRange cursorRange = Info.CursorRange;
7203
7204 // Scan the tokens that are at the end of the cursor, but are not captured
7205 // but the child cursors.
7206 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7207
7208 // Scan the tokens that are at the beginning of the cursor, but are not
7209 // capture by the child cursors.
7210 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7211 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7212 break;
7213
7214 Cursors[I] = cursor;
7215 }
7216
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007217 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7218 // encountered the attribute cursor.
7219 if (clang_isAttribute(cursor.kind))
7220 TokIdx = Info.BeforeReachingCursorIdx;
7221
Guy Benyei11169dd2012-12-18 14:30:41 +00007222 PostChildrenInfos.pop_back();
7223 return false;
7224}
7225
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007226void AnnotateTokensWorker::HandlePostPonedChildCursors(
7227 const PostChildrenInfo &Info) {
7228 for (const auto &ChildAction : Info.ChildActions) {
7229 if (ChildAction.action == PostChildrenAction::Postpone) {
7230 HandlePostPonedChildCursor(ChildAction.cursor,
7231 Info.BeforeChildrenTokenIdx);
7232 }
7233 }
7234}
7235
7236void AnnotateTokensWorker::HandlePostPonedChildCursor(
7237 CXCursor Cursor, unsigned StartTokenIndex) {
7238 const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier;
7239 unsigned I = StartTokenIndex;
7240
7241 // The bracket tokens of a Call or Subscript operator are mapped to
7242 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7243 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7244 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
7245 const CXSourceRange CXRefNameRange =
7246 clang_getCursorReferenceNameRange(Cursor, flags, RefNameRangeNr);
7247 if (clang_Range_isNull(CXRefNameRange))
7248 break; // All ranges handled.
7249
7250 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7251 while (I < NumTokens) {
7252 const SourceLocation TokenLocation = GetTokenLoc(I);
7253 if (!TokenLocation.isValid())
7254 break;
7255
7256 // Adapt the end range, because LocationCompare() reports
7257 // RangeOverlap even for the not-inclusive end location.
7258 const SourceLocation fixedEnd =
7259 RefNameRange.getEnd().getLocWithOffset(-1);
7260 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7261
7262 const RangeComparisonResult ComparisonResult =
7263 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7264
7265 if (ComparisonResult == RangeOverlap) {
7266 Cursors[I++] = Cursor;
7267 } else if (ComparisonResult == RangeBefore) {
7268 ++I; // Not relevant token, check next one.
7269 } else if (ComparisonResult == RangeAfter) {
7270 break; // All tokens updated for current range, check next.
7271 }
7272 }
7273 }
7274}
7275
Guy Benyei11169dd2012-12-18 14:30:41 +00007276static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7277 CXCursor parent,
7278 CXClientData client_data) {
7279 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7280}
7281
7282static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7283 CXClientData client_data) {
7284 return static_cast<AnnotateTokensWorker*>(client_data)->
7285 postVisitChildren(cursor);
7286}
7287
7288namespace {
7289
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007290/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007291/// and mark tokens that are macro arguments. This info is used by the
7292/// AnnotateTokensWorker.
7293class MarkMacroArgTokensVisitor {
7294 SourceManager &SM;
7295 CXToken *Tokens;
7296 unsigned NumTokens;
7297 unsigned CurIdx;
7298
7299public:
7300 MarkMacroArgTokensVisitor(SourceManager &SM,
7301 CXToken *tokens, unsigned numTokens)
7302 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7303
7304 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7305 if (cursor.kind != CXCursor_MacroExpansion)
7306 return CXChildVisit_Continue;
7307
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007308 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 if (macroRange.getBegin() == macroRange.getEnd())
7310 return CXChildVisit_Continue; // it's not a function macro.
7311
7312 for (; CurIdx < NumTokens; ++CurIdx) {
7313 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7314 macroRange.getBegin()))
7315 break;
7316 }
7317
7318 if (CurIdx == NumTokens)
7319 return CXChildVisit_Break;
7320
7321 for (; CurIdx < NumTokens; ++CurIdx) {
7322 SourceLocation tokLoc = getTokenLoc(CurIdx);
7323 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7324 break;
7325
7326 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7327 }
7328
7329 if (CurIdx == NumTokens)
7330 return CXChildVisit_Break;
7331
7332 return CXChildVisit_Continue;
7333 }
7334
7335private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007336 CXToken &getTok(unsigned Idx) {
7337 assert(Idx < NumTokens);
7338 return Tokens[Idx];
7339 }
7340 const CXToken &getTok(unsigned Idx) const {
7341 assert(Idx < NumTokens);
7342 return Tokens[Idx];
7343 }
7344
Guy Benyei11169dd2012-12-18 14:30:41 +00007345 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007346 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007347 }
7348
7349 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7350 // The third field is reserved and currently not used. Use it here
7351 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007352 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007353 }
7354};
7355
7356} // end anonymous namespace
7357
7358static CXChildVisitResult
7359MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7360 CXClientData client_data) {
7361 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7362 parent);
7363}
7364
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007365/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007366/// \returns true if lexing was finished, false otherwise.
7367static bool lexNext(Lexer &Lex, Token &Tok,
7368 unsigned &NextIdx, unsigned NumTokens) {
7369 if (NextIdx >= NumTokens)
7370 return true;
7371
7372 ++NextIdx;
7373 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007374 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007375}
7376
Guy Benyei11169dd2012-12-18 14:30:41 +00007377static void annotatePreprocessorTokens(CXTranslationUnit TU,
7378 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007379 CXCursor *Cursors,
7380 CXToken *Tokens,
7381 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007382 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007383
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007384 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007385 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7386 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007387 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007388 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007389 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007390
7391 if (BeginLocInfo.first != EndLocInfo.first)
7392 return;
7393
7394 StringRef Buffer;
7395 bool Invalid = false;
7396 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7397 if (Buffer.empty() || Invalid)
7398 return;
7399
7400 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7401 CXXUnit->getASTContext().getLangOpts(),
7402 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7403 Buffer.end());
7404 Lex.SetCommentRetentionState(true);
7405
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007406 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007407 // Lex tokens in raw mode until we hit the end of the range, to avoid
7408 // entering #includes or expanding macros.
7409 while (true) {
7410 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007411 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7412 break;
7413 unsigned TokIdx = NextIdx-1;
7414 assert(Tok.getLocation() ==
7415 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007416
7417 reprocess:
7418 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007419 // We have found a preprocessing directive. Annotate the tokens
7420 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007421 //
7422 // FIXME: Some simple tests here could identify macro definitions and
7423 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007424
7425 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007426 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7427 break;
7428
Craig Topper69186e72014-06-08 08:38:04 +00007429 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007430 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007431 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7432 break;
7433
7434 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007435 IdentifierInfo &II =
7436 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007437 SourceLocation MappedTokLoc =
7438 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7439 MI = getMacroInfo(II, MappedTokLoc, TU);
7440 }
7441 }
7442
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007443 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007444 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007445 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7446 finished = true;
7447 break;
7448 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007449 // If we are in a macro definition, check if the token was ever a
7450 // macro name and annotate it if that's the case.
7451 if (MI) {
7452 SourceLocation SaveLoc = Tok.getLocation();
7453 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007454 MacroDefinitionRecord *MacroDef =
7455 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007456 Tok.setLocation(SaveLoc);
7457 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007458 Cursors[NextIdx - 1] =
7459 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007460 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007461 } while (!Tok.isAtStartOfLine());
7462
7463 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7464 assert(TokIdx <= LastIdx);
7465 SourceLocation EndLoc =
7466 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7467 CXCursor Cursor =
7468 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7469
7470 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007471 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007472
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007473 if (finished)
7474 break;
7475 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007476 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 }
7478}
7479
7480// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007481static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7482 CXToken *Tokens, unsigned NumTokens,
7483 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007484 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007485 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7486 setThreadBackgroundPriority();
7487
7488 // Determine the region of interest, which contains all of the tokens.
7489 SourceRange RegionOfInterest;
7490 RegionOfInterest.setBegin(
7491 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7492 RegionOfInterest.setEnd(
7493 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7494 Tokens[NumTokens-1])));
7495
Guy Benyei11169dd2012-12-18 14:30:41 +00007496 // Relex the tokens within the source range to look for preprocessing
7497 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007498 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007499
7500 // If begin location points inside a macro argument, set it to the expansion
7501 // location so we can have the full context when annotating semantically.
7502 {
7503 SourceManager &SM = CXXUnit->getSourceManager();
7504 SourceLocation Loc =
7505 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7506 if (Loc.isMacroID())
7507 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7508 }
7509
Guy Benyei11169dd2012-12-18 14:30:41 +00007510 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7511 // Search and mark tokens that are macro argument expansions.
7512 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7513 Tokens, NumTokens);
7514 CursorVisitor MacroArgMarker(TU,
7515 MarkMacroArgTokensVisitorDelegate, &Visitor,
7516 /*VisitPreprocessorLast=*/true,
7517 /*VisitIncludedEntities=*/false,
7518 RegionOfInterest);
7519 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7520 }
7521
7522 // Annotate all of the source locations in the region of interest that map to
7523 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007524 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007525
7526 // FIXME: We use a ridiculous stack size here because the data-recursion
7527 // algorithm uses a large stack frame than the non-data recursive version,
7528 // and AnnotationTokensWorker currently transforms the data-recursion
7529 // algorithm back into a traditional recursion by explicitly calling
7530 // VisitChildren(). We will need to remove this explicit recursive call.
7531 W.AnnotateTokens();
7532
7533 // If we ran into any entities that involve context-sensitive keywords,
7534 // take another pass through the tokens to mark them as such.
7535 if (W.hasContextSensitiveKeywords()) {
7536 for (unsigned I = 0; I != NumTokens; ++I) {
7537 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7538 continue;
7539
7540 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7541 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007542 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007543 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7544 if (Property->getPropertyAttributesAsWritten() != 0 &&
7545 llvm::StringSwitch<bool>(II->getName())
7546 .Case("readonly", true)
7547 .Case("assign", true)
7548 .Case("unsafe_unretained", true)
7549 .Case("readwrite", true)
7550 .Case("retain", true)
7551 .Case("copy", true)
7552 .Case("nonatomic", true)
7553 .Case("atomic", true)
7554 .Case("getter", true)
7555 .Case("setter", true)
7556 .Case("strong", true)
7557 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007558 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007559 .Default(false))
7560 Tokens[I].int_data[0] = CXToken_Keyword;
7561 }
7562 continue;
7563 }
7564
7565 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7566 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7567 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7568 if (llvm::StringSwitch<bool>(II->getName())
7569 .Case("in", true)
7570 .Case("out", true)
7571 .Case("inout", true)
7572 .Case("oneway", true)
7573 .Case("bycopy", true)
7574 .Case("byref", true)
7575 .Default(false))
7576 Tokens[I].int_data[0] = CXToken_Keyword;
7577 continue;
7578 }
7579
7580 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7581 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7582 Tokens[I].int_data[0] = CXToken_Keyword;
7583 continue;
7584 }
7585 }
7586 }
7587}
7588
Guy Benyei11169dd2012-12-18 14:30:41 +00007589void clang_annotateTokens(CXTranslationUnit TU,
7590 CXToken *Tokens, unsigned NumTokens,
7591 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007592 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007593 LOG_BAD_TU(TU);
7594 return;
7595 }
7596 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007597 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007598 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007599 }
7600
7601 LOG_FUNC_SECTION {
7602 *Log << TU << ' ';
7603 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7604 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7605 *Log << clang_getRange(bloc, eloc);
7606 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007607
7608 // Any token we don't specifically annotate will have a NULL cursor.
7609 CXCursor C = clang_getNullCursor();
7610 for (unsigned I = 0; I != NumTokens; ++I)
7611 Cursors[I] = C;
7612
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007613 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007614 if (!CXXUnit)
7615 return;
7616
7617 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007618
7619 auto AnnotateTokensImpl = [=]() {
7620 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7621 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007622 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007623 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007624 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7625 }
7626}
7627
Guy Benyei11169dd2012-12-18 14:30:41 +00007628//===----------------------------------------------------------------------===//
7629// Operations for querying linkage of a cursor.
7630//===----------------------------------------------------------------------===//
7631
Guy Benyei11169dd2012-12-18 14:30:41 +00007632CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7633 if (!clang_isDeclaration(cursor.kind))
7634 return CXLinkage_Invalid;
7635
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007636 const Decl *D = cxcursor::getCursorDecl(cursor);
7637 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007638 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007639 case NoLinkage:
7640 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007641 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007642 case InternalLinkage: return CXLinkage_Internal;
7643 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007644 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007645 case ExternalLinkage: return CXLinkage_External;
7646 };
7647
7648 return CXLinkage_Invalid;
7649}
Guy Benyei11169dd2012-12-18 14:30:41 +00007650
7651//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007652// Operations for querying visibility of a cursor.
7653//===----------------------------------------------------------------------===//
7654
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007655CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7656 if (!clang_isDeclaration(cursor.kind))
7657 return CXVisibility_Invalid;
7658
7659 const Decl *D = cxcursor::getCursorDecl(cursor);
7660 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7661 switch (ND->getVisibility()) {
7662 case HiddenVisibility: return CXVisibility_Hidden;
7663 case ProtectedVisibility: return CXVisibility_Protected;
7664 case DefaultVisibility: return CXVisibility_Default;
7665 };
7666
7667 return CXVisibility_Invalid;
7668}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007669
7670//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007671// Operations for querying language of a cursor.
7672//===----------------------------------------------------------------------===//
7673
7674static CXLanguageKind getDeclLanguage(const Decl *D) {
7675 if (!D)
7676 return CXLanguage_C;
7677
7678 switch (D->getKind()) {
7679 default:
7680 break;
7681 case Decl::ImplicitParam:
7682 case Decl::ObjCAtDefsField:
7683 case Decl::ObjCCategory:
7684 case Decl::ObjCCategoryImpl:
7685 case Decl::ObjCCompatibleAlias:
7686 case Decl::ObjCImplementation:
7687 case Decl::ObjCInterface:
7688 case Decl::ObjCIvar:
7689 case Decl::ObjCMethod:
7690 case Decl::ObjCProperty:
7691 case Decl::ObjCPropertyImpl:
7692 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007693 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007694 return CXLanguage_ObjC;
7695 case Decl::CXXConstructor:
7696 case Decl::CXXConversion:
7697 case Decl::CXXDestructor:
7698 case Decl::CXXMethod:
7699 case Decl::CXXRecord:
7700 case Decl::ClassTemplate:
7701 case Decl::ClassTemplatePartialSpecialization:
7702 case Decl::ClassTemplateSpecialization:
7703 case Decl::Friend:
7704 case Decl::FriendTemplate:
7705 case Decl::FunctionTemplate:
7706 case Decl::LinkageSpec:
7707 case Decl::Namespace:
7708 case Decl::NamespaceAlias:
7709 case Decl::NonTypeTemplateParm:
7710 case Decl::StaticAssert:
7711 case Decl::TemplateTemplateParm:
7712 case Decl::TemplateTypeParm:
7713 case Decl::UnresolvedUsingTypename:
7714 case Decl::UnresolvedUsingValue:
7715 case Decl::Using:
7716 case Decl::UsingDirective:
7717 case Decl::UsingShadow:
7718 return CXLanguage_CPlusPlus;
7719 }
7720
7721 return CXLanguage_C;
7722}
7723
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007724static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7725 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007726 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007727
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007728 switch (D->getAvailability()) {
7729 case AR_Available:
7730 case AR_NotYetIntroduced:
7731 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007732 return getCursorAvailabilityForDecl(
7733 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007734 return CXAvailability_Available;
7735
7736 case AR_Deprecated:
7737 return CXAvailability_Deprecated;
7738
7739 case AR_Unavailable:
7740 return CXAvailability_NotAvailable;
7741 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007742
7743 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007744}
7745
Guy Benyei11169dd2012-12-18 14:30:41 +00007746enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7747 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007748 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7749 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007750
7751 return CXAvailability_Available;
7752}
7753
7754static CXVersion convertVersion(VersionTuple In) {
7755 CXVersion Out = { -1, -1, -1 };
7756 if (In.empty())
7757 return Out;
7758
7759 Out.Major = In.getMajor();
7760
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007761 Optional<unsigned> Minor = In.getMinor();
7762 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007763 Out.Minor = *Minor;
7764 else
7765 return Out;
7766
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007767 Optional<unsigned> Subminor = In.getSubminor();
7768 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007769 Out.Subminor = *Subminor;
7770
7771 return Out;
7772}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007773
Alex Lorenz1345ea22017-06-12 19:06:30 +00007774static void getCursorPlatformAvailabilityForDecl(
7775 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7776 int *always_unavailable, CXString *unavailable_message,
7777 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007778 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007779 for (auto A : D->attrs()) {
7780 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007781 HadAvailAttr = true;
7782 if (always_deprecated)
7783 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007784 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007785 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007786 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007787 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007788 continue;
7789 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007790
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007791 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007792 HadAvailAttr = true;
7793 if (always_unavailable)
7794 *always_unavailable = 1;
7795 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007796 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007797 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7798 }
7799 continue;
7800 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007801
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007802 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007803 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007804 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007805 }
7806 }
7807
7808 if (!HadAvailAttr)
7809 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7810 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007811 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7812 deprecated_message, always_unavailable, unavailable_message,
7813 AvailabilityAttrs);
7814
7815 if (AvailabilityAttrs.empty())
7816 return;
7817
Fangrui Song55fab262018-09-26 22:16:28 +00007818 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007819 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7820 return LHS->getPlatform()->getName() <
7821 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007822 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007823 ASTContext &Ctx = D->getASTContext();
7824 auto It = std::unique(
7825 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7826 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7827 if (LHS->getPlatform() != RHS->getPlatform())
7828 return false;
7829
7830 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7831 LHS->getDeprecated() == RHS->getDeprecated() &&
7832 LHS->getObsoleted() == RHS->getObsoleted() &&
7833 LHS->getMessage() == RHS->getMessage() &&
7834 LHS->getReplacement() == RHS->getReplacement())
7835 return true;
7836
7837 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7838 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7839 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7840 return false;
7841
7842 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7843 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7844
7845 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7846 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7847 if (LHS->getMessage().empty())
7848 LHS->setMessage(Ctx, RHS->getMessage());
7849 if (LHS->getReplacement().empty())
7850 LHS->setReplacement(Ctx, RHS->getReplacement());
7851 }
7852
7853 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7854 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7855 if (LHS->getMessage().empty())
7856 LHS->setMessage(Ctx, RHS->getMessage());
7857 if (LHS->getReplacement().empty())
7858 LHS->setReplacement(Ctx, RHS->getReplacement());
7859 }
7860
7861 return true;
7862 });
7863 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007864}
7865
Alex Lorenz1345ea22017-06-12 19:06:30 +00007866int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007867 CXString *deprecated_message,
7868 int *always_unavailable,
7869 CXString *unavailable_message,
7870 CXPlatformAvailability *availability,
7871 int availability_size) {
7872 if (always_deprecated)
7873 *always_deprecated = 0;
7874 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007875 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 if (always_unavailable)
7877 *always_unavailable = 0;
7878 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007879 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007880
Guy Benyei11169dd2012-12-18 14:30:41 +00007881 if (!clang_isDeclaration(cursor.kind))
7882 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007883
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007884 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007885 if (!D)
7886 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007887
Alex Lorenz1345ea22017-06-12 19:06:30 +00007888 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7889 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7890 always_unavailable, unavailable_message,
7891 AvailabilityAttrs);
7892 for (const auto &Avail :
7893 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7894 .take_front(availability_size))) {
7895 availability[Avail.index()].Platform =
7896 cxstring::createDup(Avail.value()->getPlatform()->getName());
7897 availability[Avail.index()].Introduced =
7898 convertVersion(Avail.value()->getIntroduced());
7899 availability[Avail.index()].Deprecated =
7900 convertVersion(Avail.value()->getDeprecated());
7901 availability[Avail.index()].Obsoleted =
7902 convertVersion(Avail.value()->getObsoleted());
7903 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7904 availability[Avail.index()].Message =
7905 cxstring::createDup(Avail.value()->getMessage());
7906 }
7907
7908 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007909}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007910
Guy Benyei11169dd2012-12-18 14:30:41 +00007911void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7912 clang_disposeString(availability->Platform);
7913 clang_disposeString(availability->Message);
7914}
7915
7916CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7917 if (clang_isDeclaration(cursor.kind))
7918 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7919
7920 return CXLanguage_Invalid;
7921}
7922
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007923CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7924 const Decl *D = cxcursor::getCursorDecl(cursor);
7925 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7926 switch (VD->getTLSKind()) {
7927 case VarDecl::TLS_None:
7928 return CXTLS_None;
7929 case VarDecl::TLS_Dynamic:
7930 return CXTLS_Dynamic;
7931 case VarDecl::TLS_Static:
7932 return CXTLS_Static;
7933 }
7934 }
7935
7936 return CXTLS_None;
7937}
7938
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007939 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007940 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007941 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007942static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007943 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007944 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007945
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007946 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007947 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7948 return FunTmpl;
7949
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007950 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007951 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7952 return ClassTmpl;
7953
7954 return D;
7955}
7956
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007957
7958enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7959 StorageClass sc = SC_None;
7960 const Decl *D = getCursorDecl(C);
7961 if (D) {
7962 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7963 sc = FD->getStorageClass();
7964 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7965 sc = VD->getStorageClass();
7966 } else {
7967 return CX_SC_Invalid;
7968 }
7969 } else {
7970 return CX_SC_Invalid;
7971 }
7972 switch (sc) {
7973 case SC_None:
7974 return CX_SC_None;
7975 case SC_Extern:
7976 return CX_SC_Extern;
7977 case SC_Static:
7978 return CX_SC_Static;
7979 case SC_PrivateExtern:
7980 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007981 case SC_Auto:
7982 return CX_SC_Auto;
7983 case SC_Register:
7984 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007985 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007986 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007987}
7988
Guy Benyei11169dd2012-12-18 14:30:41 +00007989CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7990 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007991 if (const Decl *D = getCursorDecl(cursor)) {
7992 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007993 if (!DC)
7994 return clang_getNullCursor();
7995
7996 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7997 getCursorTU(cursor));
7998 }
7999 }
8000
8001 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008002 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008003 return MakeCXCursor(D, getCursorTU(cursor));
8004 }
8005
8006 return clang_getNullCursor();
8007}
8008
8009CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8010 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008011 if (const Decl *D = getCursorDecl(cursor)) {
8012 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 if (!DC)
8014 return clang_getNullCursor();
8015
8016 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8017 getCursorTU(cursor));
8018 }
8019 }
8020
8021 // FIXME: Note that we can't easily compute the lexical context of a
8022 // statement or expression, so we return nothing.
8023 return clang_getNullCursor();
8024}
8025
8026CXFile clang_getIncludedFile(CXCursor cursor) {
8027 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008028 return nullptr;
8029
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008030 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008031 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008032}
8033
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008034unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8035 if (C.kind != CXCursor_ObjCPropertyDecl)
8036 return CXObjCPropertyAttr_noattr;
8037
8038 unsigned Result = CXObjCPropertyAttr_noattr;
8039 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8040 ObjCPropertyDecl::PropertyAttributeKind Attr =
8041 PD->getPropertyAttributesAsWritten();
8042
8043#define SET_CXOBJCPROP_ATTR(A) \
8044 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8045 Result |= CXObjCPropertyAttr_##A
8046 SET_CXOBJCPROP_ATTR(readonly);
8047 SET_CXOBJCPROP_ATTR(getter);
8048 SET_CXOBJCPROP_ATTR(assign);
8049 SET_CXOBJCPROP_ATTR(readwrite);
8050 SET_CXOBJCPROP_ATTR(retain);
8051 SET_CXOBJCPROP_ATTR(copy);
8052 SET_CXOBJCPROP_ATTR(nonatomic);
8053 SET_CXOBJCPROP_ATTR(setter);
8054 SET_CXOBJCPROP_ATTR(atomic);
8055 SET_CXOBJCPROP_ATTR(weak);
8056 SET_CXOBJCPROP_ATTR(strong);
8057 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008058 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008059#undef SET_CXOBJCPROP_ATTR
8060
8061 return Result;
8062}
8063
Michael Wu6e88f532018-08-03 05:38:29 +00008064CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8065 if (C.kind != CXCursor_ObjCPropertyDecl)
8066 return cxstring::createNull();
8067
8068 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8069 Selector sel = PD->getGetterName();
8070 if (sel.isNull())
8071 return cxstring::createNull();
8072
8073 return cxstring::createDup(sel.getAsString());
8074}
8075
8076CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8077 if (C.kind != CXCursor_ObjCPropertyDecl)
8078 return cxstring::createNull();
8079
8080 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8081 Selector sel = PD->getSetterName();
8082 if (sel.isNull())
8083 return cxstring::createNull();
8084
8085 return cxstring::createDup(sel.getAsString());
8086}
8087
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008088unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8089 if (!clang_isDeclaration(C.kind))
8090 return CXObjCDeclQualifier_None;
8091
8092 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8093 const Decl *D = getCursorDecl(C);
8094 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8095 QT = MD->getObjCDeclQualifier();
8096 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8097 QT = PD->getObjCDeclQualifier();
8098 if (QT == Decl::OBJC_TQ_None)
8099 return CXObjCDeclQualifier_None;
8100
8101 unsigned Result = CXObjCDeclQualifier_None;
8102 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8103 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8104 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8105 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8106 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8107 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8108
8109 return Result;
8110}
8111
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008112unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8113 if (!clang_isDeclaration(C.kind))
8114 return 0;
8115
8116 const Decl *D = getCursorDecl(C);
8117 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8118 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8119 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8120 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8121
8122 return 0;
8123}
8124
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008125unsigned clang_Cursor_isVariadic(CXCursor C) {
8126 if (!clang_isDeclaration(C.kind))
8127 return 0;
8128
8129 const Decl *D = getCursorDecl(C);
8130 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8131 return FD->isVariadic();
8132 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8133 return MD->isVariadic();
8134
8135 return 0;
8136}
8137
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008138unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8139 CXString *language, CXString *definedIn,
8140 unsigned *isGenerated) {
8141 if (!clang_isDeclaration(C.kind))
8142 return 0;
8143
8144 const Decl *D = getCursorDecl(C);
8145
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008146 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008147 if (language)
8148 *language = cxstring::createDup(attr->getLanguage());
8149 if (definedIn)
8150 *definedIn = cxstring::createDup(attr->getDefinedIn());
8151 if (isGenerated)
8152 *isGenerated = attr->getGeneratedDeclaration();
8153 return 1;
8154 }
8155 return 0;
8156}
8157
Guy Benyei11169dd2012-12-18 14:30:41 +00008158CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8159 if (!clang_isDeclaration(C.kind))
8160 return clang_getNullRange();
8161
8162 const Decl *D = getCursorDecl(C);
8163 ASTContext &Context = getCursorContext(C);
8164 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8165 if (!RC)
8166 return clang_getNullRange();
8167
8168 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8169}
8170
8171CXString clang_Cursor_getRawCommentText(CXCursor C) {
8172 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008173 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008174
8175 const Decl *D = getCursorDecl(C);
8176 ASTContext &Context = getCursorContext(C);
8177 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8178 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8179 StringRef();
8180
8181 // Don't duplicate the string because RawText points directly into source
8182 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008183 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008184}
8185
8186CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8187 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008188 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008189
8190 const Decl *D = getCursorDecl(C);
8191 const ASTContext &Context = getCursorContext(C);
8192 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8193
8194 if (RC) {
8195 StringRef BriefText = RC->getBriefText(Context);
8196
8197 // Don't duplicate the string because RawComment ensures that this memory
8198 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008199 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008200 }
8201
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008202 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008203}
8204
Guy Benyei11169dd2012-12-18 14:30:41 +00008205CXModule clang_Cursor_getModule(CXCursor C) {
8206 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008207 if (const ImportDecl *ImportD =
8208 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 return ImportD->getImportedModule();
8210 }
8211
Craig Topper69186e72014-06-08 08:38:04 +00008212 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008213}
8214
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008215CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8216 if (isNotUsableTU(TU)) {
8217 LOG_BAD_TU(TU);
8218 return nullptr;
8219 }
8220 if (!File)
8221 return nullptr;
8222 FileEntry *FE = static_cast<FileEntry *>(File);
8223
8224 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8225 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8226 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8227
Richard Smithfeb54b62014-10-23 02:01:19 +00008228 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008229}
8230
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008231CXFile clang_Module_getASTFile(CXModule CXMod) {
8232 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008233 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008234 Module *Mod = static_cast<Module*>(CXMod);
8235 return const_cast<FileEntry *>(Mod->getASTFile());
8236}
8237
Guy Benyei11169dd2012-12-18 14:30:41 +00008238CXModule clang_Module_getParent(CXModule CXMod) {
8239 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008240 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008241 Module *Mod = static_cast<Module*>(CXMod);
8242 return Mod->Parent;
8243}
8244
8245CXString clang_Module_getName(CXModule CXMod) {
8246 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008247 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008248 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008249 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008250}
8251
8252CXString clang_Module_getFullName(CXModule CXMod) {
8253 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008254 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008255 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008256 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008257}
8258
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008259int clang_Module_isSystem(CXModule CXMod) {
8260 if (!CXMod)
8261 return 0;
8262 Module *Mod = static_cast<Module*>(CXMod);
8263 return Mod->IsSystem;
8264}
8265
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008266unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8267 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008268 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008269 LOG_BAD_TU(TU);
8270 return 0;
8271 }
8272 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008273 return 0;
8274 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008275 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8276 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8277 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008278}
8279
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008280CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8281 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008282 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008283 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008284 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008285 }
8286 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008287 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008288 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008289 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008290
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008291 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8292 if (Index < TopHeaders.size())
8293 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008294
Craig Topper69186e72014-06-08 08:38:04 +00008295 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008296}
8297
Guy Benyei11169dd2012-12-18 14:30:41 +00008298//===----------------------------------------------------------------------===//
8299// C++ AST instrospection.
8300//===----------------------------------------------------------------------===//
8301
Jonathan Coe29565352016-04-27 12:48:25 +00008302unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8303 if (!clang_isDeclaration(C.kind))
8304 return 0;
8305
8306 const Decl *D = cxcursor::getCursorDecl(C);
8307 const CXXConstructorDecl *Constructor =
8308 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8309 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8310}
8311
8312unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8313 if (!clang_isDeclaration(C.kind))
8314 return 0;
8315
8316 const Decl *D = cxcursor::getCursorDecl(C);
8317 const CXXConstructorDecl *Constructor =
8318 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8319 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8320}
8321
8322unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8323 if (!clang_isDeclaration(C.kind))
8324 return 0;
8325
8326 const Decl *D = cxcursor::getCursorDecl(C);
8327 const CXXConstructorDecl *Constructor =
8328 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8329 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8330}
8331
8332unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8333 if (!clang_isDeclaration(C.kind))
8334 return 0;
8335
8336 const Decl *D = cxcursor::getCursorDecl(C);
8337 const CXXConstructorDecl *Constructor =
8338 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8339 // Passing 'false' excludes constructors marked 'explicit'.
8340 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8341}
8342
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008343unsigned clang_CXXField_isMutable(CXCursor C) {
8344 if (!clang_isDeclaration(C.kind))
8345 return 0;
8346
8347 if (const auto D = cxcursor::getCursorDecl(C))
8348 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8349 return FD->isMutable() ? 1 : 0;
8350 return 0;
8351}
8352
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008353unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8354 if (!clang_isDeclaration(C.kind))
8355 return 0;
8356
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008357 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008358 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008359 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008360 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8361}
8362
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008363unsigned clang_CXXMethod_isConst(CXCursor C) {
8364 if (!clang_isDeclaration(C.kind))
8365 return 0;
8366
8367 const Decl *D = cxcursor::getCursorDecl(C);
8368 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008369 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008370 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
8371}
8372
Jonathan Coe29565352016-04-27 12:48:25 +00008373unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8374 if (!clang_isDeclaration(C.kind))
8375 return 0;
8376
8377 const Decl *D = cxcursor::getCursorDecl(C);
8378 const CXXMethodDecl *Method =
8379 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8380 return (Method && Method->isDefaulted()) ? 1 : 0;
8381}
8382
Guy Benyei11169dd2012-12-18 14:30:41 +00008383unsigned clang_CXXMethod_isStatic(CXCursor C) {
8384 if (!clang_isDeclaration(C.kind))
8385 return 0;
8386
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008387 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008388 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008389 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008390 return (Method && Method->isStatic()) ? 1 : 0;
8391}
8392
8393unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8394 if (!clang_isDeclaration(C.kind))
8395 return 0;
8396
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008397 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008398 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008399 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008400 return (Method && Method->isVirtual()) ? 1 : 0;
8401}
Guy Benyei11169dd2012-12-18 14:30:41 +00008402
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008403unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8404 if (!clang_isDeclaration(C.kind))
8405 return 0;
8406
8407 const auto *D = cxcursor::getCursorDecl(C);
8408 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8409 if (RD)
8410 RD = RD->getDefinition();
8411 return (RD && RD->isAbstract()) ? 1 : 0;
8412}
8413
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008414unsigned clang_EnumDecl_isScoped(CXCursor C) {
8415 if (!clang_isDeclaration(C.kind))
8416 return 0;
8417
8418 const Decl *D = cxcursor::getCursorDecl(C);
8419 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8420 return (Enum && Enum->isScoped()) ? 1 : 0;
8421}
8422
Guy Benyei11169dd2012-12-18 14:30:41 +00008423//===----------------------------------------------------------------------===//
8424// Attribute introspection.
8425//===----------------------------------------------------------------------===//
8426
Guy Benyei11169dd2012-12-18 14:30:41 +00008427CXType clang_getIBOutletCollectionType(CXCursor C) {
8428 if (C.kind != CXCursor_IBOutletCollectionAttr)
8429 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8430
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008431 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008432 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8433
8434 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8435}
Guy Benyei11169dd2012-12-18 14:30:41 +00008436
8437//===----------------------------------------------------------------------===//
8438// Inspecting memory usage.
8439//===----------------------------------------------------------------------===//
8440
8441typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8442
8443static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8444 enum CXTUResourceUsageKind k,
8445 unsigned long amount) {
8446 CXTUResourceUsageEntry entry = { k, amount };
8447 entries.push_back(entry);
8448}
8449
Guy Benyei11169dd2012-12-18 14:30:41 +00008450const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8451 const char *str = "";
8452 switch (kind) {
8453 case CXTUResourceUsage_AST:
8454 str = "ASTContext: expressions, declarations, and types";
8455 break;
8456 case CXTUResourceUsage_Identifiers:
8457 str = "ASTContext: identifiers";
8458 break;
8459 case CXTUResourceUsage_Selectors:
8460 str = "ASTContext: selectors";
8461 break;
8462 case CXTUResourceUsage_GlobalCompletionResults:
8463 str = "Code completion: cached global results";
8464 break;
8465 case CXTUResourceUsage_SourceManagerContentCache:
8466 str = "SourceManager: content cache allocator";
8467 break;
8468 case CXTUResourceUsage_AST_SideTables:
8469 str = "ASTContext: side tables";
8470 break;
8471 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8472 str = "SourceManager: malloc'ed memory buffers";
8473 break;
8474 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8475 str = "SourceManager: mmap'ed memory buffers";
8476 break;
8477 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8478 str = "ExternalASTSource: malloc'ed memory buffers";
8479 break;
8480 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8481 str = "ExternalASTSource: mmap'ed memory buffers";
8482 break;
8483 case CXTUResourceUsage_Preprocessor:
8484 str = "Preprocessor: malloc'ed memory";
8485 break;
8486 case CXTUResourceUsage_PreprocessingRecord:
8487 str = "Preprocessor: PreprocessingRecord";
8488 break;
8489 case CXTUResourceUsage_SourceManager_DataStructures:
8490 str = "SourceManager: data structures and tables";
8491 break;
8492 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8493 str = "Preprocessor: header search tables";
8494 break;
8495 }
8496 return str;
8497}
8498
8499CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008500 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008501 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008502 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008503 return usage;
8504 }
8505
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008506 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008507 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008508 ASTContext &astContext = astUnit->getASTContext();
8509
8510 // How much memory is used by AST nodes and types?
8511 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8512 (unsigned long) astContext.getASTAllocatedMemory());
8513
8514 // How much memory is used by identifiers?
8515 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8516 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8517
8518 // How much memory is used for selectors?
8519 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8520 (unsigned long) astContext.Selectors.getTotalMemory());
8521
8522 // How much memory is used by ASTContext's side tables?
8523 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8524 (unsigned long) astContext.getSideTableAllocatedMemory());
8525
8526 // How much memory is used for caching global code completion results?
8527 unsigned long completionBytes = 0;
8528 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008529 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008530 completionBytes = completionAllocator->getTotalMemory();
8531 }
8532 createCXTUResourceUsageEntry(*entries,
8533 CXTUResourceUsage_GlobalCompletionResults,
8534 completionBytes);
8535
8536 // How much memory is being used by SourceManager's content cache?
8537 createCXTUResourceUsageEntry(*entries,
8538 CXTUResourceUsage_SourceManagerContentCache,
8539 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8540
8541 // How much memory is being used by the MemoryBuffer's in SourceManager?
8542 const SourceManager::MemoryBufferSizes &srcBufs =
8543 astUnit->getSourceManager().getMemoryBufferSizes();
8544
8545 createCXTUResourceUsageEntry(*entries,
8546 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8547 (unsigned long) srcBufs.malloc_bytes);
8548 createCXTUResourceUsageEntry(*entries,
8549 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8550 (unsigned long) srcBufs.mmap_bytes);
8551 createCXTUResourceUsageEntry(*entries,
8552 CXTUResourceUsage_SourceManager_DataStructures,
8553 (unsigned long) astContext.getSourceManager()
8554 .getDataStructureSizes());
8555
8556 // How much memory is being used by the ExternalASTSource?
8557 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8558 const ExternalASTSource::MemoryBufferSizes &sizes =
8559 esrc->getMemoryBufferSizes();
8560
8561 createCXTUResourceUsageEntry(*entries,
8562 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8563 (unsigned long) sizes.malloc_bytes);
8564 createCXTUResourceUsageEntry(*entries,
8565 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8566 (unsigned long) sizes.mmap_bytes);
8567 }
8568
8569 // How much memory is being used by the Preprocessor?
8570 Preprocessor &pp = astUnit->getPreprocessor();
8571 createCXTUResourceUsageEntry(*entries,
8572 CXTUResourceUsage_Preprocessor,
8573 pp.getTotalMemory());
8574
8575 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8576 createCXTUResourceUsageEntry(*entries,
8577 CXTUResourceUsage_PreprocessingRecord,
8578 pRec->getTotalMemory());
8579 }
8580
8581 createCXTUResourceUsageEntry(*entries,
8582 CXTUResourceUsage_Preprocessor_HeaderSearch,
8583 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008584
Guy Benyei11169dd2012-12-18 14:30:41 +00008585 CXTUResourceUsage usage = { (void*) entries.get(),
8586 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008587 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008588 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008589 return usage;
8590}
8591
8592void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8593 if (usage.data)
8594 delete (MemUsageEntries*) usage.data;
8595}
8596
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008597CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8598 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008599 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008600 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008601
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008602 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008603 LOG_BAD_TU(TU);
8604 return skipped;
8605 }
8606
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008607 if (!file)
8608 return skipped;
8609
8610 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8611 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8612 if (!ppRec)
8613 return skipped;
8614
8615 ASTContext &Ctx = astUnit->getASTContext();
8616 SourceManager &sm = Ctx.getSourceManager();
8617 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8618 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008619 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008620
8621 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8622 std::vector<SourceRange> wantedRanges;
8623 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8624 i != ei; ++i) {
8625 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8626 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008627 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8628 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008629 }
8630
8631 skipped->count = wantedRanges.size();
8632 skipped->ranges = new CXSourceRange[skipped->count];
8633 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8634 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8635
8636 return skipped;
8637}
8638
Cameron Desrochersd8091282016-08-18 15:43:55 +00008639CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8640 CXSourceRangeList *skipped = new CXSourceRangeList;
8641 skipped->count = 0;
8642 skipped->ranges = nullptr;
8643
8644 if (isNotUsableTU(TU)) {
8645 LOG_BAD_TU(TU);
8646 return skipped;
8647 }
8648
8649 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8650 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8651 if (!ppRec)
8652 return skipped;
8653
8654 ASTContext &Ctx = astUnit->getASTContext();
8655
8656 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8657
8658 skipped->count = SkippedRanges.size();
8659 skipped->ranges = new CXSourceRange[skipped->count];
8660 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8661 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8662
8663 return skipped;
8664}
8665
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008666void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8667 if (ranges) {
8668 delete[] ranges->ranges;
8669 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008670 }
8671}
8672
Guy Benyei11169dd2012-12-18 14:30:41 +00008673void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8674 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8675 for (unsigned I = 0; I != Usage.numEntries; ++I)
8676 fprintf(stderr, " %s: %lu\n",
8677 clang_getTUResourceUsageName(Usage.entries[I].kind),
8678 Usage.entries[I].amount);
8679
8680 clang_disposeCXTUResourceUsage(Usage);
8681}
8682
8683//===----------------------------------------------------------------------===//
8684// Misc. utility functions.
8685//===----------------------------------------------------------------------===//
8686
Richard Smith0a7b2972018-07-03 21:34:13 +00008687/// Default to using our desired 8 MB stack size on "safety" threads.
8688static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008689
8690namespace clang {
8691
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008692bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008693 unsigned Size) {
8694 if (!Size)
8695 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008696 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008697 return CRC.RunSafelyOnThread(Fn, Size);
8698 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008699}
8700
8701unsigned GetSafetyThreadStackSize() {
8702 return SafetyStackThreadSize;
8703}
8704
8705void SetSafetyThreadStackSize(unsigned Value) {
8706 SafetyStackThreadSize = Value;
8707}
8708
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008709}
Guy Benyei11169dd2012-12-18 14:30:41 +00008710
8711void clang::setThreadBackgroundPriority() {
8712 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8713 return;
8714
Alp Toker1a86ad22014-07-06 06:24:00 +00008715#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008716 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8717#endif
8718}
8719
8720void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8721 if (!Unit)
8722 return;
8723
8724 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8725 DEnd = Unit->stored_diag_end();
8726 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008727 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008728 CXString Msg = clang_formatDiagnostic(&Diag,
8729 clang_defaultDiagnosticDisplayOptions());
8730 fprintf(stderr, "%s\n", clang_getCString(Msg));
8731 clang_disposeString(Msg);
8732 }
Nico Weber1865df42018-04-27 19:11:14 +00008733#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008734 // On Windows, force a flush, since there may be multiple copies of
8735 // stderr and stdout in the file system, all with different buffers
8736 // but writing to the same device.
8737 fflush(stderr);
8738#endif
8739}
8740
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008741MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8742 SourceLocation MacroDefLoc,
8743 CXTranslationUnit TU){
8744 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008745 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008746 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008747 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008748
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008749 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008750 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008751 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008752 if (MD) {
8753 for (MacroDirective::DefInfo
8754 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8755 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8756 return Def.getMacroInfo();
8757 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008758 }
8759
Craig Topper69186e72014-06-08 08:38:04 +00008760 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008761}
8762
Richard Smith66a81862015-05-04 02:25:31 +00008763const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008764 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008765 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008766 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008767 const IdentifierInfo *II = MacroDef->getName();
8768 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008769 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008770
8771 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8772}
8773
Richard Smith66a81862015-05-04 02:25:31 +00008774MacroDefinitionRecord *
8775cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8776 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008777 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008778 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008779 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008780 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008781
8782 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008783 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008784 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8785 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008786 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008787
8788 // Check that the token is inside the definition and not its argument list.
8789 SourceManager &SM = Unit->getSourceManager();
8790 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008791 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008792 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008793 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008794
8795 Preprocessor &PP = Unit->getPreprocessor();
8796 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8797 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008798 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008799
Alp Toker2d57cea2014-05-17 04:53:25 +00008800 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008801 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008802 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008803
8804 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008805 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008806 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008807
Richard Smith20e883e2015-04-29 23:20:19 +00008808 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008809 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008810 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008811
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008812 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008813}
8814
Richard Smith66a81862015-05-04 02:25:31 +00008815MacroDefinitionRecord *
8816cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8817 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008818 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008819 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008820
8821 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008822 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008823 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008824 Preprocessor &PP = Unit->getPreprocessor();
8825 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008826 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008827 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8828 Token Tok;
8829 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008830 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008831
8832 return checkForMacroInMacroDefinition(MI, Tok, TU);
8833}
8834
Guy Benyei11169dd2012-12-18 14:30:41 +00008835CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008836 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008837}
8838
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008839Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8840 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008841 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008842 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008843 if (Unit->isMainFileAST())
8844 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008845 return *this;
8846 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008847 } else {
8848 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008849 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008850 return *this;
8851}
8852
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008853Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8854 *this << FE->getName();
8855 return *this;
8856}
8857
8858Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8859 CXString cursorName = clang_getCursorDisplayName(cursor);
8860 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8861 clang_disposeString(cursorName);
8862 return *this;
8863}
8864
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008865Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8866 CXFile File;
8867 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008868 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008869 CXString FileName = clang_getFileName(File);
8870 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8871 clang_disposeString(FileName);
8872 return *this;
8873}
8874
8875Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8876 CXSourceLocation BLoc = clang_getRangeStart(range);
8877 CXSourceLocation ELoc = clang_getRangeEnd(range);
8878
8879 CXFile BFile;
8880 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008881 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008882
8883 CXFile EFile;
8884 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008885 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008886
8887 CXString BFileName = clang_getFileName(BFile);
8888 if (BFile == EFile) {
8889 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8890 BLine, BColumn, ELine, EColumn);
8891 } else {
8892 CXString EFileName = clang_getFileName(EFile);
8893 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8894 BLine, BColumn)
8895 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8896 ELine, EColumn);
8897 clang_disposeString(EFileName);
8898 }
8899 clang_disposeString(BFileName);
8900 return *this;
8901}
8902
8903Logger &cxindex::Logger::operator<<(CXString Str) {
8904 *this << clang_getCString(Str);
8905 return *this;
8906}
8907
8908Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8909 LogOS << Fmt;
8910 return *this;
8911}
8912
Chandler Carruth37ad2582014-06-27 15:14:39 +00008913static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8914
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008915cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008916 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008917
8918 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8919
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008920 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008921 OS << "[libclang:" << Name << ':';
8922
Alp Toker1a86ad22014-07-06 06:24:00 +00008923#ifdef USE_DARWIN_THREADS
8924 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008925 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8926 OS << tid << ':';
8927#endif
8928
8929 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8930 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008931 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008932
8933 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008934 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008935 OS << "--------------------------------------------------\n";
8936 }
8937}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008938
8939#ifdef CLANG_TOOL_EXTRA_BUILD
8940// This anchor is used to force the linker to link the clang-tidy plugin.
8941extern volatile int ClangTidyPluginAnchorSource;
8942static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8943 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008944
8945// This anchor is used to force the linker to link the clang-include-fixer
8946// plugin.
8947extern volatile int ClangIncludeFixerPluginAnchorSource;
8948static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8949 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008950#endif