blob: 15b2df84935e4052e7aa4d39f3e9064246efcc46 [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"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000034#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000035#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000043#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000046#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000047#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/Program.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000053#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/Threading.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000057
Alp Toker1a86ad22014-07-06 06:24:00 +000058#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59#define USE_DARWIN_THREADS
60#endif
61
62#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000063#include <pthread.h>
64#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000065
66using namespace clang;
67using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000068using namespace clang::cxtu;
69using namespace clang::cxindex;
70
David Blaikieea4395e2017-01-06 19:49:01 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
72 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000073 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000074 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000075 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000076 CXTranslationUnit D = new CXTranslationUnitImpl();
77 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000078 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000079 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000080 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000081 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000082 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000083 D->ParsingOptions = 0;
84 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000085 return D;
86}
87
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000088bool cxtu::isASTReadError(ASTUnit *AU) {
89 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
90 DEnd = AU->stored_diag_end();
91 D != DEnd; ++D) {
92 if (D->getLevel() >= DiagnosticsEngine::Error &&
93 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
94 diag::DiagCat_AST_Deserialization_Issue)
95 return true;
96 }
97 return false;
98}
99
Guy Benyei11169dd2012-12-18 14:30:41 +0000100cxtu::CXTUOwner::~CXTUOwner() {
101 if (TU)
102 clang_disposeTranslationUnit(TU);
103}
104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000105/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000106/// the translation unit.
107static RangeComparisonResult RangeCompare(SourceManager &SM,
108 SourceRange R1,
109 SourceRange R2) {
110 assert(R1.isValid() && "First range is invalid?");
111 assert(R2.isValid() && "Second range is invalid?");
112 if (R1.getEnd() != R2.getBegin() &&
113 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
114 return RangeBefore;
115 if (R2.getEnd() != R1.getBegin() &&
116 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
117 return RangeAfter;
118 return RangeOverlap;
119}
120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000121/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000122/// a given source range.
123static RangeComparisonResult LocationCompare(SourceManager &SM,
124 SourceLocation L, SourceRange R) {
125 assert(R.isValid() && "First range is invalid?");
126 assert(L.isValid() && "Second range is invalid?");
127 if (L == R.getBegin() || L == R.getEnd())
128 return RangeOverlap;
129 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
130 return RangeBefore;
131 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
132 return RangeAfter;
133 return RangeOverlap;
134}
135
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000136/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000137///
138/// Clang internally represents ranges where the end location points to the
139/// start of the token at the end. However, for external clients it is more
140/// useful to have a CXSourceRange be a proper half-open interval. This routine
141/// does the appropriate translation.
142CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
143 const LangOptions &LangOpts,
144 const CharSourceRange &R) {
145 // We want the last character in this location, so we will adjust the
146 // location accordingly.
147 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000148 bool IsTokenRange = R.isTokenRange();
149 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
150 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
151 EndLoc = Expansion.getEnd();
152 IsTokenRange = Expansion.isTokenRange();
153 }
154 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000155 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
156 SM, LangOpts);
157 EndLoc = EndLoc.getLocWithOffset(Length);
158 }
159
Bill Wendlingeade3622013-01-23 08:25:41 +0000160 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000161 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000162 R.getBegin().getRawEncoding(),
163 EndLoc.getRawEncoding()
164 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000165 return Result;
166}
167
168//===----------------------------------------------------------------------===//
169// Cursor visitor.
170//===----------------------------------------------------------------------===//
171
172static SourceRange getRawCursorExtent(CXCursor C);
173static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
174
175
176RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
177 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
178}
179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000180/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000181/// its children.
182///
183/// \param Cursor the cursor to visit.
184///
185/// \param CheckedRegionOfInterest if true, then the caller already checked
186/// that this cursor is within the region of interest.
187///
188/// \returns true if the visitation should be aborted, false if it
189/// should continue.
190bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
191 if (clang_isInvalid(Cursor.kind))
192 return false;
193
194 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000195 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000196 if (!D) {
197 assert(0 && "Invalid declaration cursor");
198 return true; // abort.
199 }
200
201 // Ignore implicit declarations, unless it's an objc method because
202 // currently we should report implicit methods for properties when indexing.
203 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
204 return false;
205 }
206
207 // If we have a range of interest, and this cursor doesn't intersect with it,
208 // we're done.
209 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
210 SourceRange Range = getRawCursorExtent(Cursor);
211 if (Range.isInvalid() || CompareRegionOfInterest(Range))
212 return false;
213 }
214
215 switch (Visitor(Cursor, Parent, ClientData)) {
216 case CXChildVisit_Break:
217 return true;
218
219 case CXChildVisit_Continue:
220 return false;
221
222 case CXChildVisit_Recurse: {
223 bool ret = VisitChildren(Cursor);
224 if (PostChildrenVisitor)
225 if (PostChildrenVisitor(Cursor, ClientData))
226 return true;
227 return ret;
228 }
229 }
230
231 llvm_unreachable("Invalid CXChildVisitResult!");
232}
233
234static bool visitPreprocessedEntitiesInRange(SourceRange R,
235 PreprocessingRecord &PPRec,
236 CursorVisitor &Visitor) {
237 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
238 FileID FID;
239
240 if (!Visitor.shouldVisitIncludedEntities()) {
241 // If the begin/end of the range lie in the same FileID, do the optimization
242 // where we skip preprocessed entities that do not come from the same FileID.
243 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
244 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
245 FID = FileID();
246 }
247
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000248 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
249 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000250 PPRec, FID);
251}
252
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000253bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000254 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000255 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000256
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000257 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000258 SourceManager &SM = Unit->getSourceManager();
259
260 std::pair<FileID, unsigned>
261 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
262 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
263
264 if (End.first != Begin.first) {
265 // If the end does not reside in the same file, try to recover by
266 // picking the end of the file of begin location.
267 End.first = Begin.first;
268 End.second = SM.getFileIDSize(Begin.first);
269 }
270
271 assert(Begin.first == End.first);
272 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000273 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000274
275 FileID File = Begin.first;
276 unsigned Offset = Begin.second;
277 unsigned Length = End.second - Begin.second;
278
279 if (!VisitDeclsOnly && !VisitPreprocessorLast)
280 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000281 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000282
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000283 if (visitDeclsFromFileRegion(File, Offset, Length))
284 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000285
286 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000287 return visitPreprocessedEntitiesInRegion();
288
289 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000290}
291
292static bool isInLexicalContext(Decl *D, DeclContext *DC) {
293 if (!DC)
294 return false;
295
296 for (DeclContext *DeclDC = D->getLexicalDeclContext();
297 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
298 if (DeclDC == DC)
299 return true;
300 }
301 return false;
302}
303
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000304bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000305 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000306 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000307 SourceManager &SM = Unit->getSourceManager();
308 SourceRange Range = RegionOfInterest;
309
310 SmallVector<Decl *, 16> Decls;
311 Unit->findFileRegionDecls(File, Offset, Length, Decls);
312
313 // If we didn't find any file level decls for the file, try looking at the
314 // file that it was included from.
315 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
316 bool Invalid = false;
317 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
318 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000319 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000320
321 SourceLocation Outer;
322 if (SLEntry.isFile())
323 Outer = SLEntry.getFile().getIncludeLoc();
324 else
325 Outer = SLEntry.getExpansion().getExpansionLocStart();
326 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000327 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000328
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000329 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000330 Length = 0;
331 Unit->findFileRegionDecls(File, Offset, Length, Decls);
332 }
333
334 assert(!Decls.empty());
335
336 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000337 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000338 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
339 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000340 Decl *D = *DIt;
341 if (D->getSourceRange().isInvalid())
342 continue;
343
344 if (isInLexicalContext(D, CurDC))
345 continue;
346
347 CurDC = dyn_cast<DeclContext>(D);
348
349 if (TagDecl *TD = dyn_cast<TagDecl>(D))
350 if (!TD->isFreeStanding())
351 continue;
352
353 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
354 if (CompRes == RangeBefore)
355 continue;
356 if (CompRes == RangeAfter)
357 break;
358
359 assert(CompRes == RangeOverlap);
360 VisitedAtLeastOnce = true;
361
362 if (isa<ObjCContainerDecl>(D)) {
363 FileDI_current = &DIt;
364 FileDE_current = DE;
365 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000366 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000367 }
368
369 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000370 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000371 }
372
373 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000374 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000375
376 // No Decls overlapped with the range. Move up the lexical context until there
377 // is a context that contains the range or we reach the translation unit
378 // level.
379 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
380 : (*(DIt-1))->getLexicalDeclContext();
381
382 while (DC && !DC->isTranslationUnit()) {
383 Decl *D = cast<Decl>(DC);
384 SourceRange CurDeclRange = D->getSourceRange();
385 if (CurDeclRange.isInvalid())
386 break;
387
388 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000389 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
390 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000391 }
392
393 DC = D->getLexicalDeclContext();
394 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000395
396 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000397}
398
399bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
400 if (!AU->getPreprocessor().getPreprocessingRecord())
401 return false;
402
403 PreprocessingRecord &PPRec
404 = *AU->getPreprocessor().getPreprocessingRecord();
405 SourceManager &SM = AU->getSourceManager();
406
407 if (RegionOfInterest.isValid()) {
408 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
409 SourceLocation B = MappedRange.getBegin();
410 SourceLocation E = MappedRange.getEnd();
411
412 if (AU->isInPreambleFileID(B)) {
413 if (SM.isLoadedSourceLocation(E))
414 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
415 PPRec, *this);
416
417 // Beginning of range lies in the preamble but it also extends beyond
418 // it into the main file. Split the range into 2 parts, one covering
419 // the preamble and another covering the main file. This allows subsequent
420 // calls to visitPreprocessedEntitiesInRange to accept a source range that
421 // lies in the same FileID, allowing it to skip preprocessed entities that
422 // do not come from the same FileID.
423 bool breaked =
424 visitPreprocessedEntitiesInRange(
425 SourceRange(B, AU->getEndOfPreambleFileID()),
426 PPRec, *this);
427 if (breaked) return true;
428 return visitPreprocessedEntitiesInRange(
429 SourceRange(AU->getStartOfMainFileID(), E),
430 PPRec, *this);
431 }
432
433 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
434 }
435
436 bool OnlyLocalDecls
437 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
438
439 if (OnlyLocalDecls)
440 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
441 PPRec);
442
443 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
444}
445
446template<typename InputIterator>
447bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
448 InputIterator Last,
449 PreprocessingRecord &PPRec,
450 FileID FID) {
451 for (; First != Last; ++First) {
452 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
453 continue;
454
455 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000456 if (!PPE)
457 continue;
458
Guy Benyei11169dd2012-12-18 14:30:41 +0000459 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
460 if (Visit(MakeMacroExpansionCursor(ME, TU)))
461 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000462
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 continue;
464 }
Richard Smith66a81862015-05-04 02:25:31 +0000465
466 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000467 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
468 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000469
Guy Benyei11169dd2012-12-18 14:30:41 +0000470 continue;
471 }
472
473 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
474 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
475 return true;
476
477 continue;
478 }
479 }
480
481 return false;
482}
483
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000484/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000485///
486/// \returns true if the visitation should be aborted, false if it
487/// should continue.
488bool CursorVisitor::VisitChildren(CXCursor Cursor) {
489 if (clang_isReference(Cursor.kind) &&
490 Cursor.kind != CXCursor_CXXBaseSpecifier) {
491 // By definition, references have no children.
492 return false;
493 }
494
495 // Set the Parent field to Cursor, then back to its old value once we're
496 // done.
497 SetParentRAII SetParent(Parent, StmtParent, Cursor);
498
499 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000500 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000501 if (!D)
502 return false;
503
504 return VisitAttributes(D) || Visit(D);
505 }
506
507 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000508 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 return Visit(S);
510
511 return false;
512 }
513
514 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000515 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000516 return Visit(E);
517
518 return false;
519 }
520
521 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000522 CXTranslationUnit TU = getCursorTU(Cursor);
523 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000524
525 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
526 for (unsigned I = 0; I != 2; ++I) {
527 if (VisitOrder[I]) {
528 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
529 RegionOfInterest.isInvalid()) {
530 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
531 TLEnd = CXXUnit->top_level_end();
532 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000533 const Optional<bool> V = handleDeclForVisitation(*TL);
534 if (!V.hasValue())
535 continue;
536 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000537 }
538 } else if (VisitDeclContext(
539 CXXUnit->getASTContext().getTranslationUnitDecl()))
540 return true;
541 continue;
542 }
543
544 // Walk the preprocessing record.
545 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
546 visitPreprocessedEntitiesInRegion();
547 }
548
549 return false;
550 }
551
552 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000553 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000554 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
555 return Visit(BaseTSInfo->getTypeLoc());
556 }
557 }
558 }
559
560 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000561 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000562 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000563 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000564 return Visit(cxcursor::MakeCursorObjCClassRef(
565 ObjT->getInterface(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000566 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 }
568
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000569 // If pointing inside a macro definition, check if the token is an identifier
570 // that was ever defined as a macro. In such a case, create a "pseudo" macro
571 // expansion cursor for that token.
572 SourceLocation BeginLoc = RegionOfInterest.getBegin();
573 if (Cursor.kind == CXCursor_MacroDefinition &&
574 BeginLoc == RegionOfInterest.getEnd()) {
575 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000576 const MacroInfo *MI =
577 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000578 if (MacroDefinitionRecord *MacroDef =
579 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000580 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
581 }
582
Guy Benyei11169dd2012-12-18 14:30:41 +0000583 // Nothing to visit at the moment.
584 return false;
585}
586
587bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
588 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
589 if (Visit(TSInfo->getTypeLoc()))
590 return true;
591
592 if (Stmt *Body = B->getBody())
593 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
594
595 return false;
596}
597
Ted Kremenek03325582013-02-21 01:29:01 +0000598Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 if (RegionOfInterest.isValid()) {
600 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
601 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000602 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000603
604 switch (CompareRegionOfInterest(Range)) {
605 case RangeBefore:
606 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000607 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000608
609 case RangeAfter:
610 // This declaration comes after the region of interest; we're done.
611 return false;
612
613 case RangeOverlap:
614 // This declaration overlaps the region of interest; visit it.
615 break;
616 }
617 }
618 return true;
619}
620
621bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
622 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
623
624 // FIXME: Eventually remove. This part of a hack to support proper
625 // iteration over all Decls contained lexically within an ObjC container.
626 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
627 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
628
629 for ( ; I != E; ++I) {
630 Decl *D = *I;
631 if (D->getLexicalDeclContext() != DC)
632 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000633 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000634 if (!V.hasValue())
635 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000636 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 }
638 return false;
639}
640
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000641Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
642 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
643
644 // Ignore synthesized ivars here, otherwise if we have something like:
645 // @synthesize prop = _prop;
646 // and '_prop' is not declared, we will encounter a '_prop' ivar before
647 // encountering the 'prop' synthesize declaration and we will think that
648 // we passed the region-of-interest.
649 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
650 if (ivarD->getSynthesize())
651 return None;
652 }
653
654 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
655 // declarations is a mismatch with the compiler semantics.
656 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
657 auto *ID = cast<ObjCInterfaceDecl>(D);
658 if (!ID->isThisDeclarationADefinition())
659 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
660
661 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
662 auto *PD = cast<ObjCProtocolDecl>(D);
663 if (!PD->isThisDeclarationADefinition())
664 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
665 }
666
667 const Optional<bool> V = shouldVisitCursor(Cursor);
668 if (!V.hasValue())
669 return None;
670 if (!V.getValue())
671 return false;
672 if (Visit(Cursor, true))
673 return true;
674 return None;
675}
676
Guy Benyei11169dd2012-12-18 14:30:41 +0000677bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
678 llvm_unreachable("Translation units are visited directly by Visit()");
679}
680
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000681bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
682 if (VisitTemplateParameters(D->getTemplateParameters()))
683 return true;
684
685 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
686}
687
Guy Benyei11169dd2012-12-18 14:30:41 +0000688bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
689 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
690 return Visit(TSInfo->getTypeLoc());
691
692 return false;
693}
694
695bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
696 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
697 return Visit(TSInfo->getTypeLoc());
698
699 return false;
700}
701
702bool CursorVisitor::VisitTagDecl(TagDecl *D) {
703 return VisitDeclContext(D);
704}
705
706bool CursorVisitor::VisitClassTemplateSpecializationDecl(
707 ClassTemplateSpecializationDecl *D) {
708 bool ShouldVisitBody = false;
709 switch (D->getSpecializationKind()) {
710 case TSK_Undeclared:
711 case TSK_ImplicitInstantiation:
712 // Nothing to visit
713 return false;
714
715 case TSK_ExplicitInstantiationDeclaration:
716 case TSK_ExplicitInstantiationDefinition:
717 break;
718
719 case TSK_ExplicitSpecialization:
720 ShouldVisitBody = true;
721 break;
722 }
723
724 // Visit the template arguments used in the specialization.
725 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
726 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000727 if (TemplateSpecializationTypeLoc TSTLoc =
728 TL.getAs<TemplateSpecializationTypeLoc>()) {
729 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
730 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000731 return true;
732 }
733 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000734
735 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000736}
737
738bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
739 ClassTemplatePartialSpecializationDecl *D) {
740 // FIXME: Visit the "outer" template parameter lists on the TagDecl
741 // before visiting these template parameters.
742 if (VisitTemplateParameters(D->getTemplateParameters()))
743 return true;
744
745 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000746 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
747 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
748 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
750 return true;
751
752 return VisitCXXRecordDecl(D);
753}
754
755bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
756 // Visit the default argument.
757 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
758 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
759 if (Visit(DefArg->getTypeLoc()))
760 return true;
761
762 return false;
763}
764
765bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
766 if (Expr *Init = D->getInitExpr())
767 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
768 return false;
769}
770
771bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000772 unsigned NumParamList = DD->getNumTemplateParameterLists();
773 for (unsigned i = 0; i < NumParamList; i++) {
774 TemplateParameterList* Params = DD->getTemplateParameterList(i);
775 if (VisitTemplateParameters(Params))
776 return true;
777 }
778
Guy Benyei11169dd2012-12-18 14:30:41 +0000779 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
780 if (Visit(TSInfo->getTypeLoc()))
781 return true;
782
783 // Visit the nested-name-specifier, if present.
784 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
785 if (VisitNestedNameSpecifierLoc(QualifierLoc))
786 return true;
787
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000788 return false;
789}
790
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000791static bool HasTrailingReturnType(FunctionDecl *ND) {
792 const QualType Ty = ND->getType();
793 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
794 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
795 return FT->hasTrailingReturn();
796 }
797
798 return false;
799}
800
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000801/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000802static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
803 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000804 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
805}
806
Guy Benyei11169dd2012-12-18 14:30:41 +0000807bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000808 unsigned NumParamList = ND->getNumTemplateParameterLists();
809 for (unsigned i = 0; i < NumParamList; i++) {
810 TemplateParameterList* Params = ND->getTemplateParameterList(i);
811 if (VisitTemplateParameters(Params))
812 return true;
813 }
814
Guy Benyei11169dd2012-12-18 14:30:41 +0000815 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
816 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000817 // written. This requires a bit of work.
818 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
819 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000820 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000821
822 // If we have a function declared directly (without the use of a typedef),
823 // visit just the return type. Otherwise, just visit the function's type
824 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000825 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
826 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000827 (!FTL && Visit(TL)))
828 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000829
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000830 // Visit the nested-name-specifier, if present.
831 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
832 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000833 return true;
834
835 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000836 if (!isa<CXXDestructorDecl>(ND))
837 if (VisitDeclarationNameInfo(ND->getNameInfo()))
838 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000839
840 // FIXME: Visit explicitly-specified template arguments!
841
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000842 // Visit the function parameters, if we have a function type.
843 if (FTL && VisitFunctionTypeLoc(FTL, true))
844 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000845
846 // Visit the function's trailing return type.
847 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
848 return true;
849
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000850 // FIXME: Attributes?
851 }
852
Guy Benyei11169dd2012-12-18 14:30:41 +0000853 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
854 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
855 // Find the initializers that were written in the source.
856 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000857 for (auto *I : Constructor->inits()) {
858 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000859 continue;
860
Aaron Ballman0ad78302014-03-13 17:34:31 +0000861 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000862 }
863
864 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000865 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
866 &CompareCXXCtorInitializers);
867
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 // Visit the initializers in source order
869 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
870 CXXCtorInitializer *Init = WrittenInits[I];
871 if (Init->isAnyMemberInitializer()) {
872 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
873 Init->getMemberLocation(), TU)))
874 return true;
875 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
876 if (Visit(TInfo->getTypeLoc()))
877 return true;
878 }
879
880 // Visit the initializer value.
881 if (Expr *Initializer = Init->getInit())
882 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
883 return true;
884 }
885 }
886
887 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
888 return true;
889 }
890
891 return false;
892}
893
894bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
895 if (VisitDeclaratorDecl(D))
896 return true;
897
898 if (Expr *BitWidth = D->getBitWidth())
899 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
900
Benjamin Kramer99f97592017-11-15 12:20:41 +0000901 if (Expr *Init = D->getInClassInitializer())
902 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
903
Guy Benyei11169dd2012-12-18 14:30:41 +0000904 return false;
905}
906
907bool CursorVisitor::VisitVarDecl(VarDecl *D) {
908 if (VisitDeclaratorDecl(D))
909 return true;
910
911 if (Expr *Init = D->getInit())
912 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
913
914 return false;
915}
916
917bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
918 if (VisitDeclaratorDecl(D))
919 return true;
920
921 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
922 if (Expr *DefArg = D->getDefaultArgument())
923 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
924
925 return false;
926}
927
928bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
929 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
930 // before visiting these template parameters.
931 if (VisitTemplateParameters(D->getTemplateParameters()))
932 return true;
933
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000934 auto* FD = D->getTemplatedDecl();
935 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000936}
937
938bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
939 // FIXME: Visit the "outer" template parameter lists on the TagDecl
940 // before visiting these template parameters.
941 if (VisitTemplateParameters(D->getTemplateParameters()))
942 return true;
943
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000944 auto* CD = D->getTemplatedDecl();
945 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000946}
947
948bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
949 if (VisitTemplateParameters(D->getTemplateParameters()))
950 return true;
951
952 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
953 VisitTemplateArgumentLoc(D->getDefaultArgument()))
954 return true;
955
956 return false;
957}
958
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000959bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
960 // Visit the bound, if it's explicit.
961 if (D->hasExplicitBound()) {
962 if (auto TInfo = D->getTypeSourceInfo()) {
963 if (Visit(TInfo->getTypeLoc()))
964 return true;
965 }
966 }
967
968 return false;
969}
970
Guy Benyei11169dd2012-12-18 14:30:41 +0000971bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000972 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 if (Visit(TSInfo->getTypeLoc()))
974 return true;
975
David Majnemer59f77922016-06-24 04:05:48 +0000976 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000977 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 return true;
979 }
980
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000981 return ND->isThisDeclarationADefinition() &&
982 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000983}
984
985template <typename DeclIt>
986static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
987 SourceManager &SM, SourceLocation EndLoc,
988 SmallVectorImpl<Decl *> &Decls) {
989 DeclIt next = *DI_current;
990 while (++next != DE_current) {
991 Decl *D_next = *next;
992 if (!D_next)
993 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000994 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 if (!L.isValid())
996 break;
997 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
998 *DI_current = next;
999 Decls.push_back(D_next);
1000 continue;
1001 }
1002 break;
1003 }
1004}
1005
Guy Benyei11169dd2012-12-18 14:30:41 +00001006bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1007 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1008 // an @implementation can lexically contain Decls that are not properly
1009 // nested in the AST. When we identify such cases, we need to retrofit
1010 // this nesting here.
1011 if (!DI_current && !FileDI_current)
1012 return VisitDeclContext(D);
1013
1014 // Scan the Decls that immediately come after the container
1015 // in the current DeclContext. If any fall within the
1016 // container's lexical region, stash them into a vector
1017 // for later processing.
1018 SmallVector<Decl *, 24> DeclsInContainer;
1019 SourceLocation EndLoc = D->getSourceRange().getEnd();
1020 SourceManager &SM = AU->getSourceManager();
1021 if (EndLoc.isValid()) {
1022 if (DI_current) {
1023 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1024 DeclsInContainer);
1025 } else {
1026 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1027 DeclsInContainer);
1028 }
1029 }
1030
1031 // The common case.
1032 if (DeclsInContainer.empty())
1033 return VisitDeclContext(D);
1034
1035 // Get all the Decls in the DeclContext, and sort them with the
1036 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001037 for (auto *SubDecl : D->decls()) {
1038 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001039 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001040 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001041 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001042 }
1043
1044 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001045 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001046 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001047 SourceLocation L_A = A->getBeginLoc();
1048 SourceLocation L_B = B->getBeginLoc();
1049 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001050 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1051 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001052 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001053
1054 // Now visit the decls.
1055 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1056 E = DeclsInContainer.end(); I != E; ++I) {
1057 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001058 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001059 if (!V.hasValue())
1060 continue;
1061 if (!V.getValue())
1062 return false;
1063 if (Visit(Cursor, true))
1064 return true;
1065 }
1066 return false;
1067}
1068
1069bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1070 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1071 TU)))
1072 return true;
1073
Douglas Gregore9d95f12015-07-07 03:57:35 +00001074 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1075 return true;
1076
Guy Benyei11169dd2012-12-18 14:30:41 +00001077 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1078 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1079 E = ND->protocol_end(); I != E; ++I, ++PL)
1080 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1081 return true;
1082
1083 return VisitObjCContainerDecl(ND);
1084}
1085
1086bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1087 if (!PID->isThisDeclarationADefinition())
1088 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1089
1090 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1091 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1092 E = PID->protocol_end(); I != E; ++I, ++PL)
1093 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1094 return true;
1095
1096 return VisitObjCContainerDecl(PID);
1097}
1098
1099bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1100 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1101 return true;
1102
1103 // FIXME: This implements a workaround with @property declarations also being
1104 // installed in the DeclContext for the @interface. Eventually this code
1105 // should be removed.
1106 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1107 if (!CDecl || !CDecl->IsClassExtension())
1108 return false;
1109
1110 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1111 if (!ID)
1112 return false;
1113
1114 IdentifierInfo *PropertyId = PD->getIdentifier();
1115 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001116 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1117 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001118
1119 if (!prevDecl)
1120 return false;
1121
1122 // Visit synthesized methods since they will be skipped when visiting
1123 // the @interface.
1124 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1125 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1126 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1127 return true;
1128
1129 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1130 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1131 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1132 return true;
1133
1134 return false;
1135}
1136
Douglas Gregore9d95f12015-07-07 03:57:35 +00001137bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1138 if (!typeParamList)
1139 return false;
1140
1141 for (auto *typeParam : *typeParamList) {
1142 // Visit the type parameter.
1143 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1144 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001145 }
1146
1147 return false;
1148}
1149
Guy Benyei11169dd2012-12-18 14:30:41 +00001150bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1151 if (!D->isThisDeclarationADefinition()) {
1152 // Forward declaration is treated like a reference.
1153 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1154 }
1155
Douglas Gregore9d95f12015-07-07 03:57:35 +00001156 // Objective-C type parameters.
1157 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1158 return true;
1159
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 // Issue callbacks for super class.
1161 if (D->getSuperClass() &&
1162 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1163 D->getSuperClassLoc(),
1164 TU)))
1165 return true;
1166
Douglas Gregore9d95f12015-07-07 03:57:35 +00001167 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1168 if (Visit(SuperClassTInfo->getTypeLoc()))
1169 return true;
1170
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1172 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1173 E = D->protocol_end(); I != E; ++I, ++PL)
1174 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1175 return true;
1176
1177 return VisitObjCContainerDecl(D);
1178}
1179
1180bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1181 return VisitObjCContainerDecl(D);
1182}
1183
1184bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1185 // 'ID' could be null when dealing with invalid code.
1186 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1187 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1188 return true;
1189
1190 return VisitObjCImplDecl(D);
1191}
1192
1193bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1194#if 0
1195 // Issue callbacks for super class.
1196 // FIXME: No source location information!
1197 if (D->getSuperClass() &&
1198 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1199 D->getSuperClassLoc(),
1200 TU)))
1201 return true;
1202#endif
1203
1204 return VisitObjCImplDecl(D);
1205}
1206
1207bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1208 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1209 if (PD->isIvarNameSpecified())
1210 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1211
1212 return false;
1213}
1214
1215bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1216 return VisitDeclContext(D);
1217}
1218
1219bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1220 // Visit nested-name-specifier.
1221 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1222 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1223 return true;
1224
1225 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1226 D->getTargetNameLoc(), TU));
1227}
1228
1229bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1230 // Visit nested-name-specifier.
1231 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1232 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1233 return true;
1234 }
1235
1236 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1237 return true;
1238
1239 return VisitDeclarationNameInfo(D->getNameInfo());
1240}
1241
1242bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1243 // Visit nested-name-specifier.
1244 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1245 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1246 return true;
1247
1248 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1249 D->getIdentLocation(), TU));
1250}
1251
1252bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1253 // Visit nested-name-specifier.
1254 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1255 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1256 return true;
1257 }
1258
1259 return VisitDeclarationNameInfo(D->getNameInfo());
1260}
1261
1262bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1263 UnresolvedUsingTypenameDecl *D) {
1264 // Visit nested-name-specifier.
1265 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1266 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1267 return true;
1268
1269 return false;
1270}
1271
Olivier Goffart81978012016-06-09 16:15:55 +00001272bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1273 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1274 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001275 if (StringLiteral *Message = D->getMessage())
1276 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1277 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001278 return false;
1279}
1280
Olivier Goffartd211c642016-11-04 06:29:27 +00001281bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1282 if (NamedDecl *FriendD = D->getFriendDecl()) {
1283 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1284 return true;
1285 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1286 if (Visit(TI->getTypeLoc()))
1287 return true;
1288 }
1289 return false;
1290}
1291
Guy Benyei11169dd2012-12-18 14:30:41 +00001292bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1293 switch (Name.getName().getNameKind()) {
1294 case clang::DeclarationName::Identifier:
1295 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001296 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 case clang::DeclarationName::CXXOperatorName:
1298 case clang::DeclarationName::CXXUsingDirective:
1299 return false;
Richard Smith35845152017-02-07 01:37:30 +00001300
Guy Benyei11169dd2012-12-18 14:30:41 +00001301 case clang::DeclarationName::CXXConstructorName:
1302 case clang::DeclarationName::CXXDestructorName:
1303 case clang::DeclarationName::CXXConversionFunctionName:
1304 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1305 return Visit(TSInfo->getTypeLoc());
1306 return false;
1307
1308 case clang::DeclarationName::ObjCZeroArgSelector:
1309 case clang::DeclarationName::ObjCOneArgSelector:
1310 case clang::DeclarationName::ObjCMultiArgSelector:
1311 // FIXME: Per-identifier location info?
1312 return false;
1313 }
1314
1315 llvm_unreachable("Invalid DeclarationName::Kind!");
1316}
1317
1318bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1319 SourceRange Range) {
1320 // FIXME: This whole routine is a hack to work around the lack of proper
1321 // source information in nested-name-specifiers (PR5791). Since we do have
1322 // a beginning source location, we can visit the first component of the
1323 // nested-name-specifier, if it's a single-token component.
1324 if (!NNS)
1325 return false;
1326
1327 // Get the first component in the nested-name-specifier.
1328 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1329 NNS = Prefix;
1330
1331 switch (NNS->getKind()) {
1332 case NestedNameSpecifier::Namespace:
1333 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1334 TU));
1335
1336 case NestedNameSpecifier::NamespaceAlias:
1337 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1338 Range.getBegin(), TU));
1339
1340 case NestedNameSpecifier::TypeSpec: {
1341 // If the type has a form where we know that the beginning of the source
1342 // range matches up with a reference cursor. Visit the appropriate reference
1343 // cursor.
1344 const Type *T = NNS->getAsType();
1345 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1346 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1347 if (const TagType *Tag = dyn_cast<TagType>(T))
1348 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1349 if (const TemplateSpecializationType *TST
1350 = dyn_cast<TemplateSpecializationType>(T))
1351 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1352 break;
1353 }
1354
1355 case NestedNameSpecifier::TypeSpecWithTemplate:
1356 case NestedNameSpecifier::Global:
1357 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001358 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 break;
1360 }
1361
1362 return false;
1363}
1364
1365bool
1366CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1367 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1368 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1369 Qualifiers.push_back(Qualifier);
1370
1371 while (!Qualifiers.empty()) {
1372 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1373 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1374 switch (NNS->getKind()) {
1375 case NestedNameSpecifier::Namespace:
1376 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1377 Q.getLocalBeginLoc(),
1378 TU)))
1379 return true;
1380
1381 break;
1382
1383 case NestedNameSpecifier::NamespaceAlias:
1384 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1385 Q.getLocalBeginLoc(),
1386 TU)))
1387 return true;
1388
1389 break;
1390
1391 case NestedNameSpecifier::TypeSpec:
1392 case NestedNameSpecifier::TypeSpecWithTemplate:
1393 if (Visit(Q.getTypeLoc()))
1394 return true;
1395
1396 break;
1397
1398 case NestedNameSpecifier::Global:
1399 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001400 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001401 break;
1402 }
1403 }
1404
1405 return false;
1406}
1407
1408bool CursorVisitor::VisitTemplateParameters(
1409 const TemplateParameterList *Params) {
1410 if (!Params)
1411 return false;
1412
1413 for (TemplateParameterList::const_iterator P = Params->begin(),
1414 PEnd = Params->end();
1415 P != PEnd; ++P) {
1416 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1417 return true;
1418 }
1419
1420 return false;
1421}
1422
1423bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1424 switch (Name.getKind()) {
1425 case TemplateName::Template:
1426 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1427
1428 case TemplateName::OverloadedTemplate:
1429 // Visit the overloaded template set.
1430 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1431 return true;
1432
1433 return false;
1434
1435 case TemplateName::DependentTemplate:
1436 // FIXME: Visit nested-name-specifier.
1437 return false;
1438
1439 case TemplateName::QualifiedTemplate:
1440 // FIXME: Visit nested-name-specifier.
1441 return Visit(MakeCursorTemplateRef(
1442 Name.getAsQualifiedTemplateName()->getDecl(),
1443 Loc, TU));
1444
1445 case TemplateName::SubstTemplateTemplateParm:
1446 return Visit(MakeCursorTemplateRef(
1447 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1448 Loc, TU));
1449
1450 case TemplateName::SubstTemplateTemplateParmPack:
1451 return Visit(MakeCursorTemplateRef(
1452 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1453 Loc, TU));
1454 }
1455
1456 llvm_unreachable("Invalid TemplateName::Kind!");
1457}
1458
1459bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1460 switch (TAL.getArgument().getKind()) {
1461 case TemplateArgument::Null:
1462 case TemplateArgument::Integral:
1463 case TemplateArgument::Pack:
1464 return false;
1465
1466 case TemplateArgument::Type:
1467 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1468 return Visit(TSInfo->getTypeLoc());
1469 return false;
1470
1471 case TemplateArgument::Declaration:
1472 if (Expr *E = TAL.getSourceDeclExpression())
1473 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1474 return false;
1475
1476 case TemplateArgument::NullPtr:
1477 if (Expr *E = TAL.getSourceNullPtrExpression())
1478 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1479 return false;
1480
1481 case TemplateArgument::Expression:
1482 if (Expr *E = TAL.getSourceExpression())
1483 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1484 return false;
1485
1486 case TemplateArgument::Template:
1487 case TemplateArgument::TemplateExpansion:
1488 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1489 return true;
1490
1491 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1492 TAL.getTemplateNameLoc());
1493 }
1494
1495 llvm_unreachable("Invalid TemplateArgument::Kind!");
1496}
1497
1498bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1499 return VisitDeclContext(D);
1500}
1501
1502bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1503 return Visit(TL.getUnqualifiedLoc());
1504}
1505
1506bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1507 ASTContext &Context = AU->getASTContext();
1508
1509 // Some builtin types (such as Objective-C's "id", "sel", and
1510 // "Class") have associated declarations. Create cursors for those.
1511 QualType VisitType;
1512 switch (TL.getTypePtr()->getKind()) {
1513
1514 case BuiltinType::Void:
1515 case BuiltinType::NullPtr:
1516 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001517#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1518 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001519#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001520#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1521 case BuiltinType::Id:
1522#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001523 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001524 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001525 case BuiltinType::OCLClkEvent:
1526 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001527 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001528#define BUILTIN_TYPE(Id, SingletonId)
1529#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1530#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1531#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1532#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1533#include "clang/AST/BuiltinTypes.def"
1534 break;
1535
1536 case BuiltinType::ObjCId:
1537 VisitType = Context.getObjCIdType();
1538 break;
1539
1540 case BuiltinType::ObjCClass:
1541 VisitType = Context.getObjCClassType();
1542 break;
1543
1544 case BuiltinType::ObjCSel:
1545 VisitType = Context.getObjCSelType();
1546 break;
1547 }
1548
1549 if (!VisitType.isNull()) {
1550 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1551 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1552 TU));
1553 }
1554
1555 return false;
1556}
1557
1558bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1559 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1560}
1561
1562bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1563 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1564}
1565
1566bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1567 if (TL.isDefinition())
1568 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1569
1570 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1571}
1572
1573bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1574 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1575}
1576
1577bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001578 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001579}
1580
Manman Rene6be26c2016-09-13 17:25:08 +00001581bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001582 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001583 return true;
1584 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1585 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1586 TU)))
1587 return true;
1588 }
1589
1590 return false;
1591}
1592
Guy Benyei11169dd2012-12-18 14:30:41 +00001593bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1594 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1595 return true;
1596
Douglas Gregore9d95f12015-07-07 03:57:35 +00001597 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1598 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1599 return true;
1600 }
1601
Guy Benyei11169dd2012-12-18 14:30:41 +00001602 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1603 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1604 TU)))
1605 return true;
1606 }
1607
1608 return false;
1609}
1610
1611bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1612 return Visit(TL.getPointeeLoc());
1613}
1614
1615bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1616 return Visit(TL.getInnerLoc());
1617}
1618
1619bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1620 return Visit(TL.getPointeeLoc());
1621}
1622
1623bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1624 return Visit(TL.getPointeeLoc());
1625}
1626
1627bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1628 return Visit(TL.getPointeeLoc());
1629}
1630
1631bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1632 return Visit(TL.getPointeeLoc());
1633}
1634
1635bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1636 return Visit(TL.getPointeeLoc());
1637}
1638
1639bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1640 return Visit(TL.getModifiedLoc());
1641}
1642
1643bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1644 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001645 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 return true;
1647
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001648 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1649 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1651 return true;
1652
1653 return false;
1654}
1655
1656bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1657 if (Visit(TL.getElementLoc()))
1658 return true;
1659
1660 if (Expr *Size = TL.getSizeExpr())
1661 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1662
1663 return false;
1664}
1665
Reid Kleckner8a365022013-06-24 17:51:48 +00001666bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1667 return Visit(TL.getOriginalLoc());
1668}
1669
Reid Kleckner0503a872013-12-05 01:23:43 +00001670bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1671 return Visit(TL.getOriginalLoc());
1672}
1673
Richard Smith600b5262017-01-26 20:40:47 +00001674bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1675 DeducedTemplateSpecializationTypeLoc TL) {
1676 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1677 TL.getTemplateNameLoc()))
1678 return true;
1679
1680 return false;
1681}
1682
Guy Benyei11169dd2012-12-18 14:30:41 +00001683bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1684 TemplateSpecializationTypeLoc TL) {
1685 // Visit the template name.
1686 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1687 TL.getTemplateNameLoc()))
1688 return true;
1689
1690 // Visit the template arguments.
1691 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1692 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1693 return true;
1694
1695 return false;
1696}
1697
1698bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1699 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1700}
1701
1702bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1703 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1704 return Visit(TSInfo->getTypeLoc());
1705
1706 return false;
1707}
1708
1709bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1710 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1711 return Visit(TSInfo->getTypeLoc());
1712
1713 return false;
1714}
1715
1716bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001717 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001718}
1719
1720bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1721 DependentTemplateSpecializationTypeLoc TL) {
1722 // Visit the nested-name-specifier, if there is one.
1723 if (TL.getQualifierLoc() &&
1724 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1725 return true;
1726
1727 // Visit the template arguments.
1728 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1729 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1730 return true;
1731
1732 return false;
1733}
1734
1735bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1736 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1737 return true;
1738
1739 return Visit(TL.getNamedTypeLoc());
1740}
1741
1742bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1743 return Visit(TL.getPatternLoc());
1744}
1745
1746bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1747 if (Expr *E = TL.getUnderlyingExpr())
1748 return Visit(MakeCXCursor(E, StmtParent, TU));
1749
1750 return false;
1751}
1752
1753bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1754 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1755}
1756
1757bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1758 return Visit(TL.getValueLoc());
1759}
1760
Xiuli Pan9c14e282016-01-09 12:53:17 +00001761bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1762 return Visit(TL.getValueLoc());
1763}
1764
Guy Benyei11169dd2012-12-18 14:30:41 +00001765#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1766bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1767 return Visit##PARENT##Loc(TL); \
1768}
1769
1770DEFAULT_TYPELOC_IMPL(Complex, Type)
1771DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1772DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1773DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1774DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001775DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001776DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001777DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1778DEFAULT_TYPELOC_IMPL(Vector, Type)
1779DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1780DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1781DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1782DEFAULT_TYPELOC_IMPL(Record, TagType)
1783DEFAULT_TYPELOC_IMPL(Enum, TagType)
1784DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1785DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1786DEFAULT_TYPELOC_IMPL(Auto, Type)
1787
1788bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1789 // Visit the nested-name-specifier, if present.
1790 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1791 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1792 return true;
1793
1794 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001795 for (const auto &I : D->bases()) {
1796 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001797 return true;
1798 }
1799 }
1800
1801 return VisitTagDecl(D);
1802}
1803
1804bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001805 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001806 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1807 !I->isImplicit()) &&
1808 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 return true;
1810
1811 return false;
1812}
1813
1814//===----------------------------------------------------------------------===//
1815// Data-recursive visitor methods.
1816//===----------------------------------------------------------------------===//
1817
1818namespace {
1819#define DEF_JOB(NAME, DATA, KIND)\
1820class NAME : public VisitorJob {\
1821public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001822 NAME(const DATA *d, CXCursor parent) : \
1823 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001824 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001825 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001826};
1827
1828DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1829DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1830DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1831DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001832DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1833DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1834DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1835#undef DEF_JOB
1836
James Y Knight04ec5bf2015-12-24 02:59:37 +00001837class ExplicitTemplateArgsVisit : public VisitorJob {
1838public:
1839 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1840 const TemplateArgumentLoc *End, CXCursor parent)
1841 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1842 End) {}
1843 static bool classof(const VisitorJob *VJ) {
1844 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1845 }
1846 const TemplateArgumentLoc *begin() const {
1847 return static_cast<const TemplateArgumentLoc *>(data[0]);
1848 }
1849 const TemplateArgumentLoc *end() {
1850 return static_cast<const TemplateArgumentLoc *>(data[1]);
1851 }
1852};
Guy Benyei11169dd2012-12-18 14:30:41 +00001853class DeclVisit : public VisitorJob {
1854public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001855 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001856 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001857 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001858 static bool classof(const VisitorJob *VJ) {
1859 return VJ->getKind() == DeclVisitKind;
1860 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001861 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001862 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001863};
1864class TypeLocVisit : public VisitorJob {
1865public:
1866 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1867 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1868 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1869
1870 static bool classof(const VisitorJob *VJ) {
1871 return VJ->getKind() == TypeLocVisitKind;
1872 }
1873
1874 TypeLoc get() const {
1875 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001876 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001877 }
1878};
1879
1880class LabelRefVisit : public VisitorJob {
1881public:
1882 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1883 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1884 labelLoc.getPtrEncoding()) {}
1885
1886 static bool classof(const VisitorJob *VJ) {
1887 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1888 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001889 const LabelDecl *get() const {
1890 return static_cast<const LabelDecl *>(data[0]);
1891 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001892 SourceLocation getLoc() const {
1893 return SourceLocation::getFromPtrEncoding(data[1]); }
1894};
1895
1896class NestedNameSpecifierLocVisit : public VisitorJob {
1897public:
1898 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1899 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1900 Qualifier.getNestedNameSpecifier(),
1901 Qualifier.getOpaqueData()) { }
1902
1903 static bool classof(const VisitorJob *VJ) {
1904 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1905 }
1906
1907 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001908 return NestedNameSpecifierLoc(
1909 const_cast<NestedNameSpecifier *>(
1910 static_cast<const NestedNameSpecifier *>(data[0])),
1911 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001912 }
1913};
1914
1915class DeclarationNameInfoVisit : public VisitorJob {
1916public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001917 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001918 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001919 static bool classof(const VisitorJob *VJ) {
1920 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1921 }
1922 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001923 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001924 switch (S->getStmtClass()) {
1925 default:
1926 llvm_unreachable("Unhandled Stmt");
1927 case clang::Stmt::MSDependentExistsStmtClass:
1928 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1929 case Stmt::CXXDependentScopeMemberExprClass:
1930 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1931 case Stmt::DependentScopeDeclRefExprClass:
1932 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001933 case Stmt::OMPCriticalDirectiveClass:
1934 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001935 }
1936 }
1937};
1938class MemberRefVisit : public VisitorJob {
1939public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001940 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001941 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1942 L.getPtrEncoding()) {}
1943 static bool classof(const VisitorJob *VJ) {
1944 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1945 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001946 const FieldDecl *get() const {
1947 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001948 }
1949 SourceLocation getLoc() const {
1950 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1951 }
1952};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001953class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001954 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001955 VisitorWorkList &WL;
1956 CXCursor Parent;
1957public:
1958 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1959 : WL(wl), Parent(parent) {}
1960
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001961 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1962 void VisitBlockExpr(const BlockExpr *B);
1963 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1964 void VisitCompoundStmt(const CompoundStmt *S);
1965 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1966 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1967 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1968 void VisitCXXNewExpr(const CXXNewExpr *E);
1969 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1970 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1971 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1972 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1973 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1974 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1975 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1976 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001977 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001978 void VisitDeclRefExpr(const DeclRefExpr *D);
1979 void VisitDeclStmt(const DeclStmt *S);
1980 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1981 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1982 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1983 void VisitForStmt(const ForStmt *FS);
1984 void VisitGotoStmt(const GotoStmt *GS);
1985 void VisitIfStmt(const IfStmt *If);
1986 void VisitInitListExpr(const InitListExpr *IE);
1987 void VisitMemberExpr(const MemberExpr *M);
1988 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1989 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1990 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1991 void VisitOverloadExpr(const OverloadExpr *E);
1992 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1993 void VisitStmt(const Stmt *S);
1994 void VisitSwitchStmt(const SwitchStmt *S);
1995 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001996 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1997 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1998 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1999 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2000 void VisitVAArgExpr(const VAArgExpr *E);
2001 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2002 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2003 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2004 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002005 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002006 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002007 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002008 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002009 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002010 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002011 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002012 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002013 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002014 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002015 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002016 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002017 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002018 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002019 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002020 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002021 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002022 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002023 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002024 void
2025 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002026 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002027 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002028 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002029 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002030 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002031 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002032 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002033 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002034 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002035 void
2036 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002037 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002038 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002039 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002040 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002041 void VisitOMPDistributeParallelForDirective(
2042 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002043 void VisitOMPDistributeParallelForSimdDirective(
2044 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002045 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002046 void VisitOMPTargetParallelForSimdDirective(
2047 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002048 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002049 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002050 void VisitOMPTeamsDistributeSimdDirective(
2051 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002052 void VisitOMPTeamsDistributeParallelForSimdDirective(
2053 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002054 void VisitOMPTeamsDistributeParallelForDirective(
2055 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002056 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002057 void VisitOMPTargetTeamsDistributeDirective(
2058 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002059 void VisitOMPTargetTeamsDistributeParallelForDirective(
2060 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002061 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2062 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002063 void VisitOMPTargetTeamsDistributeSimdDirective(
2064 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002065
Guy Benyei11169dd2012-12-18 14:30:41 +00002066private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002067 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002068 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002069 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2070 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002071 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2072 void AddStmt(const Stmt *S);
2073 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002074 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002075 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002076 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002077};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002078} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002079
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002080void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002081 // 'S' should always be non-null, since it comes from the
2082 // statement we are visiting.
2083 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2084}
2085
2086void
2087EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2088 if (Qualifier)
2089 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2090}
2091
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002092void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002093 if (S)
2094 WL.push_back(StmtVisit(S, Parent));
2095}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002096void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002097 if (D)
2098 WL.push_back(DeclVisit(D, Parent, isFirst));
2099}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002100void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2101 unsigned NumTemplateArgs) {
2102 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002103}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002104void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002105 if (D)
2106 WL.push_back(MemberRefVisit(D, L, Parent));
2107}
2108void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2109 if (TI)
2110 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2111 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002112void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002113 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002114 for (const Stmt *SubStmt : S->children()) {
2115 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002116 }
2117 if (size == WL.size())
2118 return;
2119 // Now reverse the entries we just added. This will match the DFS
2120 // ordering performed by the worklist.
2121 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2122 std::reverse(I, E);
2123}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002124namespace {
2125class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2126 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002127 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002128 template <typename T>
2129 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002130public:
2131 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2132#define OPENMP_CLAUSE(Name, Class) \
2133 void Visit##Class(const Class *C);
2134#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002135 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002136 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002137};
2138
Alexey Bataev3392d762016-02-16 11:18:12 +00002139void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2140 const OMPClauseWithPreInit *C) {
2141 Visitor->AddStmt(C->getPreInitStmt());
2142}
2143
Alexey Bataev005248a2016-02-25 05:25:57 +00002144void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2145 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002146 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002147 Visitor->AddStmt(C->getPostUpdateExpr());
2148}
2149
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002150void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002151 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002152 Visitor->AddStmt(C->getCondition());
2153}
2154
Alexey Bataev3778b602014-07-17 07:32:53 +00002155void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2156 Visitor->AddStmt(C->getCondition());
2157}
2158
Alexey Bataev568a8332014-03-06 06:15:19 +00002159void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002160 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002161 Visitor->AddStmt(C->getNumThreads());
2162}
2163
Alexey Bataev62c87d22014-03-21 04:51:18 +00002164void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2165 Visitor->AddStmt(C->getSafelen());
2166}
2167
Alexey Bataev66b15b52015-08-21 11:14:16 +00002168void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2169 Visitor->AddStmt(C->getSimdlen());
2170}
2171
Alexander Musman8bd31e62014-05-27 15:12:19 +00002172void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2173 Visitor->AddStmt(C->getNumForLoops());
2174}
2175
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002176void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002177
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002178void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2179
Alexey Bataev56dafe82014-06-20 07:16:17 +00002180void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002181 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002182 Visitor->AddStmt(C->getChunkSize());
2183}
2184
Alexey Bataev10e775f2015-07-30 11:36:16 +00002185void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2186 Visitor->AddStmt(C->getNumForLoops());
2187}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002188
Alexey Bataev236070f2014-06-20 11:19:47 +00002189void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2190
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002191void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2192
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002193void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2194
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002195void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2196
Alexey Bataevdea47612014-07-23 07:46:59 +00002197void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2198
Alexey Bataev67a4f222014-07-23 10:25:33 +00002199void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2200
Alexey Bataev459dec02014-07-24 06:46:57 +00002201void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2202
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002203void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2204
Alexey Bataev346265e2015-09-25 10:37:12 +00002205void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2206
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002207void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2208
Alexey Bataevb825de12015-12-07 10:51:44 +00002209void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2210
Kelvin Li1408f912018-09-26 04:28:39 +00002211void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2212 const OMPUnifiedAddressClause *) {}
2213
Patrick Lyster4a370b92018-10-01 13:47:43 +00002214void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2215 const OMPUnifiedSharedMemoryClause *) {}
2216
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002217void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2218 const OMPReverseOffloadClause *) {}
2219
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002220void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2221 const OMPDynamicAllocatorsClause *) {}
2222
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002223void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2224 const OMPAtomicDefaultMemOrderClause *) {}
2225
Michael Wonge710d542015-08-07 16:16:36 +00002226void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2227 Visitor->AddStmt(C->getDevice());
2228}
2229
Kelvin Li099bb8c2015-11-24 20:50:12 +00002230void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002231 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002232 Visitor->AddStmt(C->getNumTeams());
2233}
2234
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002235void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002236 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002237 Visitor->AddStmt(C->getThreadLimit());
2238}
2239
Alexey Bataeva0569352015-12-01 10:17:31 +00002240void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2241 Visitor->AddStmt(C->getPriority());
2242}
2243
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002244void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2245 Visitor->AddStmt(C->getGrainsize());
2246}
2247
Alexey Bataev382967a2015-12-08 12:06:20 +00002248void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2249 Visitor->AddStmt(C->getNumTasks());
2250}
2251
Alexey Bataev28c75412015-12-15 08:19:24 +00002252void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2253 Visitor->AddStmt(C->getHint());
2254}
2255
Alexey Bataev756c1962013-09-24 03:17:45 +00002256template<typename T>
2257void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002258 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002259 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002260 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002261}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002262
2263void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002264 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002265 for (const auto *E : C->private_copies()) {
2266 Visitor->AddStmt(E);
2267 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002268}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002269void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2270 const OMPFirstprivateClause *C) {
2271 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002272 VisitOMPClauseWithPreInit(C);
2273 for (const auto *E : C->private_copies()) {
2274 Visitor->AddStmt(E);
2275 }
2276 for (const auto *E : C->inits()) {
2277 Visitor->AddStmt(E);
2278 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002279}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002280void OMPClauseEnqueue::VisitOMPLastprivateClause(
2281 const OMPLastprivateClause *C) {
2282 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002283 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002284 for (auto *E : C->private_copies()) {
2285 Visitor->AddStmt(E);
2286 }
2287 for (auto *E : C->source_exprs()) {
2288 Visitor->AddStmt(E);
2289 }
2290 for (auto *E : C->destination_exprs()) {
2291 Visitor->AddStmt(E);
2292 }
2293 for (auto *E : C->assignment_ops()) {
2294 Visitor->AddStmt(E);
2295 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002296}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002297void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002298 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002299}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002300void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2301 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002302 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002303 for (auto *E : C->privates()) {
2304 Visitor->AddStmt(E);
2305 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002306 for (auto *E : C->lhs_exprs()) {
2307 Visitor->AddStmt(E);
2308 }
2309 for (auto *E : C->rhs_exprs()) {
2310 Visitor->AddStmt(E);
2311 }
2312 for (auto *E : C->reduction_ops()) {
2313 Visitor->AddStmt(E);
2314 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002315}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002316void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2317 const OMPTaskReductionClause *C) {
2318 VisitOMPClauseList(C);
2319 VisitOMPClauseWithPostUpdate(C);
2320 for (auto *E : C->privates()) {
2321 Visitor->AddStmt(E);
2322 }
2323 for (auto *E : C->lhs_exprs()) {
2324 Visitor->AddStmt(E);
2325 }
2326 for (auto *E : C->rhs_exprs()) {
2327 Visitor->AddStmt(E);
2328 }
2329 for (auto *E : C->reduction_ops()) {
2330 Visitor->AddStmt(E);
2331 }
2332}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002333void OMPClauseEnqueue::VisitOMPInReductionClause(
2334 const OMPInReductionClause *C) {
2335 VisitOMPClauseList(C);
2336 VisitOMPClauseWithPostUpdate(C);
2337 for (auto *E : C->privates()) {
2338 Visitor->AddStmt(E);
2339 }
2340 for (auto *E : C->lhs_exprs()) {
2341 Visitor->AddStmt(E);
2342 }
2343 for (auto *E : C->rhs_exprs()) {
2344 Visitor->AddStmt(E);
2345 }
2346 for (auto *E : C->reduction_ops()) {
2347 Visitor->AddStmt(E);
2348 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002349 for (auto *E : C->taskgroup_descriptors())
2350 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002351}
Alexander Musman8dba6642014-04-22 13:09:42 +00002352void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2353 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002354 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002355 for (const auto *E : C->privates()) {
2356 Visitor->AddStmt(E);
2357 }
Alexander Musman3276a272015-03-21 10:12:56 +00002358 for (const auto *E : C->inits()) {
2359 Visitor->AddStmt(E);
2360 }
2361 for (const auto *E : C->updates()) {
2362 Visitor->AddStmt(E);
2363 }
2364 for (const auto *E : C->finals()) {
2365 Visitor->AddStmt(E);
2366 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002367 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002368 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002369}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002370void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2371 VisitOMPClauseList(C);
2372 Visitor->AddStmt(C->getAlignment());
2373}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002374void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2375 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002376 for (auto *E : C->source_exprs()) {
2377 Visitor->AddStmt(E);
2378 }
2379 for (auto *E : C->destination_exprs()) {
2380 Visitor->AddStmt(E);
2381 }
2382 for (auto *E : C->assignment_ops()) {
2383 Visitor->AddStmt(E);
2384 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002385}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002386void
2387OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2388 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002389 for (auto *E : C->source_exprs()) {
2390 Visitor->AddStmt(E);
2391 }
2392 for (auto *E : C->destination_exprs()) {
2393 Visitor->AddStmt(E);
2394 }
2395 for (auto *E : C->assignment_ops()) {
2396 Visitor->AddStmt(E);
2397 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002398}
Alexey Bataev6125da92014-07-21 11:26:11 +00002399void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2400 VisitOMPClauseList(C);
2401}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002402void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2403 VisitOMPClauseList(C);
2404}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002405void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2406 VisitOMPClauseList(C);
2407}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002408void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2409 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002410 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002411 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002412}
Alexey Bataev3392d762016-02-16 11:18:12 +00002413void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2414 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002415void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2416 VisitOMPClauseList(C);
2417}
Samuel Antaoec172c62016-05-26 17:49:04 +00002418void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2419 VisitOMPClauseList(C);
2420}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002421void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2422 VisitOMPClauseList(C);
2423}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002424void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2425 VisitOMPClauseList(C);
2426}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002427}
Alexey Bataev756c1962013-09-24 03:17:45 +00002428
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002429void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2430 unsigned size = WL.size();
2431 OMPClauseEnqueue Visitor(this);
2432 Visitor.Visit(S);
2433 if (size == WL.size())
2434 return;
2435 // Now reverse the entries we just added. This will match the DFS
2436 // ordering performed by the worklist.
2437 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2438 std::reverse(I, E);
2439}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002440void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2442}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002443void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 AddDecl(B->getBlockDecl());
2445}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002446void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 EnqueueChildren(E);
2448 AddTypeLoc(E->getTypeSourceInfo());
2449}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002450void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002451 for (auto &I : llvm::reverse(S->body()))
2452 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002453}
2454void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002455VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 AddStmt(S->getSubStmt());
2457 AddDeclarationNameInfo(S);
2458 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2459 AddNestedNameSpecifierLoc(QualifierLoc);
2460}
2461
2462void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002463VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002464 if (E->hasExplicitTemplateArgs())
2465 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 AddDeclarationNameInfo(E);
2467 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2468 AddNestedNameSpecifierLoc(QualifierLoc);
2469 if (!E->isImplicitAccess())
2470 AddStmt(E->getBase());
2471}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002472void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 // Enqueue the initializer , if any.
2474 AddStmt(E->getInitializer());
2475 // Enqueue the array size, if any.
2476 AddStmt(E->getArraySize());
2477 // Enqueue the allocated type.
2478 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2479 // Enqueue the placement arguments.
2480 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2481 AddStmt(E->getPlacementArg(I-1));
2482}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002483void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2485 AddStmt(CE->getArg(I-1));
2486 AddStmt(CE->getCallee());
2487 AddStmt(CE->getArg(0));
2488}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002489void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2490 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 // Visit the name of the type being destroyed.
2492 AddTypeLoc(E->getDestroyedTypeInfo());
2493 // Visit the scope type that looks disturbingly like the nested-name-specifier
2494 // but isn't.
2495 AddTypeLoc(E->getScopeTypeInfo());
2496 // Visit the nested-name-specifier.
2497 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2498 AddNestedNameSpecifierLoc(QualifierLoc);
2499 // Visit base expression.
2500 AddStmt(E->getBase());
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2503 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 AddTypeLoc(E->getTypeSourceInfo());
2505}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002506void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2507 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 EnqueueChildren(E);
2509 AddTypeLoc(E->getTypeSourceInfo());
2510}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002511void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 EnqueueChildren(E);
2513 if (E->isTypeOperand())
2514 AddTypeLoc(E->getTypeOperandSourceInfo());
2515}
2516
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002517void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2518 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 EnqueueChildren(E);
2520 AddTypeLoc(E->getTypeSourceInfo());
2521}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002522void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 EnqueueChildren(E);
2524 if (E->isTypeOperand())
2525 AddTypeLoc(E->getTypeOperandSourceInfo());
2526}
2527
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002528void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 EnqueueChildren(S);
2530 AddDecl(S->getExceptionDecl());
2531}
2532
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002533void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002534 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002535 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002536 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002537}
2538
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002539void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002540 if (DR->hasExplicitTemplateArgs())
2541 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 WL.push_back(DeclRefExprParts(DR, Parent));
2543}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002544void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2545 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002546 if (E->hasExplicitTemplateArgs())
2547 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 AddDeclarationNameInfo(E);
2549 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2550}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002551void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 unsigned size = WL.size();
2553 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002554 for (const auto *D : S->decls()) {
2555 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 isFirst = false;
2557 }
2558 if (size == WL.size())
2559 return;
2560 // Now reverse the entries we just added. This will match the DFS
2561 // ordering performed by the worklist.
2562 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2563 std::reverse(I, E);
2564}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002565void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002567 for (const DesignatedInitExpr::Designator &D :
2568 llvm::reverse(E->designators())) {
2569 if (D.isFieldDesignator()) {
2570 if (FieldDecl *Field = D.getField())
2571 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 continue;
2573 }
David Majnemerf7e36092016-06-23 00:15:04 +00002574 if (D.isArrayDesignator()) {
2575 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 continue;
2577 }
David Majnemerf7e36092016-06-23 00:15:04 +00002578 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2579 AddStmt(E->getArrayRangeEnd(D));
2580 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 }
2582}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002583void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 EnqueueChildren(E);
2585 AddTypeLoc(E->getTypeInfoAsWritten());
2586}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002587void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 AddStmt(FS->getBody());
2589 AddStmt(FS->getInc());
2590 AddStmt(FS->getCond());
2591 AddDecl(FS->getConditionVariable());
2592 AddStmt(FS->getInit());
2593}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002594void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2596}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002597void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 AddStmt(If->getElse());
2599 AddStmt(If->getThen());
2600 AddStmt(If->getCond());
2601 AddDecl(If->getConditionVariable());
2602}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002603void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 // We care about the syntactic form of the initializer list, only.
2605 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2606 IE = Syntactic;
2607 EnqueueChildren(IE);
2608}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002609void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 WL.push_back(MemberExprParts(M, Parent));
2611
2612 // If the base of the member access expression is an implicit 'this', don't
2613 // visit it.
2614 // FIXME: If we ever want to show these implicit accesses, this will be
2615 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002616 if (M->isImplicitAccess())
2617 return;
2618
2619 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002620 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002621 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2622 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2623 if (FD->isAnonymousStructOrUnion()) {
2624 AddStmt(SubME->getBase());
2625 return;
2626 }
2627 }
2628 }
2629
2630 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002631}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002632void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 AddTypeLoc(E->getEncodedTypeSourceInfo());
2634}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002635void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 EnqueueChildren(M);
2637 AddTypeLoc(M->getClassReceiverTypeInfo());
2638}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002639void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 // Visit the components of the offsetof expression.
2641 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 const OffsetOfNode &Node = E->getComponent(I-1);
2643 switch (Node.getKind()) {
2644 case OffsetOfNode::Array:
2645 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2646 break;
2647 case OffsetOfNode::Field:
2648 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2649 break;
2650 case OffsetOfNode::Identifier:
2651 case OffsetOfNode::Base:
2652 continue;
2653 }
2654 }
2655 // Visit the type into which we're computing the offset.
2656 AddTypeLoc(E->getTypeSourceInfo());
2657}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002658void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002659 if (E->hasExplicitTemplateArgs())
2660 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 WL.push_back(OverloadExprParts(E, Parent));
2662}
2663void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002664 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 EnqueueChildren(E);
2666 if (E->isArgumentType())
2667 AddTypeLoc(E->getArgumentTypeInfo());
2668}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002669void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 EnqueueChildren(S);
2671}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002672void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 AddStmt(S->getBody());
2674 AddStmt(S->getCond());
2675 AddDecl(S->getConditionVariable());
2676}
2677
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002678void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 AddStmt(W->getBody());
2680 AddStmt(W->getCond());
2681 AddDecl(W->getConditionVariable());
2682}
2683
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002684void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 for (unsigned I = E->getNumArgs(); I > 0; --I)
2686 AddTypeLoc(E->getArg(I-1));
2687}
2688
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002689void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 AddTypeLoc(E->getQueriedTypeSourceInfo());
2691}
2692
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002693void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 EnqueueChildren(E);
2695}
2696
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002697void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 VisitOverloadExpr(U);
2699 if (!U->isImplicitAccess())
2700 AddStmt(U->getBase());
2701}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002702void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 AddStmt(E->getSubExpr());
2704 AddTypeLoc(E->getWrittenTypeInfo());
2705}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002706void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 WL.push_back(SizeOfPackExprParts(E, Parent));
2708}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002709void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 // If the opaque value has a source expression, just transparently
2711 // visit that. This is useful for (e.g.) pseudo-object expressions.
2712 if (Expr *SourceExpr = E->getSourceExpr())
2713 return Visit(SourceExpr);
2714}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002715void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 AddStmt(E->getBody());
2717 WL.push_back(LambdaExprParts(E, Parent));
2718}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002719void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 // Treat the expression like its syntactic form.
2721 Visit(E->getSyntacticForm());
2722}
2723
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002724void EnqueueVisitor::VisitOMPExecutableDirective(
2725 const OMPExecutableDirective *D) {
2726 EnqueueChildren(D);
2727 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2728 E = D->clauses().end();
2729 I != E; ++I)
2730 EnqueueChildren(*I);
2731}
2732
Alexander Musman3aaab662014-08-19 11:27:13 +00002733void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2734 VisitOMPExecutableDirective(D);
2735}
2736
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002737void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2738 VisitOMPExecutableDirective(D);
2739}
2740
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002741void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002742 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002743}
2744
Alexey Bataevf29276e2014-06-18 04:14:57 +00002745void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002746 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002747}
2748
Alexander Musmanf82886e2014-09-18 05:12:34 +00002749void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2750 VisitOMPLoopDirective(D);
2751}
2752
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002753void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2754 VisitOMPExecutableDirective(D);
2755}
2756
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002757void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2758 VisitOMPExecutableDirective(D);
2759}
2760
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002761void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2762 VisitOMPExecutableDirective(D);
2763}
2764
Alexander Musman80c22892014-07-17 08:54:58 +00002765void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2766 VisitOMPExecutableDirective(D);
2767}
2768
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002769void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2770 VisitOMPExecutableDirective(D);
2771 AddDeclarationNameInfo(D);
2772}
2773
Alexey Bataev4acb8592014-07-07 13:01:15 +00002774void
2775EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002776 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002777}
2778
Alexander Musmane4e893b2014-09-23 09:33:00 +00002779void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2780 const OMPParallelForSimdDirective *D) {
2781 VisitOMPLoopDirective(D);
2782}
2783
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002784void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2785 const OMPParallelSectionsDirective *D) {
2786 VisitOMPExecutableDirective(D);
2787}
2788
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002789void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2790 VisitOMPExecutableDirective(D);
2791}
2792
Alexey Bataev68446b72014-07-18 07:47:19 +00002793void
2794EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2795 VisitOMPExecutableDirective(D);
2796}
2797
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002798void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2799 VisitOMPExecutableDirective(D);
2800}
2801
Alexey Bataev2df347a2014-07-18 10:17:07 +00002802void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2803 VisitOMPExecutableDirective(D);
2804}
2805
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002806void EnqueueVisitor::VisitOMPTaskgroupDirective(
2807 const OMPTaskgroupDirective *D) {
2808 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002809 if (const Expr *E = D->getReductionRef())
2810 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002811}
2812
Alexey Bataev6125da92014-07-21 11:26:11 +00002813void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2814 VisitOMPExecutableDirective(D);
2815}
2816
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002817void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819}
2820
Alexey Bataev0162e452014-07-22 10:10:35 +00002821void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2822 VisitOMPExecutableDirective(D);
2823}
2824
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002825void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2826 VisitOMPExecutableDirective(D);
2827}
2828
Michael Wong65f367f2015-07-21 13:44:28 +00002829void EnqueueVisitor::VisitOMPTargetDataDirective(const
2830 OMPTargetDataDirective *D) {
2831 VisitOMPExecutableDirective(D);
2832}
2833
Samuel Antaodf67fc42016-01-19 19:15:56 +00002834void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2835 const OMPTargetEnterDataDirective *D) {
2836 VisitOMPExecutableDirective(D);
2837}
2838
Samuel Antao72590762016-01-19 20:04:50 +00002839void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2840 const OMPTargetExitDataDirective *D) {
2841 VisitOMPExecutableDirective(D);
2842}
2843
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002844void EnqueueVisitor::VisitOMPTargetParallelDirective(
2845 const OMPTargetParallelDirective *D) {
2846 VisitOMPExecutableDirective(D);
2847}
2848
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002849void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2850 const OMPTargetParallelForDirective *D) {
2851 VisitOMPLoopDirective(D);
2852}
2853
Alexey Bataev13314bf2014-10-09 04:18:56 +00002854void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2855 VisitOMPExecutableDirective(D);
2856}
2857
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002858void EnqueueVisitor::VisitOMPCancellationPointDirective(
2859 const OMPCancellationPointDirective *D) {
2860 VisitOMPExecutableDirective(D);
2861}
2862
Alexey Bataev80909872015-07-02 11:25:17 +00002863void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2864 VisitOMPExecutableDirective(D);
2865}
2866
Alexey Bataev49f6e782015-12-01 04:18:41 +00002867void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2868 VisitOMPLoopDirective(D);
2869}
2870
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002871void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2872 const OMPTaskLoopSimdDirective *D) {
2873 VisitOMPLoopDirective(D);
2874}
2875
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002876void EnqueueVisitor::VisitOMPDistributeDirective(
2877 const OMPDistributeDirective *D) {
2878 VisitOMPLoopDirective(D);
2879}
2880
Carlo Bertolli9925f152016-06-27 14:55:37 +00002881void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2882 const OMPDistributeParallelForDirective *D) {
2883 VisitOMPLoopDirective(D);
2884}
2885
Kelvin Li4a39add2016-07-05 05:00:15 +00002886void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2887 const OMPDistributeParallelForSimdDirective *D) {
2888 VisitOMPLoopDirective(D);
2889}
2890
Kelvin Li787f3fc2016-07-06 04:45:38 +00002891void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2892 const OMPDistributeSimdDirective *D) {
2893 VisitOMPLoopDirective(D);
2894}
2895
Kelvin Lia579b912016-07-14 02:54:56 +00002896void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2897 const OMPTargetParallelForSimdDirective *D) {
2898 VisitOMPLoopDirective(D);
2899}
2900
Kelvin Li986330c2016-07-20 22:57:10 +00002901void EnqueueVisitor::VisitOMPTargetSimdDirective(
2902 const OMPTargetSimdDirective *D) {
2903 VisitOMPLoopDirective(D);
2904}
2905
Kelvin Li02532872016-08-05 14:37:37 +00002906void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2907 const OMPTeamsDistributeDirective *D) {
2908 VisitOMPLoopDirective(D);
2909}
2910
Kelvin Li4e325f72016-10-25 12:50:55 +00002911void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2912 const OMPTeamsDistributeSimdDirective *D) {
2913 VisitOMPLoopDirective(D);
2914}
2915
Kelvin Li579e41c2016-11-30 23:51:03 +00002916void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2917 const OMPTeamsDistributeParallelForSimdDirective *D) {
2918 VisitOMPLoopDirective(D);
2919}
2920
Kelvin Li7ade93f2016-12-09 03:24:30 +00002921void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2922 const OMPTeamsDistributeParallelForDirective *D) {
2923 VisitOMPLoopDirective(D);
2924}
2925
Kelvin Libf594a52016-12-17 05:48:59 +00002926void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2927 const OMPTargetTeamsDirective *D) {
2928 VisitOMPExecutableDirective(D);
2929}
2930
Kelvin Li83c451e2016-12-25 04:52:54 +00002931void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2932 const OMPTargetTeamsDistributeDirective *D) {
2933 VisitOMPLoopDirective(D);
2934}
2935
Kelvin Li80e8f562016-12-29 22:16:30 +00002936void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2937 const OMPTargetTeamsDistributeParallelForDirective *D) {
2938 VisitOMPLoopDirective(D);
2939}
2940
Kelvin Li1851df52017-01-03 05:23:48 +00002941void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2942 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2943 VisitOMPLoopDirective(D);
2944}
2945
Kelvin Lida681182017-01-10 18:08:18 +00002946void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2947 const OMPTargetTeamsDistributeSimdDirective *D) {
2948 VisitOMPLoopDirective(D);
2949}
2950
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002951void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2953}
2954
2955bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2956 if (RegionOfInterest.isValid()) {
2957 SourceRange Range = getRawCursorExtent(C);
2958 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2959 return false;
2960 }
2961 return true;
2962}
2963
2964bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2965 while (!WL.empty()) {
2966 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002967 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002968
2969 // Set the Parent field, then back to its old value once we're done.
2970 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2971
2972 switch (LI.getKind()) {
2973 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002974 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 if (!D)
2976 continue;
2977
2978 // For now, perform default visitation for Decls.
2979 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2980 cast<DeclVisit>(&LI)->isFirst())))
2981 return true;
2982
2983 continue;
2984 }
2985 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002986 for (const TemplateArgumentLoc &Arg :
2987 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2988 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 return true;
2990 }
2991 continue;
2992 }
2993 case VisitorJob::TypeLocVisitKind: {
2994 // Perform default visitation for TypeLocs.
2995 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2996 return true;
2997 continue;
2998 }
2999 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003000 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 if (LabelStmt *stmt = LS->getStmt()) {
3002 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3003 TU))) {
3004 return true;
3005 }
3006 }
3007 continue;
3008 }
3009
3010 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3011 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3012 if (VisitNestedNameSpecifierLoc(V->get()))
3013 return true;
3014 continue;
3015 }
3016
3017 case VisitorJob::DeclarationNameInfoVisitKind: {
3018 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3019 ->get()))
3020 return true;
3021 continue;
3022 }
3023 case VisitorJob::MemberRefVisitKind: {
3024 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3025 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3026 return true;
3027 continue;
3028 }
3029 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003030 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 if (!S)
3032 continue;
3033
3034 // Update the current cursor.
3035 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3036 if (!IsInRegionOfInterest(Cursor))
3037 continue;
3038 switch (Visitor(Cursor, Parent, ClientData)) {
3039 case CXChildVisit_Break: return true;
3040 case CXChildVisit_Continue: break;
3041 case CXChildVisit_Recurse:
3042 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003043 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 EnqueueWorkList(WL, S);
3045 break;
3046 }
3047 continue;
3048 }
3049 case VisitorJob::MemberExprPartsKind: {
3050 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003051 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003052
3053 // Visit the nested-name-specifier
3054 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3055 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3056 return true;
3057
3058 // Visit the declaration name.
3059 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3060 return true;
3061
3062 // Visit the explicitly-specified template arguments, if any.
3063 if (M->hasExplicitTemplateArgs()) {
3064 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3065 *ArgEnd = Arg + M->getNumTemplateArgs();
3066 Arg != ArgEnd; ++Arg) {
3067 if (VisitTemplateArgumentLoc(*Arg))
3068 return true;
3069 }
3070 }
3071 continue;
3072 }
3073 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003074 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 // Visit nested-name-specifier, if present.
3076 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3077 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3078 return true;
3079 // Visit declaration name.
3080 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3081 return true;
3082 continue;
3083 }
3084 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003085 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 // Visit the nested-name-specifier.
3087 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3088 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3089 return true;
3090 // Visit the declaration name.
3091 if (VisitDeclarationNameInfo(O->getNameInfo()))
3092 return true;
3093 // Visit the overloaded declaration reference.
3094 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3095 return true;
3096 continue;
3097 }
3098 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003099 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003100 NamedDecl *Pack = E->getPack();
3101 if (isa<TemplateTypeParmDecl>(Pack)) {
3102 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3103 E->getPackLoc(), TU)))
3104 return true;
3105
3106 continue;
3107 }
3108
3109 if (isa<TemplateTemplateParmDecl>(Pack)) {
3110 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3111 E->getPackLoc(), TU)))
3112 return true;
3113
3114 continue;
3115 }
3116
3117 // Non-type template parameter packs and function parameter packs are
3118 // treated like DeclRefExpr cursors.
3119 continue;
3120 }
3121
3122 case VisitorJob::LambdaExprPartsKind: {
3123 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003124 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3126 CEnd = E->explicit_capture_end();
3127 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003128 // FIXME: Lambda init-captures.
3129 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003131
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3133 C->getLocation(),
3134 TU)))
3135 return true;
3136 }
3137
Haojian Wuef87c262018-12-18 15:29:12 +00003138 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003140 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3141 if (E->hasExplicitParameters()) {
3142 // Visit parameters.
3143 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3144 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003146 }
3147 if (E->hasExplicitResultType()) {
3148 // Visit result type.
3149 if (Visit(Proto.getReturnLoc()))
3150 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 }
3152 }
3153 break;
3154 }
3155
3156 case VisitorJob::PostChildrenVisitKind:
3157 if (PostChildrenVisitor(Parent, ClientData))
3158 return true;
3159 break;
3160 }
3161 }
3162 return false;
3163}
3164
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003165bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003166 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 if (!WorkListFreeList.empty()) {
3168 WL = WorkListFreeList.back();
3169 WL->clear();
3170 WorkListFreeList.pop_back();
3171 }
3172 else {
3173 WL = new VisitorWorkList();
3174 WorkListCache.push_back(WL);
3175 }
3176 EnqueueWorkList(*WL, S);
3177 bool result = RunVisitorWorkList(*WL);
3178 WorkListFreeList.push_back(WL);
3179 return result;
3180}
3181
3182namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003183typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003184RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3185 const DeclarationNameInfo &NI, SourceRange QLoc,
3186 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3188 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3189 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3190
3191 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3192
3193 RefNamePieces Pieces;
3194
3195 if (WantQualifier && QLoc.isValid())
3196 Pieces.push_back(QLoc);
3197
3198 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3199 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003200
3201 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3202 Pieces.push_back(*TemplateArgsLoc);
3203
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 if (Kind == DeclarationName::CXXOperatorName) {
3205 Pieces.push_back(SourceLocation::getFromRawEncoding(
3206 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3207 Pieces.push_back(SourceLocation::getFromRawEncoding(
3208 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3209 }
3210
3211 if (WantSinglePiece) {
3212 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3213 Pieces.clear();
3214 Pieces.push_back(R);
3215 }
3216
3217 return Pieces;
3218}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003219}
Guy Benyei11169dd2012-12-18 14:30:41 +00003220
3221//===----------------------------------------------------------------------===//
3222// Misc. API hooks.
3223//===----------------------------------------------------------------------===//
3224
Chad Rosier05c71aa2013-03-27 18:28:23 +00003225static void fatal_error_handler(void *user_data, const std::string& reason,
3226 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 // Write the result out to stderr avoiding errs() because raw_ostreams can
3228 // call report_fatal_error.
3229 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3230 ::abort();
3231}
3232
Chandler Carruth66660742014-06-27 16:37:27 +00003233namespace {
3234struct RegisterFatalErrorHandler {
3235 RegisterFatalErrorHandler() {
3236 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3237 }
3238};
3239}
3240
3241static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3242
Guy Benyei11169dd2012-12-18 14:30:41 +00003243CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3244 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 // We use crash recovery to make some of our APIs more reliable, implicitly
3246 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003247 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3248 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003249
Chandler Carruth66660742014-06-27 16:37:27 +00003250 // Look through the managed static to trigger construction of the managed
3251 // static which registers our fatal error handler. This ensures it is only
3252 // registered once.
3253 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003254
Adrian Prantlbc068582015-07-08 01:00:30 +00003255 // Initialize targets for clang module support.
3256 llvm::InitializeAllTargets();
3257 llvm::InitializeAllTargetMCs();
3258 llvm::InitializeAllAsmPrinters();
3259 llvm::InitializeAllAsmParsers();
3260
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003261 CIndexer *CIdxr = new CIndexer();
3262
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 if (excludeDeclarationsFromPCH)
3264 CIdxr->setOnlyLocalDecls();
3265 if (displayDiagnostics)
3266 CIdxr->setDisplayDiagnostics();
3267
3268 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3269 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3270 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3271 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3272 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3273 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3274
3275 return CIdxr;
3276}
3277
3278void clang_disposeIndex(CXIndex CIdx) {
3279 if (CIdx)
3280 delete static_cast<CIndexer *>(CIdx);
3281}
3282
3283void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3284 if (CIdx)
3285 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3286}
3287
3288unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3289 if (CIdx)
3290 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3291 return 0;
3292}
3293
Alex Lorenz08615792017-12-04 21:56:36 +00003294void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3295 const char *Path) {
3296 if (CIdx)
3297 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3298}
3299
Guy Benyei11169dd2012-12-18 14:30:41 +00003300void clang_toggleCrashRecovery(unsigned isEnabled) {
3301 if (isEnabled)
3302 llvm::CrashRecoveryContext::Enable();
3303 else
3304 llvm::CrashRecoveryContext::Disable();
3305}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003306
Guy Benyei11169dd2012-12-18 14:30:41 +00003307CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3308 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003309 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003310 enum CXErrorCode Result =
3311 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003312 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003313 assert((TU && Result == CXError_Success) ||
3314 (!TU && Result != CXError_Success));
3315 return TU;
3316}
3317
3318enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3319 const char *ast_filename,
3320 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003321 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003322 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003323
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003324 if (!CIdx || !ast_filename || !out_TU)
3325 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003326
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003327 LOG_FUNC_SECTION {
3328 *Log << ast_filename;
3329 }
3330
Guy Benyei11169dd2012-12-18 14:30:41 +00003331 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3332 FileSystemOptions FileSystemOpts;
3333
Justin Bognerd512c1e2014-10-15 00:33:06 +00003334 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3335 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003336 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003337 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3338 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003339 FileSystemOpts, /*UseDebugInfo=*/false,
3340 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003341 /*CaptureDiagnostics=*/true,
3342 /*AllowPCHWithCompilerErrors=*/true,
3343 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003344 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003345 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003346}
3347
3348unsigned clang_defaultEditingTranslationUnitOptions() {
3349 return CXTranslationUnit_PrecompiledPreamble |
3350 CXTranslationUnit_CacheCompletionResults;
3351}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003352
Guy Benyei11169dd2012-12-18 14:30:41 +00003353CXTranslationUnit
3354clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3355 const char *source_filename,
3356 int num_command_line_args,
3357 const char * const *command_line_args,
3358 unsigned num_unsaved_files,
3359 struct CXUnsavedFile *unsaved_files) {
3360 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3361 return clang_parseTranslationUnit(CIdx, source_filename,
3362 command_line_args, num_command_line_args,
3363 unsaved_files, num_unsaved_files,
3364 Options);
3365}
3366
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003367static CXErrorCode
3368clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3369 const char *const *command_line_args,
3370 int num_command_line_args,
3371 ArrayRef<CXUnsavedFile> unsaved_files,
3372 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003373 // Set up the initial return values.
3374 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003375 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003376
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003377 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003378 if (!CIdx || !out_TU)
3379 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003380
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3382
3383 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3384 setThreadBackgroundPriority();
3385
3386 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003387 bool CreatePreambleOnFirstParse =
3388 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003389 // FIXME: Add a flag for modules.
3390 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003391 = (options & (CXTranslationUnit_Incomplete |
3392 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003393 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003394 = options & CXTranslationUnit_CacheCompletionResults;
3395 bool IncludeBriefCommentsInCodeCompletion
3396 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003397 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3398 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003399 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3400 if (options & CXTranslationUnit_SkipFunctionBodies) {
3401 SkipFunctionBodies =
3402 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3403 ? SkipFunctionBodiesScope::Preamble
3404 : SkipFunctionBodiesScope::PreambleAndMainFile;
3405 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003406
3407 // Configure the diagnostics.
3408 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003409 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003410
Manuel Klimek016c0242016-03-01 10:56:19 +00003411 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003412 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003413
Guy Benyei11169dd2012-12-18 14:30:41 +00003414 // Recover resources if we crash before exiting this function.
3415 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3416 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003417 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003418
Ahmed Charlesb8984322014-03-07 20:03:18 +00003419 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3420 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003421
3422 // Recover resources if we crash before exiting this function.
3423 llvm::CrashRecoveryContextCleanupRegistrar<
3424 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3425
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003426 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003427 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003428 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003429 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 }
3431
Ahmed Charlesb8984322014-03-07 20:03:18 +00003432 std::unique_ptr<std::vector<const char *>> Args(
3433 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003434
3435 // Recover resources if we crash before exiting this method.
3436 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3437 ArgsCleanup(Args.get());
3438
3439 // Since the Clang C library is primarily used by batch tools dealing with
3440 // (often very broken) source code, where spell-checking can have a
3441 // significant negative impact on performance (particularly when
3442 // precompiled headers are involved), we disable it by default.
3443 // Only do this if we haven't found a spell-checking-related argument.
3444 bool FoundSpellCheckingArgument = false;
3445 for (int I = 0; I != num_command_line_args; ++I) {
3446 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3447 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3448 FoundSpellCheckingArgument = true;
3449 break;
3450 }
3451 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003452 Args->insert(Args->end(), command_line_args,
3453 command_line_args + num_command_line_args);
3454
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003455 if (!FoundSpellCheckingArgument)
3456 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3457
Guy Benyei11169dd2012-12-18 14:30:41 +00003458 // The 'source_filename' argument is optional. If the caller does not
3459 // specify it then it is assumed that the source file is specified
3460 // in the actual argument list.
3461 // Put the source file after command_line_args otherwise if '-x' flag is
3462 // present it will be unused.
3463 if (source_filename)
3464 Args->push_back(source_filename);
3465
3466 // Do we need the detailed preprocessing record?
3467 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3468 Args->push_back("-Xclang");
3469 Args->push_back("-detailed-preprocessing-record");
3470 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003471
3472 // Suppress any editor placeholder diagnostics.
3473 Args->push_back("-fallow-editor-placeholders");
3474
Guy Benyei11169dd2012-12-18 14:30:41 +00003475 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003476 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003477 // Unless the user specified that they want the preamble on the first parse
3478 // set it up to be created on the first reparse. This makes the first parse
3479 // faster, trading for a slower (first) reparse.
3480 unsigned PrecompilePreambleAfterNParses =
3481 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003482
Alex Lorenz08615792017-12-04 21:56:36 +00003483 LibclangInvocationReporter InvocationReporter(
3484 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003485 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3486 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003487 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003488 Args->data(), Args->data() + Args->size(),
3489 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003490 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3491 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003492 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3493 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003494 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003495 /*UserFilesAreVolatile=*/true, ForSerialization,
3496 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3497 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003498
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003499 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003500 if (!Unit && !ErrUnit)
3501 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003502
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 if (NumErrors != Diags->getClient()->getNumErrors()) {
3504 // Make sure to check that 'Unit' is non-NULL.
3505 if (CXXIdx->getDisplayDiagnostics())
3506 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3507 }
3508
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003509 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3510 return CXError_ASTReadError;
3511
David Blaikieea4395e2017-01-06 19:49:01 +00003512 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003513 if (CXTranslationUnitImpl *TU = *out_TU) {
3514 TU->ParsingOptions = options;
3515 TU->Arguments.reserve(Args->size());
3516 for (const char *Arg : *Args)
3517 TU->Arguments.push_back(Arg);
3518 return CXError_Success;
3519 }
3520 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003521}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003522
3523CXTranslationUnit
3524clang_parseTranslationUnit(CXIndex CIdx,
3525 const char *source_filename,
3526 const char *const *command_line_args,
3527 int num_command_line_args,
3528 struct CXUnsavedFile *unsaved_files,
3529 unsigned num_unsaved_files,
3530 unsigned options) {
3531 CXTranslationUnit TU;
3532 enum CXErrorCode Result = clang_parseTranslationUnit2(
3533 CIdx, source_filename, command_line_args, num_command_line_args,
3534 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003535 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003536 assert((TU && Result == CXError_Success) ||
3537 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003538 return TU;
3539}
3540
3541enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003542 CXIndex CIdx, const char *source_filename,
3543 const char *const *command_line_args, int num_command_line_args,
3544 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3545 unsigned options, CXTranslationUnit *out_TU) {
3546 SmallVector<const char *, 4> Args;
3547 Args.push_back("clang");
3548 Args.append(command_line_args, command_line_args + num_command_line_args);
3549 return clang_parseTranslationUnit2FullArgv(
3550 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3551 num_unsaved_files, options, out_TU);
3552}
3553
3554enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3555 CXIndex CIdx, const char *source_filename,
3556 const char *const *command_line_args, int num_command_line_args,
3557 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3558 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003559 LOG_FUNC_SECTION {
3560 *Log << source_filename << ": ";
3561 for (int i = 0; i != num_command_line_args; ++i)
3562 *Log << command_line_args[i] << " ";
3563 }
3564
Alp Toker9d85b182014-07-07 01:23:14 +00003565 if (num_unsaved_files && !unsaved_files)
3566 return CXError_InvalidArguments;
3567
Alp Toker5c532982014-07-07 22:42:03 +00003568 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003569 auto ParseTranslationUnitImpl = [=, &result] {
3570 result = clang_parseTranslationUnit_Impl(
3571 CIdx, source_filename, command_line_args, num_command_line_args,
3572 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3573 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003574
Guy Benyei11169dd2012-12-18 14:30:41 +00003575 llvm::CrashRecoveryContext CRC;
3576
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003577 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003578 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3579 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3580 fprintf(stderr, " 'command_line_args' : [");
3581 for (int i = 0; i != num_command_line_args; ++i) {
3582 if (i)
3583 fprintf(stderr, ", ");
3584 fprintf(stderr, "'%s'", command_line_args[i]);
3585 }
3586 fprintf(stderr, "],\n");
3587 fprintf(stderr, " 'unsaved_files' : [");
3588 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3589 if (i)
3590 fprintf(stderr, ", ");
3591 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3592 unsaved_files[i].Length);
3593 }
3594 fprintf(stderr, "],\n");
3595 fprintf(stderr, " 'options' : %d,\n", options);
3596 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003597
3598 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003599 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003600 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003601 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003602 }
Alp Toker5c532982014-07-07 22:42:03 +00003603
3604 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003605}
3606
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003607CXString clang_Type_getObjCEncoding(CXType CT) {
3608 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3609 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3610 std::string encoding;
3611 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3612 encoding);
3613
3614 return cxstring::createDup(encoding);
3615}
3616
3617static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3618 if (C.kind == CXCursor_MacroDefinition) {
3619 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3620 return MDR->getName();
3621 } else if (C.kind == CXCursor_MacroExpansion) {
3622 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3623 return ME.getName();
3624 }
3625 return nullptr;
3626}
3627
3628unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3629 const IdentifierInfo *II = getMacroIdentifier(C);
3630 if (!II) {
3631 return false;
3632 }
3633 ASTUnit *ASTU = getCursorASTUnit(C);
3634 Preprocessor &PP = ASTU->getPreprocessor();
3635 if (const MacroInfo *MI = PP.getMacroInfo(II))
3636 return MI->isFunctionLike();
3637 return false;
3638}
3639
3640unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3641 const IdentifierInfo *II = getMacroIdentifier(C);
3642 if (!II) {
3643 return false;
3644 }
3645 ASTUnit *ASTU = getCursorASTUnit(C);
3646 Preprocessor &PP = ASTU->getPreprocessor();
3647 if (const MacroInfo *MI = PP.getMacroInfo(II))
3648 return MI->isBuiltinMacro();
3649 return false;
3650}
3651
3652unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3653 const Decl *D = getCursorDecl(C);
3654 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3655 if (!FD) {
3656 return false;
3657 }
3658 return FD->isInlined();
3659}
3660
3661static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3662 if (callExpr->getNumArgs() != 1) {
3663 return nullptr;
3664 }
3665
3666 StringLiteral *S = nullptr;
3667 auto *arg = callExpr->getArg(0);
3668 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3669 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3670 auto *subExpr = I->getSubExprAsWritten();
3671
3672 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3673 return nullptr;
3674 }
3675
3676 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3677 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3678 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3679 } else {
3680 return nullptr;
3681 }
3682 return S;
3683}
3684
David Blaikie59272572016-04-13 18:23:33 +00003685struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003686 CXEvalResultKind EvalType;
3687 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003688 unsigned long long unsignedVal;
3689 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003690 double floatVal;
3691 char *stringVal;
3692 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003693 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003694 ~ExprEvalResult() {
3695 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3696 EvalType != CXEval_Int) {
3697 delete EvalData.stringVal;
3698 }
3699 }
3700};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003701
3702void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003703 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003704}
3705
3706CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3707 if (!E) {
3708 return CXEval_UnExposed;
3709 }
3710 return ((ExprEvalResult *)E)->EvalType;
3711}
3712
3713int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003714 return clang_EvalResult_getAsLongLong(E);
3715}
3716
3717long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003718 if (!E) {
3719 return 0;
3720 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003721 ExprEvalResult *Result = (ExprEvalResult*)E;
3722 if (Result->IsUnsignedInt)
3723 return Result->EvalData.unsignedVal;
3724 return Result->EvalData.intVal;
3725}
3726
3727unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3728 return ((ExprEvalResult *)E)->IsUnsignedInt;
3729}
3730
3731unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3732 if (!E) {
3733 return 0;
3734 }
3735
3736 ExprEvalResult *Result = (ExprEvalResult*)E;
3737 if (Result->IsUnsignedInt)
3738 return Result->EvalData.unsignedVal;
3739 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003740}
3741
3742double clang_EvalResult_getAsDouble(CXEvalResult E) {
3743 if (!E) {
3744 return 0;
3745 }
3746 return ((ExprEvalResult *)E)->EvalData.floatVal;
3747}
3748
3749const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3750 if (!E) {
3751 return nullptr;
3752 }
3753 return ((ExprEvalResult *)E)->EvalData.stringVal;
3754}
3755
3756static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3757 Expr::EvalResult ER;
3758 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003759 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003760 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003761
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003762 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003763 if (!expr->EvaluateAsRValue(ER, ctx))
3764 return nullptr;
3765
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003766 QualType rettype;
3767 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003768 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003769 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003770 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003771
David Blaikiebbc00882016-04-13 18:36:19 +00003772 if (ER.Val.isInt()) {
3773 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003774
3775 auto& val = ER.Val.getInt();
3776 if (val.isUnsigned()) {
3777 result->IsUnsignedInt = true;
3778 result->EvalData.unsignedVal = val.getZExtValue();
3779 } else {
3780 result->EvalData.intVal = val.getExtValue();
3781 }
3782
David Blaikiebbc00882016-04-13 18:36:19 +00003783 return result.release();
3784 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003785
David Blaikiebbc00882016-04-13 18:36:19 +00003786 if (ER.Val.isFloat()) {
3787 llvm::SmallVector<char, 100> Buffer;
3788 ER.Val.getFloat().toString(Buffer);
3789 std::string floatStr(Buffer.data(), Buffer.size());
3790 result->EvalType = CXEval_Float;
3791 bool ignored;
3792 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003793 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003794 llvm::APFloat::rmNearestTiesToEven, &ignored);
3795 result->EvalData.floatVal = apFloat.convertToDouble();
3796 return result.release();
3797 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003798
David Blaikiebbc00882016-04-13 18:36:19 +00003799 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3800 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3801 auto *subExpr = I->getSubExprAsWritten();
3802 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3803 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003804 const StringLiteral *StrE = nullptr;
3805 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003806 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003807
3808 if (ObjCExpr) {
3809 StrE = ObjCExpr->getString();
3810 result->EvalType = CXEval_ObjCStrLiteral;
3811 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003812 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003813 result->EvalType = CXEval_StrLiteral;
3814 }
3815
3816 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003817 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003818 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3819 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003820 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003821 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003822 }
3823 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3824 expr->getStmtClass() == Stmt::StringLiteralClass) {
3825 const StringLiteral *StrE = nullptr;
3826 const ObjCStringLiteral *ObjCExpr;
3827 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003828
David Blaikiebbc00882016-04-13 18:36:19 +00003829 if (ObjCExpr) {
3830 StrE = ObjCExpr->getString();
3831 result->EvalType = CXEval_ObjCStrLiteral;
3832 } else {
3833 StrE = cast<StringLiteral>(expr);
3834 result->EvalType = CXEval_StrLiteral;
3835 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003836
David Blaikiebbc00882016-04-13 18:36:19 +00003837 std::string strRef(StrE->getString().str());
3838 result->EvalData.stringVal = new char[strRef.size() + 1];
3839 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3840 result->EvalData.stringVal[strRef.size()] = '\0';
3841 return result.release();
3842 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003843
David Blaikiebbc00882016-04-13 18:36:19 +00003844 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3845 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003846
David Blaikiebbc00882016-04-13 18:36:19 +00003847 rettype = CC->getType();
3848 if (rettype.getAsString() == "CFStringRef" &&
3849 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003850
David Blaikiebbc00882016-04-13 18:36:19 +00003851 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3852 StringLiteral *S = getCFSTR_value(callExpr);
3853 if (S) {
3854 std::string strLiteral(S->getString().str());
3855 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003856
David Blaikiebbc00882016-04-13 18:36:19 +00003857 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3858 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3859 strLiteral.size());
3860 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003861 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003862 }
3863 }
3864
David Blaikiebbc00882016-04-13 18:36:19 +00003865 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3866 callExpr = static_cast<CallExpr *>(expr);
3867 rettype = callExpr->getCallReturnType(ctx);
3868
3869 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3870 return nullptr;
3871
3872 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3873 if (callExpr->getNumArgs() == 1 &&
3874 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3875 return nullptr;
3876 } else if (rettype.getAsString() == "CFStringRef") {
3877
3878 StringLiteral *S = getCFSTR_value(callExpr);
3879 if (S) {
3880 std::string strLiteral(S->getString().str());
3881 result->EvalType = CXEval_CFStr;
3882 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3883 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3884 strLiteral.size());
3885 result->EvalData.stringVal[strLiteral.size()] = '\0';
3886 return result.release();
3887 }
3888 }
3889 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3890 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3891 ValueDecl *V = D->getDecl();
3892 if (V->getKind() == Decl::Function) {
3893 std::string strName = V->getNameAsString();
3894 result->EvalType = CXEval_Other;
3895 result->EvalData.stringVal = new char[strName.size() + 1];
3896 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3897 result->EvalData.stringVal[strName.size()] = '\0';
3898 return result.release();
3899 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003900 }
3901
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003902 return nullptr;
3903}
3904
Alex Lorenz65317e12019-01-08 22:32:51 +00003905static const Expr *evaluateDeclExpr(const Decl *D) {
3906 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003907 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003908 if (auto *Var = dyn_cast<VarDecl>(D))
3909 return Var->getInit();
3910 else if (auto *Field = dyn_cast<FieldDecl>(D))
3911 return Field->getInClassInitializer();
3912 return nullptr;
3913}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003914
Alex Lorenz65317e12019-01-08 22:32:51 +00003915static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3916 assert(CS && "invalid compound statement");
3917 for (auto *bodyIterator : CS->body()) {
3918 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3919 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003920 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003921 return nullptr;
3922}
3923
Alex Lorenz65317e12019-01-08 22:32:51 +00003924CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3925 if (const Expr *E =
3926 clang_getCursorKind(C) == CXCursor_CompoundStmt
3927 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3928 : evaluateDeclExpr(getCursorDecl(C)))
3929 return const_cast<CXEvalResult>(
3930 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3931 return nullptr;
3932}
3933
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003934unsigned clang_Cursor_hasAttrs(CXCursor C) {
3935 const Decl *D = getCursorDecl(C);
3936 if (!D) {
3937 return 0;
3938 }
3939
3940 if (D->hasAttrs()) {
3941 return 1;
3942 }
3943
3944 return 0;
3945}
Guy Benyei11169dd2012-12-18 14:30:41 +00003946unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3947 return CXSaveTranslationUnit_None;
3948}
3949
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003950static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3951 const char *FileName,
3952 unsigned options) {
3953 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003954 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3955 setThreadBackgroundPriority();
3956
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003957 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3958 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003959}
3960
3961int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3962 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003963 LOG_FUNC_SECTION {
3964 *Log << TU << ' ' << FileName;
3965 }
3966
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003967 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003968 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003969 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003970 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003971
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003972 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3974 if (!CXXUnit->hasSema())
3975 return CXSaveError_InvalidTU;
3976
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003977 CXSaveError result;
3978 auto SaveTranslationUnitImpl = [=, &result]() {
3979 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3980 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003981
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003982 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003983 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003984
3985 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3986 PrintLibclangResourceUsage(TU);
3987
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003988 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003989 }
3990
3991 // We have an AST that has invalid nodes due to compiler errors.
3992 // Use a crash recovery thread for protection.
3993
3994 llvm::CrashRecoveryContext CRC;
3995
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003996 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003997 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3998 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3999 fprintf(stderr, " 'options' : %d,\n", options);
4000 fprintf(stderr, "}\n");
4001
4002 return CXSaveError_Unknown;
4003
4004 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4005 PrintLibclangResourceUsage(TU);
4006 }
4007
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004008 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004009}
4010
4011void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4012 if (CTUnit) {
4013 // If the translation unit has been marked as unsafe to free, just discard
4014 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004015 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4016 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 return;
4018
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004019 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004020 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4022 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004023 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 delete CTUnit;
4025 }
4026}
4027
Erik Verbruggen346066b2017-05-30 14:25:54 +00004028unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4029 if (CTUnit) {
4030 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4031
4032 if (Unit && Unit->isUnsafeToFree())
4033 return false;
4034
4035 Unit->ResetForParse();
4036 return true;
4037 }
4038
4039 return false;
4040}
4041
Guy Benyei11169dd2012-12-18 14:30:41 +00004042unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4043 return CXReparse_None;
4044}
4045
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004046static CXErrorCode
4047clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4048 ArrayRef<CXUnsavedFile> unsaved_files,
4049 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004050 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004051 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004052 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004053 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004054 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004055
4056 // Reset the associated diagnostics.
4057 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004058 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004059
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004060 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004061 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4062 setThreadBackgroundPriority();
4063
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004064 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004065 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004066
4067 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4068 new std::vector<ASTUnit::RemappedFile>());
4069
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 // Recover resources if we crash before exiting this function.
4071 llvm::CrashRecoveryContextCleanupRegistrar<
4072 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004073
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004074 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004075 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004076 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004077 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004079
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004080 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4081 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004082 return CXError_Success;
4083 if (isASTReadError(CXXUnit))
4084 return CXError_ASTReadError;
4085 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004086}
4087
4088int clang_reparseTranslationUnit(CXTranslationUnit TU,
4089 unsigned num_unsaved_files,
4090 struct CXUnsavedFile *unsaved_files,
4091 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004092 LOG_FUNC_SECTION {
4093 *Log << TU;
4094 }
4095
Alp Toker9d85b182014-07-07 01:23:14 +00004096 if (num_unsaved_files && !unsaved_files)
4097 return CXError_InvalidArguments;
4098
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004099 CXErrorCode result;
4100 auto ReparseTranslationUnitImpl = [=, &result]() {
4101 result = clang_reparseTranslationUnit_Impl(
4102 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4103 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004104
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 llvm::CrashRecoveryContext CRC;
4106
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004107 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004108 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004109 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004110 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4112 PrintLibclangResourceUsage(TU);
4113
Alp Toker5c532982014-07-07 22:42:03 +00004114 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004115}
4116
4117
4118CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004119 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004120 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004121 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004122 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004123
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004124 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004125 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004126}
4127
4128CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004129 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004130 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004131 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004132 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004133
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004134 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004135 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4136}
4137
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004138CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4139 if (isNotUsableTU(CTUnit)) {
4140 LOG_BAD_TU(CTUnit);
4141 return nullptr;
4142 }
4143
4144 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4145 impl->TranslationUnit = CTUnit;
4146 return impl;
4147}
4148
4149CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4150 if (!TargetInfo)
4151 return cxstring::createEmpty();
4152
4153 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4154 assert(!isNotUsableTU(CTUnit) &&
4155 "Unexpected unusable translation unit in TargetInfo");
4156
4157 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4158 std::string Triple =
4159 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4160 return cxstring::createDup(Triple);
4161}
4162
4163int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4164 if (!TargetInfo)
4165 return -1;
4166
4167 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4168 assert(!isNotUsableTU(CTUnit) &&
4169 "Unexpected unusable translation unit in TargetInfo");
4170
4171 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4172 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4173}
4174
4175void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4176 if (!TargetInfo)
4177 return;
4178
4179 delete TargetInfo;
4180}
4181
Guy Benyei11169dd2012-12-18 14:30:41 +00004182//===----------------------------------------------------------------------===//
4183// CXFile Operations.
4184//===----------------------------------------------------------------------===//
4185
Guy Benyei11169dd2012-12-18 14:30:41 +00004186CXString clang_getFileName(CXFile SFile) {
4187 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004188 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004189
4190 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004191 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004192}
4193
4194time_t clang_getFileTime(CXFile SFile) {
4195 if (!SFile)
4196 return 0;
4197
4198 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4199 return FEnt->getModificationTime();
4200}
4201
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004202CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004203 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004204 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004205 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004206 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004207
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004208 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004209
4210 FileManager &FMgr = CXXUnit->getFileManager();
4211 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4212}
4213
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004214const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4215 size_t *size) {
4216 if (isNotUsableTU(TU)) {
4217 LOG_BAD_TU(TU);
4218 return nullptr;
4219 }
4220
4221 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4222 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4223 bool Invalid = true;
4224 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4225 if (Invalid) {
4226 if (size)
4227 *size = 0;
4228 return nullptr;
4229 }
4230 if (size)
4231 *size = buf->getBufferSize();
4232 return buf->getBufferStart();
4233}
4234
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004235unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4236 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004237 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004238 LOG_BAD_TU(TU);
4239 return 0;
4240 }
4241
4242 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 return 0;
4244
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004245 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 FileEntry *FEnt = static_cast<FileEntry *>(file);
4247 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4248 .isFileMultipleIncludeGuarded(FEnt);
4249}
4250
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004251int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4252 if (!file || !outID)
4253 return 1;
4254
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004255 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004256 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4257 outID->data[0] = ID.getDevice();
4258 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004259 outID->data[2] = FEnt->getModificationTime();
4260 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004261}
4262
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004263int clang_File_isEqual(CXFile file1, CXFile file2) {
4264 if (file1 == file2)
4265 return true;
4266
4267 if (!file1 || !file2)
4268 return false;
4269
4270 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4271 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4272 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4273}
4274
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004275CXString clang_File_tryGetRealPathName(CXFile SFile) {
4276 if (!SFile)
4277 return cxstring::createNull();
4278
4279 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4280 return cxstring::createRef(FEnt->tryGetRealPathName());
4281}
4282
Guy Benyei11169dd2012-12-18 14:30:41 +00004283//===----------------------------------------------------------------------===//
4284// CXCursor Operations.
4285//===----------------------------------------------------------------------===//
4286
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004287static const Decl *getDeclFromExpr(const Stmt *E) {
4288 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004289 return getDeclFromExpr(CE->getSubExpr());
4290
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004291 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004293 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004295 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004297 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 if (PRE->isExplicitProperty())
4299 return PRE->getExplicitProperty();
4300 // It could be messaging both getter and setter as in:
4301 // ++myobj.myprop;
4302 // in which case prefer to associate the setter since it is less obvious
4303 // from inspecting the source that the setter is going to get called.
4304 if (PRE->isMessagingSetter())
4305 return PRE->getImplicitPropertySetter();
4306 return PRE->getImplicitPropertyGetter();
4307 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004308 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004310 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 if (Expr *Src = OVE->getSourceExpr())
4312 return getDeclFromExpr(Src);
4313
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004314 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004316 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 if (!CE->isElidable())
4318 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004319 if (const CXXInheritedCtorInitExpr *CE =
4320 dyn_cast<CXXInheritedCtorInitExpr>(E))
4321 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004322 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 return OME->getMethodDecl();
4324
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004325 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004327 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4329 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004330 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4332 isa<ParmVarDecl>(SizeOfPack->getPack()))
4333 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004334
4335 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004336}
4337
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004338static SourceLocation getLocationFromExpr(const Expr *E) {
4339 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004340 return getLocationFromExpr(CE->getSubExpr());
4341
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004342 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004344 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004346 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004348 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004350 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004352 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004354
4355 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004356}
4357
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004358extern "C" {
4359
Guy Benyei11169dd2012-12-18 14:30:41 +00004360unsigned clang_visitChildren(CXCursor parent,
4361 CXCursorVisitor visitor,
4362 CXClientData client_data) {
4363 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4364 /*VisitPreprocessorLast=*/false);
4365 return CursorVis.VisitChildren(parent);
4366}
4367
4368#ifndef __has_feature
4369#define __has_feature(x) 0
4370#endif
4371#if __has_feature(blocks)
4372typedef enum CXChildVisitResult
4373 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4374
4375static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4376 CXClientData client_data) {
4377 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4378 return block(cursor, parent);
4379}
4380#else
4381// If we are compiled with a compiler that doesn't have native blocks support,
4382// define and call the block manually, so the
4383typedef struct _CXChildVisitResult
4384{
4385 void *isa;
4386 int flags;
4387 int reserved;
4388 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4389 CXCursor);
4390} *CXCursorVisitorBlock;
4391
4392static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4393 CXClientData client_data) {
4394 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4395 return block->invoke(block, cursor, parent);
4396}
4397#endif
4398
4399
4400unsigned clang_visitChildrenWithBlock(CXCursor parent,
4401 CXCursorVisitorBlock block) {
4402 return clang_visitChildren(parent, visitWithBlock, block);
4403}
4404
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004405static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004407 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004408
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004409 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004411 if (const ObjCPropertyImplDecl *PropImpl =
4412 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004414 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004415
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004416 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004418 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004419
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004420 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 }
4422
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004423 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004424 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004425
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004426 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4428 // and returns different names. NamedDecl returns the class name and
4429 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004430 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004431
4432 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004433 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004434
4435 SmallString<1024> S;
4436 llvm::raw_svector_ostream os(S);
4437 ND->printName(os);
4438
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004439 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004440}
4441
4442CXString clang_getCursorSpelling(CXCursor C) {
4443 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004444 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004445
4446 if (clang_isReference(C.kind)) {
4447 switch (C.kind) {
4448 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004449 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004450 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 }
4452 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004453 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004454 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 }
4456 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004457 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004459 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 }
4461 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004462 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004463 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 }
4465 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004466 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 assert(Type && "Missing type decl");
4468
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004469 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 getAsString());
4471 }
4472 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004473 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 assert(Template && "Missing template decl");
4475
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004476 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 }
4478
4479 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004480 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 assert(NS && "Missing namespace decl");
4482
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004483 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 }
4485
4486 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004487 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 assert(Field && "Missing member decl");
4489
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004490 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 }
4492
4493 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004494 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 assert(Label && "Missing label");
4496
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004497 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 }
4499
4500 case CXCursor_OverloadedDeclRef: {
4501 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004502 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4503 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004504 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004505 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004507 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004508 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 OverloadedTemplateStorage *Ovl
4510 = Storage.get<OverloadedTemplateStorage*>();
4511 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004512 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004513 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 }
4515
4516 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004517 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 assert(Var && "Missing variable decl");
4519
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004520 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 }
4522
4523 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004524 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 }
4526 }
4527
4528 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004529 const Expr *E = getCursorExpr(C);
4530
4531 if (C.kind == CXCursor_ObjCStringLiteral ||
4532 C.kind == CXCursor_StringLiteral) {
4533 const StringLiteral *SLit;
4534 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4535 SLit = OSL->getString();
4536 } else {
4537 SLit = cast<StringLiteral>(E);
4538 }
4539 SmallString<256> Buf;
4540 llvm::raw_svector_ostream OS(Buf);
4541 SLit->outputString(OS);
4542 return cxstring::createDup(OS.str());
4543 }
4544
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004545 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 if (D)
4547 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004548 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 }
4550
4551 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004552 const Stmt *S = getCursorStmt(C);
4553 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004554 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004555
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004556 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 }
4558
4559 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004560 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 ->getNameStart());
4562
4563 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004564 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 ->getNameStart());
4566
4567 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004568 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004569
4570 if (clang_isDeclaration(C.kind))
4571 return getDeclSpelling(getCursorDecl(C));
4572
4573 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004574 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004575 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 }
4577
4578 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004579 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004580 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 }
4582
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004583 if (C.kind == CXCursor_PackedAttr) {
4584 return cxstring::createRef("packed");
4585 }
4586
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004587 if (C.kind == CXCursor_VisibilityAttr) {
4588 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4589 switch (AA->getVisibility()) {
4590 case VisibilityAttr::VisibilityType::Default:
4591 return cxstring::createRef("default");
4592 case VisibilityAttr::VisibilityType::Hidden:
4593 return cxstring::createRef("hidden");
4594 case VisibilityAttr::VisibilityType::Protected:
4595 return cxstring::createRef("protected");
4596 }
4597 llvm_unreachable("unknown visibility type");
4598 }
4599
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004600 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004601}
4602
4603CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4604 unsigned pieceIndex,
4605 unsigned options) {
4606 if (clang_Cursor_isNull(C))
4607 return clang_getNullRange();
4608
4609 ASTContext &Ctx = getCursorContext(C);
4610
4611 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004612 const Stmt *S = getCursorStmt(C);
4613 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 if (pieceIndex > 0)
4615 return clang_getNullRange();
4616 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4617 }
4618
4619 return clang_getNullRange();
4620 }
4621
4622 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004623 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4625 if (pieceIndex >= ME->getNumSelectorLocs())
4626 return clang_getNullRange();
4627 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4628 }
4629 }
4630
4631 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4632 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004633 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4635 if (pieceIndex >= MD->getNumSelectorLocs())
4636 return clang_getNullRange();
4637 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4638 }
4639 }
4640
4641 if (C.kind == CXCursor_ObjCCategoryDecl ||
4642 C.kind == CXCursor_ObjCCategoryImplDecl) {
4643 if (pieceIndex > 0)
4644 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004645 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4647 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004648 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4650 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4651 }
4652
4653 if (C.kind == CXCursor_ModuleImportDecl) {
4654 if (pieceIndex > 0)
4655 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004656 if (const ImportDecl *ImportD =
4657 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4659 if (!Locs.empty())
4660 return cxloc::translateSourceRange(Ctx,
4661 SourceRange(Locs.front(), Locs.back()));
4662 }
4663 return clang_getNullRange();
4664 }
4665
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004666 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004667 C.kind == CXCursor_ConversionFunction ||
4668 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004669 if (pieceIndex > 0)
4670 return clang_getNullRange();
4671 if (const FunctionDecl *FD =
4672 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4673 DeclarationNameInfo FunctionName = FD->getNameInfo();
4674 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4675 }
4676 return clang_getNullRange();
4677 }
4678
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 // FIXME: A CXCursor_InclusionDirective should give the location of the
4680 // filename, but we don't keep track of this.
4681
4682 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4683 // but we don't keep track of this.
4684
4685 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4686 // but we don't keep track of this.
4687
4688 // Default handling, give the location of the cursor.
4689
4690 if (pieceIndex > 0)
4691 return clang_getNullRange();
4692
4693 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4694 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4695 return cxloc::translateSourceRange(Ctx, Loc);
4696}
4697
Eli Bendersky44a206f2014-07-31 18:04:56 +00004698CXString clang_Cursor_getMangling(CXCursor C) {
4699 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4700 return cxstring::createEmpty();
4701
Eli Bendersky44a206f2014-07-31 18:04:56 +00004702 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004703 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004704 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4705 return cxstring::createEmpty();
4706
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004707 ASTContext &Ctx = D->getASTContext();
4708 index::CodegenNameGenerator CGNameGen(Ctx);
4709 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004710}
4711
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004712CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4713 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4714 return nullptr;
4715
4716 const Decl *D = getCursorDecl(C);
4717 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4718 return nullptr;
4719
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004720 ASTContext &Ctx = D->getASTContext();
4721 index::CodegenNameGenerator CGNameGen(Ctx);
4722 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004723 return cxstring::createSet(Manglings);
4724}
4725
Dave Lee1a532c92017-09-22 16:58:57 +00004726CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4727 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4728 return nullptr;
4729
4730 const Decl *D = getCursorDecl(C);
4731 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4732 return nullptr;
4733
4734 ASTContext &Ctx = D->getASTContext();
4735 index::CodegenNameGenerator CGNameGen(Ctx);
4736 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4737 return cxstring::createSet(Manglings);
4738}
4739
Jonathan Coe45ef5032018-01-16 10:19:56 +00004740CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4741 if (clang_Cursor_isNull(C))
4742 return 0;
4743 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4744}
4745
4746void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4747 if (Policy)
4748 delete static_cast<PrintingPolicy *>(Policy);
4749}
4750
4751unsigned
4752clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4753 enum CXPrintingPolicyProperty Property) {
4754 if (!Policy)
4755 return 0;
4756
4757 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4758 switch (Property) {
4759 case CXPrintingPolicy_Indentation:
4760 return P->Indentation;
4761 case CXPrintingPolicy_SuppressSpecifiers:
4762 return P->SuppressSpecifiers;
4763 case CXPrintingPolicy_SuppressTagKeyword:
4764 return P->SuppressTagKeyword;
4765 case CXPrintingPolicy_IncludeTagDefinition:
4766 return P->IncludeTagDefinition;
4767 case CXPrintingPolicy_SuppressScope:
4768 return P->SuppressScope;
4769 case CXPrintingPolicy_SuppressUnwrittenScope:
4770 return P->SuppressUnwrittenScope;
4771 case CXPrintingPolicy_SuppressInitializers:
4772 return P->SuppressInitializers;
4773 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4774 return P->ConstantArraySizeAsWritten;
4775 case CXPrintingPolicy_AnonymousTagLocations:
4776 return P->AnonymousTagLocations;
4777 case CXPrintingPolicy_SuppressStrongLifetime:
4778 return P->SuppressStrongLifetime;
4779 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4780 return P->SuppressLifetimeQualifiers;
4781 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4782 return P->SuppressTemplateArgsInCXXConstructors;
4783 case CXPrintingPolicy_Bool:
4784 return P->Bool;
4785 case CXPrintingPolicy_Restrict:
4786 return P->Restrict;
4787 case CXPrintingPolicy_Alignof:
4788 return P->Alignof;
4789 case CXPrintingPolicy_UnderscoreAlignof:
4790 return P->UnderscoreAlignof;
4791 case CXPrintingPolicy_UseVoidForZeroParams:
4792 return P->UseVoidForZeroParams;
4793 case CXPrintingPolicy_TerseOutput:
4794 return P->TerseOutput;
4795 case CXPrintingPolicy_PolishForDeclaration:
4796 return P->PolishForDeclaration;
4797 case CXPrintingPolicy_Half:
4798 return P->Half;
4799 case CXPrintingPolicy_MSWChar:
4800 return P->MSWChar;
4801 case CXPrintingPolicy_IncludeNewlines:
4802 return P->IncludeNewlines;
4803 case CXPrintingPolicy_MSVCFormatting:
4804 return P->MSVCFormatting;
4805 case CXPrintingPolicy_ConstantsAsWritten:
4806 return P->ConstantsAsWritten;
4807 case CXPrintingPolicy_SuppressImplicitBase:
4808 return P->SuppressImplicitBase;
4809 case CXPrintingPolicy_FullyQualifiedName:
4810 return P->FullyQualifiedName;
4811 }
4812
4813 assert(false && "Invalid CXPrintingPolicyProperty");
4814 return 0;
4815}
4816
4817void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4818 enum CXPrintingPolicyProperty Property,
4819 unsigned Value) {
4820 if (!Policy)
4821 return;
4822
4823 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4824 switch (Property) {
4825 case CXPrintingPolicy_Indentation:
4826 P->Indentation = Value;
4827 return;
4828 case CXPrintingPolicy_SuppressSpecifiers:
4829 P->SuppressSpecifiers = Value;
4830 return;
4831 case CXPrintingPolicy_SuppressTagKeyword:
4832 P->SuppressTagKeyword = Value;
4833 return;
4834 case CXPrintingPolicy_IncludeTagDefinition:
4835 P->IncludeTagDefinition = Value;
4836 return;
4837 case CXPrintingPolicy_SuppressScope:
4838 P->SuppressScope = Value;
4839 return;
4840 case CXPrintingPolicy_SuppressUnwrittenScope:
4841 P->SuppressUnwrittenScope = Value;
4842 return;
4843 case CXPrintingPolicy_SuppressInitializers:
4844 P->SuppressInitializers = Value;
4845 return;
4846 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4847 P->ConstantArraySizeAsWritten = Value;
4848 return;
4849 case CXPrintingPolicy_AnonymousTagLocations:
4850 P->AnonymousTagLocations = Value;
4851 return;
4852 case CXPrintingPolicy_SuppressStrongLifetime:
4853 P->SuppressStrongLifetime = Value;
4854 return;
4855 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4856 P->SuppressLifetimeQualifiers = Value;
4857 return;
4858 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4859 P->SuppressTemplateArgsInCXXConstructors = Value;
4860 return;
4861 case CXPrintingPolicy_Bool:
4862 P->Bool = Value;
4863 return;
4864 case CXPrintingPolicy_Restrict:
4865 P->Restrict = Value;
4866 return;
4867 case CXPrintingPolicy_Alignof:
4868 P->Alignof = Value;
4869 return;
4870 case CXPrintingPolicy_UnderscoreAlignof:
4871 P->UnderscoreAlignof = Value;
4872 return;
4873 case CXPrintingPolicy_UseVoidForZeroParams:
4874 P->UseVoidForZeroParams = Value;
4875 return;
4876 case CXPrintingPolicy_TerseOutput:
4877 P->TerseOutput = Value;
4878 return;
4879 case CXPrintingPolicy_PolishForDeclaration:
4880 P->PolishForDeclaration = Value;
4881 return;
4882 case CXPrintingPolicy_Half:
4883 P->Half = Value;
4884 return;
4885 case CXPrintingPolicy_MSWChar:
4886 P->MSWChar = Value;
4887 return;
4888 case CXPrintingPolicy_IncludeNewlines:
4889 P->IncludeNewlines = Value;
4890 return;
4891 case CXPrintingPolicy_MSVCFormatting:
4892 P->MSVCFormatting = Value;
4893 return;
4894 case CXPrintingPolicy_ConstantsAsWritten:
4895 P->ConstantsAsWritten = Value;
4896 return;
4897 case CXPrintingPolicy_SuppressImplicitBase:
4898 P->SuppressImplicitBase = Value;
4899 return;
4900 case CXPrintingPolicy_FullyQualifiedName:
4901 P->FullyQualifiedName = Value;
4902 return;
4903 }
4904
4905 assert(false && "Invalid CXPrintingPolicyProperty");
4906}
4907
4908CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4909 if (clang_Cursor_isNull(C))
4910 return cxstring::createEmpty();
4911
4912 if (clang_isDeclaration(C.kind)) {
4913 const Decl *D = getCursorDecl(C);
4914 if (!D)
4915 return cxstring::createEmpty();
4916
4917 SmallString<128> Str;
4918 llvm::raw_svector_ostream OS(Str);
4919 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4920 D->print(OS, UserPolicy ? *UserPolicy
4921 : getCursorContext(C).getPrintingPolicy());
4922
4923 return cxstring::createDup(OS.str());
4924 }
4925
4926 return cxstring::createEmpty();
4927}
4928
Guy Benyei11169dd2012-12-18 14:30:41 +00004929CXString clang_getCursorDisplayName(CXCursor C) {
4930 if (!clang_isDeclaration(C.kind))
4931 return clang_getCursorSpelling(C);
4932
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004933 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004935 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004936
4937 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004938 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 D = FunTmpl->getTemplatedDecl();
4940
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004941 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004942 SmallString<64> Str;
4943 llvm::raw_svector_ostream OS(Str);
4944 OS << *Function;
4945 if (Function->getPrimaryTemplate())
4946 OS << "<>";
4947 OS << "(";
4948 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4949 if (I)
4950 OS << ", ";
4951 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4952 }
4953
4954 if (Function->isVariadic()) {
4955 if (Function->getNumParams())
4956 OS << ", ";
4957 OS << "...";
4958 }
4959 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004960 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 }
4962
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004963 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 SmallString<64> Str;
4965 llvm::raw_svector_ostream OS(Str);
4966 OS << *ClassTemplate;
4967 OS << "<";
4968 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4969 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4970 if (I)
4971 OS << ", ";
4972
4973 NamedDecl *Param = Params->getParam(I);
4974 if (Param->getIdentifier()) {
4975 OS << Param->getIdentifier()->getName();
4976 continue;
4977 }
4978
4979 // There is no parameter name, which makes this tricky. Try to come up
4980 // with something useful that isn't too long.
4981 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4982 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4983 else if (NonTypeTemplateParmDecl *NTTP
4984 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4985 OS << NTTP->getType().getAsString(Policy);
4986 else
4987 OS << "template<...> class";
4988 }
4989
4990 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004991 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004992 }
4993
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004994 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4996 // If the type was explicitly written, use that.
4997 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004998 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004999
Benjamin Kramer9170e912013-02-22 15:46:01 +00005000 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 llvm::raw_svector_ostream OS(Str);
5002 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005003 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5004 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005005 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 }
5007
5008 return clang_getCursorSpelling(C);
5009}
5010
5011CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5012 switch (Kind) {
5013 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005014 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005016 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005018 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005020 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005022 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005024 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005026 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005028 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005030 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005032 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005034 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005036 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005038 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005040 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005042 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005077 case CXCursor_FixedPointLiteral:
5078 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005093 case CXCursor_OMPArraySectionExpr:
5094 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005145 case CXCursor_ObjCAvailabilityCheckExpr:
5146 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005147 case CXCursor_ObjCSelfExpr:
5148 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005237 case CXCursor_SEHLeaveStmt:
5238 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005262 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005267 case CXCursor_PackedAttr:
5268 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005269 case CXCursor_PureAttr:
5270 return cxstring::createRef("attribute(pure)");
5271 case CXCursor_ConstAttr:
5272 return cxstring::createRef("attribute(const)");
5273 case CXCursor_NoDuplicateAttr:
5274 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005275 case CXCursor_CUDAConstantAttr:
5276 return cxstring::createRef("attribute(constant)");
5277 case CXCursor_CUDADeviceAttr:
5278 return cxstring::createRef("attribute(device)");
5279 case CXCursor_CUDAGlobalAttr:
5280 return cxstring::createRef("attribute(global)");
5281 case CXCursor_CUDAHostAttr:
5282 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005283 case CXCursor_CUDASharedAttr:
5284 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005285 case CXCursor_VisibilityAttr:
5286 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005287 case CXCursor_DLLExport:
5288 return cxstring::createRef("attribute(dllexport)");
5289 case CXCursor_DLLImport:
5290 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005291 case CXCursor_NSReturnsRetained:
5292 return cxstring::createRef("attribute(ns_returns_retained)");
5293 case CXCursor_NSReturnsNotRetained:
5294 return cxstring::createRef("attribute(ns_returns_not_retained)");
5295 case CXCursor_NSReturnsAutoreleased:
5296 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5297 case CXCursor_NSConsumesSelf:
5298 return cxstring::createRef("attribute(ns_consumes_self)");
5299 case CXCursor_NSConsumed:
5300 return cxstring::createRef("attribute(ns_consumed)");
5301 case CXCursor_ObjCException:
5302 return cxstring::createRef("attribute(objc_exception)");
5303 case CXCursor_ObjCNSObject:
5304 return cxstring::createRef("attribute(NSObject)");
5305 case CXCursor_ObjCIndependentClass:
5306 return cxstring::createRef("attribute(objc_independent_class)");
5307 case CXCursor_ObjCPreciseLifetime:
5308 return cxstring::createRef("attribute(objc_precise_lifetime)");
5309 case CXCursor_ObjCReturnsInnerPointer:
5310 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5311 case CXCursor_ObjCRequiresSuper:
5312 return cxstring::createRef("attribute(objc_requires_super)");
5313 case CXCursor_ObjCRootClass:
5314 return cxstring::createRef("attribute(objc_root_class)");
5315 case CXCursor_ObjCSubclassingRestricted:
5316 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5317 case CXCursor_ObjCExplicitProtocolImpl:
5318 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5319 case CXCursor_ObjCDesignatedInitializer:
5320 return cxstring::createRef("attribute(objc_designated_initializer)");
5321 case CXCursor_ObjCRuntimeVisible:
5322 return cxstring::createRef("attribute(objc_runtime_visible)");
5323 case CXCursor_ObjCBoxable:
5324 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005325 case CXCursor_FlagEnum:
5326 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005327 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005328 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005329 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005330 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005332 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005334 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005336 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005338 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005340 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005342 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005344 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005346 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005348 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005350 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005354 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005355 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005356 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005358 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005360 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005362 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005364 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005365 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005366 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005368 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005369 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005370 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005371 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005372 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005374 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005375 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005376 return cxstring::createRef("OMPParallelDirective");
5377 case CXCursor_OMPSimdDirective:
5378 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005379 case CXCursor_OMPForDirective:
5380 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005381 case CXCursor_OMPForSimdDirective:
5382 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005383 case CXCursor_OMPSectionsDirective:
5384 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005385 case CXCursor_OMPSectionDirective:
5386 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005387 case CXCursor_OMPSingleDirective:
5388 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005389 case CXCursor_OMPMasterDirective:
5390 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005391 case CXCursor_OMPCriticalDirective:
5392 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005393 case CXCursor_OMPParallelForDirective:
5394 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005395 case CXCursor_OMPParallelForSimdDirective:
5396 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005397 case CXCursor_OMPParallelSectionsDirective:
5398 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005399 case CXCursor_OMPTaskDirective:
5400 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005401 case CXCursor_OMPTaskyieldDirective:
5402 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005403 case CXCursor_OMPBarrierDirective:
5404 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005405 case CXCursor_OMPTaskwaitDirective:
5406 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005407 case CXCursor_OMPTaskgroupDirective:
5408 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005409 case CXCursor_OMPFlushDirective:
5410 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005411 case CXCursor_OMPOrderedDirective:
5412 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005413 case CXCursor_OMPAtomicDirective:
5414 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005415 case CXCursor_OMPTargetDirective:
5416 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005417 case CXCursor_OMPTargetDataDirective:
5418 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005419 case CXCursor_OMPTargetEnterDataDirective:
5420 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005421 case CXCursor_OMPTargetExitDataDirective:
5422 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005423 case CXCursor_OMPTargetParallelDirective:
5424 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005425 case CXCursor_OMPTargetParallelForDirective:
5426 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005427 case CXCursor_OMPTargetUpdateDirective:
5428 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005429 case CXCursor_OMPTeamsDirective:
5430 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005431 case CXCursor_OMPCancellationPointDirective:
5432 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005433 case CXCursor_OMPCancelDirective:
5434 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005435 case CXCursor_OMPTaskLoopDirective:
5436 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005437 case CXCursor_OMPTaskLoopSimdDirective:
5438 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005439 case CXCursor_OMPDistributeDirective:
5440 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005441 case CXCursor_OMPDistributeParallelForDirective:
5442 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005443 case CXCursor_OMPDistributeParallelForSimdDirective:
5444 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005445 case CXCursor_OMPDistributeSimdDirective:
5446 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005447 case CXCursor_OMPTargetParallelForSimdDirective:
5448 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005449 case CXCursor_OMPTargetSimdDirective:
5450 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005451 case CXCursor_OMPTeamsDistributeDirective:
5452 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005453 case CXCursor_OMPTeamsDistributeSimdDirective:
5454 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005455 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5456 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005457 case CXCursor_OMPTeamsDistributeParallelForDirective:
5458 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005459 case CXCursor_OMPTargetTeamsDirective:
5460 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005461 case CXCursor_OMPTargetTeamsDistributeDirective:
5462 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005463 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5464 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005465 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5466 return cxstring::createRef(
5467 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005468 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5469 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005470 case CXCursor_OverloadCandidate:
5471 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005472 case CXCursor_TypeAliasTemplateDecl:
5473 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005474 case CXCursor_StaticAssert:
5475 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005476 case CXCursor_FriendDecl:
5477 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005478 }
5479
5480 llvm_unreachable("Unhandled CXCursorKind");
5481}
5482
5483struct GetCursorData {
5484 SourceLocation TokenBeginLoc;
5485 bool PointsAtMacroArgExpansion;
5486 bool VisitedObjCPropertyImplDecl;
5487 SourceLocation VisitedDeclaratorDeclStartLoc;
5488 CXCursor &BestCursor;
5489
5490 GetCursorData(SourceManager &SM,
5491 SourceLocation tokenBegin, CXCursor &outputCursor)
5492 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5493 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5494 VisitedObjCPropertyImplDecl = false;
5495 }
5496};
5497
5498static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5499 CXCursor parent,
5500 CXClientData client_data) {
5501 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5502 CXCursor *BestCursor = &Data->BestCursor;
5503
5504 // If we point inside a macro argument we should provide info of what the
5505 // token is so use the actual cursor, don't replace it with a macro expansion
5506 // cursor.
5507 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5508 return CXChildVisit_Recurse;
5509
5510 if (clang_isDeclaration(cursor.kind)) {
5511 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005512 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5514 if (MD->isImplicit())
5515 return CXChildVisit_Break;
5516
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005517 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5519 // Check that when we have multiple @class references in the same line,
5520 // that later ones do not override the previous ones.
5521 // If we have:
5522 // @class Foo, Bar;
5523 // source ranges for both start at '@', so 'Bar' will end up overriding
5524 // 'Foo' even though the cursor location was at 'Foo'.
5525 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5526 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005527 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005528 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5529 if (PrevID != ID &&
5530 !PrevID->isThisDeclarationADefinition() &&
5531 !ID->isThisDeclarationADefinition())
5532 return CXChildVisit_Break;
5533 }
5534
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005535 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005536 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5537 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5538 // Check that when we have multiple declarators in the same line,
5539 // that later ones do not override the previous ones.
5540 // If we have:
5541 // int Foo, Bar;
5542 // source ranges for both start at 'int', so 'Bar' will end up overriding
5543 // 'Foo' even though the cursor location was at 'Foo'.
5544 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5545 return CXChildVisit_Break;
5546 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5547
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005548 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005549 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5550 (void)PropImp;
5551 // Check that when we have multiple @synthesize in the same line,
5552 // that later ones do not override the previous ones.
5553 // If we have:
5554 // @synthesize Foo, Bar;
5555 // source ranges for both start at '@', so 'Bar' will end up overriding
5556 // 'Foo' even though the cursor location was at 'Foo'.
5557 if (Data->VisitedObjCPropertyImplDecl)
5558 return CXChildVisit_Break;
5559 Data->VisitedObjCPropertyImplDecl = true;
5560 }
5561 }
5562
5563 if (clang_isExpression(cursor.kind) &&
5564 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005565 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005566 // Avoid having the cursor of an expression replace the declaration cursor
5567 // when the expression source range overlaps the declaration range.
5568 // This can happen for C++ constructor expressions whose range generally
5569 // include the variable declaration, e.g.:
5570 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5571 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5572 D->getLocation() == Data->TokenBeginLoc)
5573 return CXChildVisit_Break;
5574 }
5575 }
5576
5577 // If our current best cursor is the construction of a temporary object,
5578 // don't replace that cursor with a type reference, because we want
5579 // clang_getCursor() to point at the constructor.
5580 if (clang_isExpression(BestCursor->kind) &&
5581 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5582 cursor.kind == CXCursor_TypeRef) {
5583 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5584 // as having the actual point on the type reference.
5585 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5586 return CXChildVisit_Recurse;
5587 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005588
5589 // If we already have an Objective-C superclass reference, don't
5590 // update it further.
5591 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5592 return CXChildVisit_Break;
5593
Guy Benyei11169dd2012-12-18 14:30:41 +00005594 *BestCursor = cursor;
5595 return CXChildVisit_Recurse;
5596}
5597
5598CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005599 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005600 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005601 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005602 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005603
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005604 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005605 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5606
5607 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5608 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5609
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005610 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005611 CXFile SearchFile;
5612 unsigned SearchLine, SearchColumn;
5613 CXFile ResultFile;
5614 unsigned ResultLine, ResultColumn;
5615 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5616 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5617 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005618
5619 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5620 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005621 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005622 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005623 SearchFileName = clang_getFileName(SearchFile);
5624 ResultFileName = clang_getFileName(ResultFile);
5625 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5626 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005627 *Log << llvm::format("(%s:%d:%d) = %s",
5628 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5629 clang_getCString(KindSpelling))
5630 << llvm::format("(%s:%d:%d):%s%s",
5631 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5632 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005633 clang_disposeString(SearchFileName);
5634 clang_disposeString(ResultFileName);
5635 clang_disposeString(KindSpelling);
5636 clang_disposeString(USR);
5637
5638 CXCursor Definition = clang_getCursorDefinition(Result);
5639 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5640 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5641 CXString DefinitionKindSpelling
5642 = clang_getCursorKindSpelling(Definition.kind);
5643 CXFile DefinitionFile;
5644 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005645 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005646 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005647 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005648 *Log << llvm::format(" -> %s(%s:%d:%d)",
5649 clang_getCString(DefinitionKindSpelling),
5650 clang_getCString(DefinitionFileName),
5651 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005652 clang_disposeString(DefinitionFileName);
5653 clang_disposeString(DefinitionKindSpelling);
5654 }
5655 }
5656
5657 return Result;
5658}
5659
5660CXCursor clang_getNullCursor(void) {
5661 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5662}
5663
5664unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005665 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5666 // can't set consistently. For example, when visiting a DeclStmt we will set
5667 // it but we don't set it on the result of clang_getCursorDefinition for
5668 // a reference of the same declaration.
5669 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5670 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5671 // to provide that kind of info.
5672 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005673 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005674 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005675 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005676
Guy Benyei11169dd2012-12-18 14:30:41 +00005677 return X == Y;
5678}
5679
5680unsigned clang_hashCursor(CXCursor C) {
5681 unsigned Index = 0;
5682 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5683 Index = 1;
5684
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005685 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005686 std::make_pair(C.kind, C.data[Index]));
5687}
5688
5689unsigned clang_isInvalid(enum CXCursorKind K) {
5690 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5691}
5692
5693unsigned clang_isDeclaration(enum CXCursorKind K) {
5694 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005695 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5696}
5697
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005698unsigned clang_isInvalidDeclaration(CXCursor C) {
5699 if (clang_isDeclaration(C.kind)) {
5700 if (const Decl *D = getCursorDecl(C))
5701 return D->isInvalidDecl();
5702 }
5703
5704 return 0;
5705}
5706
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005707unsigned clang_isReference(enum CXCursorKind K) {
5708 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5709}
Guy Benyei11169dd2012-12-18 14:30:41 +00005710
5711unsigned clang_isExpression(enum CXCursorKind K) {
5712 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5713}
5714
5715unsigned clang_isStatement(enum CXCursorKind K) {
5716 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5717}
5718
5719unsigned clang_isAttribute(enum CXCursorKind K) {
5720 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5721}
5722
5723unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5724 return K == CXCursor_TranslationUnit;
5725}
5726
5727unsigned clang_isPreprocessing(enum CXCursorKind K) {
5728 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5729}
5730
5731unsigned clang_isUnexposed(enum CXCursorKind K) {
5732 switch (K) {
5733 case CXCursor_UnexposedDecl:
5734 case CXCursor_UnexposedExpr:
5735 case CXCursor_UnexposedStmt:
5736 case CXCursor_UnexposedAttr:
5737 return true;
5738 default:
5739 return false;
5740 }
5741}
5742
5743CXCursorKind clang_getCursorKind(CXCursor C) {
5744 return C.kind;
5745}
5746
5747CXSourceLocation clang_getCursorLocation(CXCursor C) {
5748 if (clang_isReference(C.kind)) {
5749 switch (C.kind) {
5750 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005751 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005752 = getCursorObjCSuperClassRef(C);
5753 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5754 }
5755
5756 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005757 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005758 = getCursorObjCProtocolRef(C);
5759 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5760 }
5761
5762 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005763 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 = getCursorObjCClassRef(C);
5765 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5766 }
5767
5768 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005769 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005770 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5771 }
5772
5773 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005774 std::pair<const TemplateDecl *, SourceLocation> P =
5775 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005776 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5777 }
5778
5779 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005780 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005781 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5782 }
5783
5784 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005785 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005786 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5787 }
5788
5789 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005790 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005791 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5792 }
5793
5794 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005795 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005796 if (!BaseSpec)
5797 return clang_getNullLocation();
5798
5799 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5800 return cxloc::translateSourceLocation(getCursorContext(C),
5801 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005802
Guy Benyei11169dd2012-12-18 14:30:41 +00005803 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005804 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005805 }
5806
5807 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005808 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005809 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5810 }
5811
5812 case CXCursor_OverloadedDeclRef:
5813 return cxloc::translateSourceLocation(getCursorContext(C),
5814 getCursorOverloadedDeclRef(C).second);
5815
5816 default:
5817 // FIXME: Need a way to enumerate all non-reference cases.
5818 llvm_unreachable("Missed a reference kind");
5819 }
5820 }
5821
5822 if (clang_isExpression(C.kind))
5823 return cxloc::translateSourceLocation(getCursorContext(C),
5824 getLocationFromExpr(getCursorExpr(C)));
5825
5826 if (clang_isStatement(C.kind))
5827 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005828 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005829
5830 if (C.kind == CXCursor_PreprocessingDirective) {
5831 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5832 return cxloc::translateSourceLocation(getCursorContext(C), L);
5833 }
5834
5835 if (C.kind == CXCursor_MacroExpansion) {
5836 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005837 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005838 return cxloc::translateSourceLocation(getCursorContext(C), L);
5839 }
5840
5841 if (C.kind == CXCursor_MacroDefinition) {
5842 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5843 return cxloc::translateSourceLocation(getCursorContext(C), L);
5844 }
5845
5846 if (C.kind == CXCursor_InclusionDirective) {
5847 SourceLocation L
5848 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5849 return cxloc::translateSourceLocation(getCursorContext(C), L);
5850 }
5851
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005852 if (clang_isAttribute(C.kind)) {
5853 SourceLocation L
5854 = cxcursor::getCursorAttr(C)->getLocation();
5855 return cxloc::translateSourceLocation(getCursorContext(C), L);
5856 }
5857
Guy Benyei11169dd2012-12-18 14:30:41 +00005858 if (!clang_isDeclaration(C.kind))
5859 return clang_getNullLocation();
5860
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005861 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005862 if (!D)
5863 return clang_getNullLocation();
5864
5865 SourceLocation Loc = D->getLocation();
5866 // FIXME: Multiple variables declared in a single declaration
5867 // currently lack the information needed to correctly determine their
5868 // ranges when accounting for the type-specifier. We use context
5869 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5870 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005871 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005872 if (!cxcursor::isFirstInDeclGroup(C))
5873 Loc = VD->getLocation();
5874 }
5875
5876 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005877 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005878 Loc = MD->getSelectorStartLoc();
5879
5880 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5881}
5882
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005883} // end extern "C"
5884
Guy Benyei11169dd2012-12-18 14:30:41 +00005885CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5886 assert(TU);
5887
5888 // Guard against an invalid SourceLocation, or we may assert in one
5889 // of the following calls.
5890 if (SLoc.isInvalid())
5891 return clang_getNullCursor();
5892
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005893 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005894
5895 // Translate the given source location to make it point at the beginning of
5896 // the token under the cursor.
5897 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5898 CXXUnit->getASTContext().getLangOpts());
5899
5900 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5901 if (SLoc.isValid()) {
5902 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5903 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5904 /*VisitPreprocessorLast=*/true,
5905 /*VisitIncludedEntities=*/false,
5906 SourceLocation(SLoc));
5907 CursorVis.visitFileRegion();
5908 }
5909
5910 return Result;
5911}
5912
5913static SourceRange getRawCursorExtent(CXCursor C) {
5914 if (clang_isReference(C.kind)) {
5915 switch (C.kind) {
5916 case CXCursor_ObjCSuperClassRef:
5917 return getCursorObjCSuperClassRef(C).second;
5918
5919 case CXCursor_ObjCProtocolRef:
5920 return getCursorObjCProtocolRef(C).second;
5921
5922 case CXCursor_ObjCClassRef:
5923 return getCursorObjCClassRef(C).second;
5924
5925 case CXCursor_TypeRef:
5926 return getCursorTypeRef(C).second;
5927
5928 case CXCursor_TemplateRef:
5929 return getCursorTemplateRef(C).second;
5930
5931 case CXCursor_NamespaceRef:
5932 return getCursorNamespaceRef(C).second;
5933
5934 case CXCursor_MemberRef:
5935 return getCursorMemberRef(C).second;
5936
5937 case CXCursor_CXXBaseSpecifier:
5938 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5939
5940 case CXCursor_LabelRef:
5941 return getCursorLabelRef(C).second;
5942
5943 case CXCursor_OverloadedDeclRef:
5944 return getCursorOverloadedDeclRef(C).second;
5945
5946 case CXCursor_VariableRef:
5947 return getCursorVariableRef(C).second;
5948
5949 default:
5950 // FIXME: Need a way to enumerate all non-reference cases.
5951 llvm_unreachable("Missed a reference kind");
5952 }
5953 }
5954
5955 if (clang_isExpression(C.kind))
5956 return getCursorExpr(C)->getSourceRange();
5957
5958 if (clang_isStatement(C.kind))
5959 return getCursorStmt(C)->getSourceRange();
5960
5961 if (clang_isAttribute(C.kind))
5962 return getCursorAttr(C)->getRange();
5963
5964 if (C.kind == CXCursor_PreprocessingDirective)
5965 return cxcursor::getCursorPreprocessingDirective(C);
5966
5967 if (C.kind == CXCursor_MacroExpansion) {
5968 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005969 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 return TU->mapRangeFromPreamble(Range);
5971 }
5972
5973 if (C.kind == CXCursor_MacroDefinition) {
5974 ASTUnit *TU = getCursorASTUnit(C);
5975 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5976 return TU->mapRangeFromPreamble(Range);
5977 }
5978
5979 if (C.kind == CXCursor_InclusionDirective) {
5980 ASTUnit *TU = getCursorASTUnit(C);
5981 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5982 return TU->mapRangeFromPreamble(Range);
5983 }
5984
5985 if (C.kind == CXCursor_TranslationUnit) {
5986 ASTUnit *TU = getCursorASTUnit(C);
5987 FileID MainID = TU->getSourceManager().getMainFileID();
5988 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5989 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5990 return SourceRange(Start, End);
5991 }
5992
5993 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005994 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005995 if (!D)
5996 return SourceRange();
5997
5998 SourceRange R = D->getSourceRange();
5999 // FIXME: Multiple variables declared in a single declaration
6000 // currently lack the information needed to correctly determine their
6001 // ranges when accounting for the type-specifier. We use context
6002 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6003 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006004 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006005 if (!cxcursor::isFirstInDeclGroup(C))
6006 R.setBegin(VD->getLocation());
6007 }
6008 return R;
6009 }
6010 return SourceRange();
6011}
6012
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006013/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006014/// the decl-specifier-seq for declarations.
6015static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6016 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006017 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006018 if (!D)
6019 return SourceRange();
6020
6021 SourceRange R = D->getSourceRange();
6022
6023 // Adjust the start of the location for declarations preceded by
6024 // declaration specifiers.
6025 SourceLocation StartLoc;
6026 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6027 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006028 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006029 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006030 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006031 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006032 }
6033
6034 if (StartLoc.isValid() && R.getBegin().isValid() &&
6035 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6036 R.setBegin(StartLoc);
6037
6038 // FIXME: Multiple variables declared in a single declaration
6039 // currently lack the information needed to correctly determine their
6040 // ranges when accounting for the type-specifier. We use context
6041 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6042 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006043 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006044 if (!cxcursor::isFirstInDeclGroup(C))
6045 R.setBegin(VD->getLocation());
6046 }
6047
6048 return R;
6049 }
6050
6051 return getRawCursorExtent(C);
6052}
6053
Guy Benyei11169dd2012-12-18 14:30:41 +00006054CXSourceRange clang_getCursorExtent(CXCursor C) {
6055 SourceRange R = getRawCursorExtent(C);
6056 if (R.isInvalid())
6057 return clang_getNullRange();
6058
6059 return cxloc::translateSourceRange(getCursorContext(C), R);
6060}
6061
6062CXCursor clang_getCursorReferenced(CXCursor C) {
6063 if (clang_isInvalid(C.kind))
6064 return clang_getNullCursor();
6065
6066 CXTranslationUnit tu = getCursorTU(C);
6067 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006068 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006069 if (!D)
6070 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006071 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006072 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006073 if (const ObjCPropertyImplDecl *PropImpl =
6074 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6076 return MakeCXCursor(Property, tu);
6077
6078 return C;
6079 }
6080
6081 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006082 const Expr *E = getCursorExpr(C);
6083 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006084 if (D) {
6085 CXCursor declCursor = MakeCXCursor(D, tu);
6086 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6087 declCursor);
6088 return declCursor;
6089 }
6090
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006091 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006092 return MakeCursorOverloadedDeclRef(Ovl, tu);
6093
6094 return clang_getNullCursor();
6095 }
6096
6097 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006098 const Stmt *S = getCursorStmt(C);
6099 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006100 if (LabelDecl *label = Goto->getLabel())
6101 if (LabelStmt *labelS = label->getStmt())
6102 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6103
6104 return clang_getNullCursor();
6105 }
Richard Smith66a81862015-05-04 02:25:31 +00006106
Guy Benyei11169dd2012-12-18 14:30:41 +00006107 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006108 if (const MacroDefinitionRecord *Def =
6109 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006110 return MakeMacroDefinitionCursor(Def, tu);
6111 }
6112
6113 if (!clang_isReference(C.kind))
6114 return clang_getNullCursor();
6115
6116 switch (C.kind) {
6117 case CXCursor_ObjCSuperClassRef:
6118 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6119
6120 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006121 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6122 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006123 return MakeCXCursor(Def, tu);
6124
6125 return MakeCXCursor(Prot, tu);
6126 }
6127
6128 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006129 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6130 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006131 return MakeCXCursor(Def, tu);
6132
6133 return MakeCXCursor(Class, tu);
6134 }
6135
6136 case CXCursor_TypeRef:
6137 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6138
6139 case CXCursor_TemplateRef:
6140 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6141
6142 case CXCursor_NamespaceRef:
6143 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6144
6145 case CXCursor_MemberRef:
6146 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6147
6148 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006149 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006150 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6151 tu ));
6152 }
6153
6154 case CXCursor_LabelRef:
6155 // FIXME: We end up faking the "parent" declaration here because we
6156 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006157 return MakeCXCursor(getCursorLabelRef(C).first,
6158 cxtu::getASTUnit(tu)->getASTContext()
6159 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006160 tu);
6161
6162 case CXCursor_OverloadedDeclRef:
6163 return C;
6164
6165 case CXCursor_VariableRef:
6166 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6167
6168 default:
6169 // We would prefer to enumerate all non-reference cursor kinds here.
6170 llvm_unreachable("Unhandled reference cursor kind");
6171 }
6172}
6173
6174CXCursor clang_getCursorDefinition(CXCursor C) {
6175 if (clang_isInvalid(C.kind))
6176 return clang_getNullCursor();
6177
6178 CXTranslationUnit TU = getCursorTU(C);
6179
6180 bool WasReference = false;
6181 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6182 C = clang_getCursorReferenced(C);
6183 WasReference = true;
6184 }
6185
6186 if (C.kind == CXCursor_MacroExpansion)
6187 return clang_getCursorReferenced(C);
6188
6189 if (!clang_isDeclaration(C.kind))
6190 return clang_getNullCursor();
6191
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006192 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006193 if (!D)
6194 return clang_getNullCursor();
6195
6196 switch (D->getKind()) {
6197 // Declaration kinds that don't really separate the notions of
6198 // declaration and definition.
6199 case Decl::Namespace:
6200 case Decl::Typedef:
6201 case Decl::TypeAlias:
6202 case Decl::TypeAliasTemplate:
6203 case Decl::TemplateTypeParm:
6204 case Decl::EnumConstant:
6205 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006206 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006207 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006208 case Decl::IndirectField:
6209 case Decl::ObjCIvar:
6210 case Decl::ObjCAtDefsField:
6211 case Decl::ImplicitParam:
6212 case Decl::ParmVar:
6213 case Decl::NonTypeTemplateParm:
6214 case Decl::TemplateTemplateParm:
6215 case Decl::ObjCCategoryImpl:
6216 case Decl::ObjCImplementation:
6217 case Decl::AccessSpec:
6218 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006219 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006220 case Decl::ObjCPropertyImpl:
6221 case Decl::FileScopeAsm:
6222 case Decl::StaticAssert:
6223 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006224 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006225 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006226 case Decl::Label: // FIXME: Is this right??
6227 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006228 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006230 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006231 case Decl::OMPDeclareReduction:
Kelvin Li1408f912018-09-26 04:28:39 +00006232 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006233 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006234 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006235 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006236 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006237 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006238 return C;
6239
6240 // Declaration kinds that don't make any sense here, but are
6241 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006242 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006243 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006244 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006245 break;
6246
6247 // Declaration kinds for which the definition is not resolvable.
6248 case Decl::UnresolvedUsingTypename:
6249 case Decl::UnresolvedUsingValue:
6250 break;
6251
6252 case Decl::UsingDirective:
6253 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6254 TU);
6255
6256 case Decl::NamespaceAlias:
6257 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6258
6259 case Decl::Enum:
6260 case Decl::Record:
6261 case Decl::CXXRecord:
6262 case Decl::ClassTemplateSpecialization:
6263 case Decl::ClassTemplatePartialSpecialization:
6264 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6265 return MakeCXCursor(Def, TU);
6266 return clang_getNullCursor();
6267
6268 case Decl::Function:
6269 case Decl::CXXMethod:
6270 case Decl::CXXConstructor:
6271 case Decl::CXXDestructor:
6272 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006273 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006274 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006275 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006276 return clang_getNullCursor();
6277 }
6278
Larisse Voufo39a1e502013-08-06 01:03:05 +00006279 case Decl::Var:
6280 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006281 case Decl::VarTemplatePartialSpecialization:
6282 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006284 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006285 return MakeCXCursor(Def, TU);
6286 return clang_getNullCursor();
6287 }
6288
6289 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006290 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006291 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6292 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6293 return clang_getNullCursor();
6294 }
6295
6296 case Decl::ClassTemplate: {
6297 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6298 ->getDefinition())
6299 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6300 TU);
6301 return clang_getNullCursor();
6302 }
6303
Larisse Voufo39a1e502013-08-06 01:03:05 +00006304 case Decl::VarTemplate: {
6305 if (VarDecl *Def =
6306 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6307 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6308 return clang_getNullCursor();
6309 }
6310
Guy Benyei11169dd2012-12-18 14:30:41 +00006311 case Decl::Using:
6312 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6313 D->getLocation(), TU);
6314
6315 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006316 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006317 return clang_getCursorDefinition(
6318 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6319 TU));
6320
6321 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006322 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006323 if (Method->isThisDeclarationADefinition())
6324 return C;
6325
6326 // Dig out the method definition in the associated
6327 // @implementation, if we have it.
6328 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006329 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6331 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6332 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6333 Method->isInstanceMethod()))
6334 if (Def->isThisDeclarationADefinition())
6335 return MakeCXCursor(Def, TU);
6336
6337 return clang_getNullCursor();
6338 }
6339
6340 case Decl::ObjCCategory:
6341 if (ObjCCategoryImplDecl *Impl
6342 = cast<ObjCCategoryDecl>(D)->getImplementation())
6343 return MakeCXCursor(Impl, TU);
6344 return clang_getNullCursor();
6345
6346 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006347 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006348 return MakeCXCursor(Def, TU);
6349 return clang_getNullCursor();
6350
6351 case Decl::ObjCInterface: {
6352 // There are two notions of a "definition" for an Objective-C
6353 // class: the interface and its implementation. When we resolved a
6354 // reference to an Objective-C class, produce the @interface as
6355 // the definition; when we were provided with the interface,
6356 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006357 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006358 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006359 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006360 return MakeCXCursor(Def, TU);
6361 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6362 return MakeCXCursor(Impl, TU);
6363 return clang_getNullCursor();
6364 }
6365
6366 case Decl::ObjCProperty:
6367 // FIXME: We don't really know where to find the
6368 // ObjCPropertyImplDecls that implement this property.
6369 return clang_getNullCursor();
6370
6371 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006372 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006373 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006374 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 return MakeCXCursor(Def, TU);
6376
6377 return clang_getNullCursor();
6378
6379 case Decl::Friend:
6380 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6381 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6382 return clang_getNullCursor();
6383
6384 case Decl::FriendTemplate:
6385 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6386 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6387 return clang_getNullCursor();
6388 }
6389
6390 return clang_getNullCursor();
6391}
6392
6393unsigned clang_isCursorDefinition(CXCursor C) {
6394 if (!clang_isDeclaration(C.kind))
6395 return 0;
6396
6397 return clang_getCursorDefinition(C) == C;
6398}
6399
6400CXCursor clang_getCanonicalCursor(CXCursor C) {
6401 if (!clang_isDeclaration(C.kind))
6402 return C;
6403
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006404 if (const Decl *D = getCursorDecl(C)) {
6405 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6407 return MakeCXCursor(CatD, getCursorTU(C));
6408
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006409 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6410 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006411 return MakeCXCursor(IFD, getCursorTU(C));
6412
6413 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6414 }
6415
6416 return C;
6417}
6418
6419int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6420 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6421}
6422
6423unsigned clang_getNumOverloadedDecls(CXCursor C) {
6424 if (C.kind != CXCursor_OverloadedDeclRef)
6425 return 0;
6426
6427 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006428 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006429 return E->getNumDecls();
6430
6431 if (OverloadedTemplateStorage *S
6432 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6433 return S->size();
6434
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006435 const Decl *D = Storage.get<const Decl *>();
6436 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006437 return Using->shadow_size();
6438
6439 return 0;
6440}
6441
6442CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6443 if (cursor.kind != CXCursor_OverloadedDeclRef)
6444 return clang_getNullCursor();
6445
6446 if (index >= clang_getNumOverloadedDecls(cursor))
6447 return clang_getNullCursor();
6448
6449 CXTranslationUnit TU = getCursorTU(cursor);
6450 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006451 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006452 return MakeCXCursor(E->decls_begin()[index], TU);
6453
6454 if (OverloadedTemplateStorage *S
6455 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6456 return MakeCXCursor(S->begin()[index], TU);
6457
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006458 const Decl *D = Storage.get<const Decl *>();
6459 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006460 // FIXME: This is, unfortunately, linear time.
6461 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6462 std::advance(Pos, index);
6463 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6464 }
6465
6466 return clang_getNullCursor();
6467}
6468
6469void clang_getDefinitionSpellingAndExtent(CXCursor C,
6470 const char **startBuf,
6471 const char **endBuf,
6472 unsigned *startLine,
6473 unsigned *startColumn,
6474 unsigned *endLine,
6475 unsigned *endColumn) {
6476 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006477 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006478 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6479
6480 SourceManager &SM = FD->getASTContext().getSourceManager();
6481 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6482 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6483 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6484 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6485 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6486 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6487}
6488
6489
6490CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6491 unsigned PieceIndex) {
6492 RefNamePieces Pieces;
6493
6494 switch (C.kind) {
6495 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006496 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6498 E->getQualifierLoc().getSourceRange());
6499 break;
6500
6501 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006502 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6503 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6504 Pieces =
6505 buildPieces(NameFlags, false, E->getNameInfo(),
6506 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6507 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006508 break;
6509
6510 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006511 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006512 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006513 const Expr *Callee = OCE->getCallee();
6514 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006515 Callee = ICE->getSubExpr();
6516
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006517 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006518 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6519 DRE->getQualifierLoc().getSourceRange());
6520 }
6521 break;
6522
6523 default:
6524 break;
6525 }
6526
6527 if (Pieces.empty()) {
6528 if (PieceIndex == 0)
6529 return clang_getCursorExtent(C);
6530 } else if (PieceIndex < Pieces.size()) {
6531 SourceRange R = Pieces[PieceIndex];
6532 if (R.isValid())
6533 return cxloc::translateSourceRange(getCursorContext(C), R);
6534 }
6535
6536 return clang_getNullRange();
6537}
6538
6539void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006540 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6541 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006542}
6543
6544void clang_executeOnThread(void (*fn)(void*), void *user_data,
6545 unsigned stack_size) {
6546 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6547}
6548
Guy Benyei11169dd2012-12-18 14:30:41 +00006549//===----------------------------------------------------------------------===//
6550// Token-based Operations.
6551//===----------------------------------------------------------------------===//
6552
6553/* CXToken layout:
6554 * int_data[0]: a CXTokenKind
6555 * int_data[1]: starting token location
6556 * int_data[2]: token length
6557 * int_data[3]: reserved
6558 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6559 * otherwise unused.
6560 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006561CXTokenKind clang_getTokenKind(CXToken CXTok) {
6562 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6563}
6564
6565CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6566 switch (clang_getTokenKind(CXTok)) {
6567 case CXToken_Identifier:
6568 case CXToken_Keyword:
6569 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006570 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006571 ->getNameStart());
6572
6573 case CXToken_Literal: {
6574 // We have stashed the starting pointer in the ptr_data field. Use it.
6575 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006576 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006577 }
6578
6579 case CXToken_Punctuation:
6580 case CXToken_Comment:
6581 break;
6582 }
6583
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006584 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006585 LOG_BAD_TU(TU);
6586 return cxstring::createEmpty();
6587 }
6588
Guy Benyei11169dd2012-12-18 14:30:41 +00006589 // We have to find the starting buffer pointer the hard way, by
6590 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006591 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006593 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006594
6595 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6596 std::pair<FileID, unsigned> LocInfo
6597 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6598 bool Invalid = false;
6599 StringRef Buffer
6600 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6601 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006602 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006603
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006604 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006605}
6606
6607CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006608 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006609 LOG_BAD_TU(TU);
6610 return clang_getNullLocation();
6611 }
6612
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006613 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 if (!CXXUnit)
6615 return clang_getNullLocation();
6616
6617 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6618 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6619}
6620
6621CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006622 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006623 LOG_BAD_TU(TU);
6624 return clang_getNullRange();
6625 }
6626
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006627 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 if (!CXXUnit)
6629 return clang_getNullRange();
6630
6631 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6632 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6633}
6634
6635static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6636 SmallVectorImpl<CXToken> &CXTokens) {
6637 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6638 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006639 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006641 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006642
6643 // Cannot tokenize across files.
6644 if (BeginLocInfo.first != EndLocInfo.first)
6645 return;
6646
6647 // Create a lexer
6648 bool Invalid = false;
6649 StringRef Buffer
6650 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6651 if (Invalid)
6652 return;
6653
6654 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6655 CXXUnit->getASTContext().getLangOpts(),
6656 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6657 Lex.SetCommentRetentionState(true);
6658
6659 // Lex tokens until we hit the end of the range.
6660 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6661 Token Tok;
6662 bool previousWasAt = false;
6663 do {
6664 // Lex the next token
6665 Lex.LexFromRawLexer(Tok);
6666 if (Tok.is(tok::eof))
6667 break;
6668
6669 // Initialize the CXToken.
6670 CXToken CXTok;
6671
6672 // - Common fields
6673 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6674 CXTok.int_data[2] = Tok.getLength();
6675 CXTok.int_data[3] = 0;
6676
6677 // - Kind-specific fields
6678 if (Tok.isLiteral()) {
6679 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006680 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006681 } else if (Tok.is(tok::raw_identifier)) {
6682 // Lookup the identifier to determine whether we have a keyword.
6683 IdentifierInfo *II
6684 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6685
6686 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6687 CXTok.int_data[0] = CXToken_Keyword;
6688 }
6689 else {
6690 CXTok.int_data[0] = Tok.is(tok::identifier)
6691 ? CXToken_Identifier
6692 : CXToken_Keyword;
6693 }
6694 CXTok.ptr_data = II;
6695 } else if (Tok.is(tok::comment)) {
6696 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006697 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006698 } else {
6699 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006700 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006701 }
6702 CXTokens.push_back(CXTok);
6703 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006704 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006705}
6706
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006707CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6708 LOG_FUNC_SECTION {
6709 *Log << TU << ' ' << Location;
6710 }
6711
6712 if (isNotUsableTU(TU)) {
6713 LOG_BAD_TU(TU);
6714 return NULL;
6715 }
6716
6717 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6718 if (!CXXUnit)
6719 return NULL;
6720
6721 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6722 if (Begin.isInvalid())
6723 return NULL;
6724 SourceManager &SM = CXXUnit->getSourceManager();
6725 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6726 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6727
6728 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6729
6730 SmallVector<CXToken, 32> CXTokens;
6731 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6732
6733 if (CXTokens.empty())
6734 return NULL;
6735
6736 CXTokens.resize(1);
6737 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6738
6739 memmove(Token, CXTokens.data(), sizeof(CXToken));
6740 return Token;
6741}
6742
Guy Benyei11169dd2012-12-18 14:30:41 +00006743void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6744 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006745 LOG_FUNC_SECTION {
6746 *Log << TU << ' ' << Range;
6747 }
6748
Guy Benyei11169dd2012-12-18 14:30:41 +00006749 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006750 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006751 if (NumTokens)
6752 *NumTokens = 0;
6753
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006754 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006755 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006756 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006757 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006758
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006759 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006760 if (!CXXUnit || !Tokens || !NumTokens)
6761 return;
6762
6763 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6764
6765 SourceRange R = cxloc::translateCXSourceRange(Range);
6766 if (R.isInvalid())
6767 return;
6768
6769 SmallVector<CXToken, 32> CXTokens;
6770 getTokens(CXXUnit, R, CXTokens);
6771
6772 if (CXTokens.empty())
6773 return;
6774
Serge Pavlov52525732018-02-21 02:02:39 +00006775 *Tokens = static_cast<CXToken *>(
6776 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6778 *NumTokens = CXTokens.size();
6779}
6780
6781void clang_disposeTokens(CXTranslationUnit TU,
6782 CXToken *Tokens, unsigned NumTokens) {
6783 free(Tokens);
6784}
6785
Guy Benyei11169dd2012-12-18 14:30:41 +00006786//===----------------------------------------------------------------------===//
6787// Token annotation APIs.
6788//===----------------------------------------------------------------------===//
6789
Guy Benyei11169dd2012-12-18 14:30:41 +00006790static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6791 CXCursor parent,
6792 CXClientData client_data);
6793static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6794 CXClientData client_data);
6795
6796namespace {
6797class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006798 CXToken *Tokens;
6799 CXCursor *Cursors;
6800 unsigned NumTokens;
6801 unsigned TokIdx;
6802 unsigned PreprocessingTokIdx;
6803 CursorVisitor AnnotateVis;
6804 SourceManager &SrcMgr;
6805 bool HasContextSensitiveKeywords;
6806
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006807 struct PostChildrenAction {
6808 CXCursor cursor;
6809 enum Action { Invalid, Ignore, Postpone } action;
6810 };
6811 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6812
Guy Benyei11169dd2012-12-18 14:30:41 +00006813 struct PostChildrenInfo {
6814 CXCursor Cursor;
6815 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006816 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006817 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006818 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006819 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006820 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006821
6822 CXToken &getTok(unsigned Idx) {
6823 assert(Idx < NumTokens);
6824 return Tokens[Idx];
6825 }
6826 const CXToken &getTok(unsigned Idx) const {
6827 assert(Idx < NumTokens);
6828 return Tokens[Idx];
6829 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006830 bool MoreTokens() const { return TokIdx < NumTokens; }
6831 unsigned NextToken() const { return TokIdx; }
6832 void AdvanceToken() { ++TokIdx; }
6833 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006834 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006835 }
6836 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006837 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006838 }
6839 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006840 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006841 }
6842
6843 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006844 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006845 SourceRange);
6846
6847public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006848 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006849 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006850 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006851 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006852 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 AnnotateTokensVisitor, this,
6854 /*VisitPreprocessorLast=*/true,
6855 /*VisitIncludedEntities=*/false,
6856 RegionOfInterest,
6857 /*VisitDeclsOnly=*/false,
6858 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006859 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 HasContextSensitiveKeywords(false) { }
6861
6862 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6863 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006864 bool IsIgnoredChildCursor(CXCursor cursor) const;
6865 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6866
Guy Benyei11169dd2012-12-18 14:30:41 +00006867 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006868 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6869 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6870
Guy Benyei11169dd2012-12-18 14:30:41 +00006871 void AnnotateTokens();
6872
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006873 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006874 /// context-sensitive keywords.
6875 bool hasContextSensitiveKeywords() const {
6876 return HasContextSensitiveKeywords;
6877 }
6878
6879 ~AnnotateTokensWorker() {
6880 assert(PostChildrenInfos.empty());
6881 }
6882};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006883}
Guy Benyei11169dd2012-12-18 14:30:41 +00006884
6885void AnnotateTokensWorker::AnnotateTokens() {
6886 // Walk the AST within the region of interest, annotating tokens
6887 // along the way.
6888 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006889}
Guy Benyei11169dd2012-12-18 14:30:41 +00006890
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006891bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6892 if (PostChildrenInfos.empty())
6893 return false;
6894
6895 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6896 if (ChildAction.cursor == cursor &&
6897 ChildAction.action == PostChildrenAction::Ignore) {
6898 return true;
6899 }
6900 }
6901
6902 return false;
6903}
6904
6905const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6906 if (!clang_isExpression(Cursor.kind))
6907 return nullptr;
6908
6909 const Expr *E = getCursorExpr(Cursor);
6910 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6911 const OverloadedOperatorKind Kind = OCE->getOperator();
6912 if (Kind == OO_Call || Kind == OO_Subscript)
6913 return OCE;
6914 }
6915
6916 return nullptr;
6917}
6918
6919AnnotateTokensWorker::PostChildrenActions
6920AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6921 PostChildrenActions actions;
6922
6923 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6924 // visited before the arguments to the operator call. For the Call and
6925 // Subscript operator the range of this DeclRefExpr includes the whole call
6926 // expression, so that all tokens in that range would be mapped to the
6927 // operator function, including the tokens of the arguments. To avoid that,
6928 // ensure to visit this DeclRefExpr as last node.
6929 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6930 const Expr *Callee = OCE->getCallee();
6931 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6932 const Expr *SubExpr = ICE->getSubExpr();
6933 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00006934 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006935 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6936
6937 // Visit the DeclRefExpr as last.
6938 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6939 actions.push_back({cxChild, PostChildrenAction::Postpone});
6940
6941 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6942 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6943 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6944 actions.push_back({cxChild, PostChildrenAction::Ignore});
6945 }
6946 }
6947 }
6948
6949 return actions;
6950}
6951
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006952static inline void updateCursorAnnotation(CXCursor &Cursor,
6953 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006954 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006956 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006957}
6958
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006959/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006960//// between the cursor location and the source range is the same as
6961/// \arg compResult.
6962///
6963/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6964/// Pass RangeOverlap to annotate tokens inside a range.
6965void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6966 RangeComparisonResult compResult,
6967 SourceRange range) {
6968 while (MoreTokens()) {
6969 const unsigned I = NextToken();
6970 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006971 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6972 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006973
6974 SourceLocation TokLoc = GetTokenLoc(I);
6975 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006976 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006977 AdvanceToken();
6978 continue;
6979 }
6980 break;
6981 }
6982}
6983
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006984/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006985/// \returns true if it advanced beyond all macro tokens, false otherwise.
6986bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006987 CXCursor updateC,
6988 RangeComparisonResult compResult,
6989 SourceRange range) {
6990 assert(MoreTokens());
6991 assert(isFunctionMacroToken(NextToken()) &&
6992 "Should be called only for macro arg tokens");
6993
6994 // This works differently than annotateAndAdvanceTokens; because expanded
6995 // macro arguments can have arbitrary translation-unit source order, we do not
6996 // advance the token index one by one until a token fails the range test.
6997 // We only advance once past all of the macro arg tokens if all of them
6998 // pass the range test. If one of them fails we keep the token index pointing
6999 // at the start of the macro arg tokens so that the failing token will be
7000 // annotated by a subsequent annotation try.
7001
7002 bool atLeastOneCompFail = false;
7003
7004 unsigned I = NextToken();
7005 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7006 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7007 if (TokLoc.isFileID())
7008 continue; // not macro arg token, it's parens or comma.
7009 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7010 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7011 Cursors[I] = updateC;
7012 } else
7013 atLeastOneCompFail = true;
7014 }
7015
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007016 if (atLeastOneCompFail)
7017 return false;
7018
7019 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7020 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007021}
7022
7023enum CXChildVisitResult
7024AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007025 SourceRange cursorRange = getRawCursorExtent(cursor);
7026 if (cursorRange.isInvalid())
7027 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007028
7029 if (IsIgnoredChildCursor(cursor))
7030 return CXChildVisit_Continue;
7031
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 if (!HasContextSensitiveKeywords) {
7033 // Objective-C properties can have context-sensitive keywords.
7034 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007035 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007036 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7037 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7038 }
7039 // Objective-C methods can have context-sensitive keywords.
7040 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7041 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007042 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007043 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7044 if (Method->getObjCDeclQualifier())
7045 HasContextSensitiveKeywords = true;
7046 else {
David Majnemer59f77922016-06-24 04:05:48 +00007047 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007048 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007049 HasContextSensitiveKeywords = true;
7050 break;
7051 }
7052 }
7053 }
7054 }
7055 }
7056 // C++ methods can have context-sensitive keywords.
7057 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007058 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007059 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7060 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7061 HasContextSensitiveKeywords = true;
7062 }
7063 }
7064 // C++ classes can have context-sensitive keywords.
7065 else if (cursor.kind == CXCursor_StructDecl ||
7066 cursor.kind == CXCursor_ClassDecl ||
7067 cursor.kind == CXCursor_ClassTemplate ||
7068 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007069 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 if (D->hasAttr<FinalAttr>())
7071 HasContextSensitiveKeywords = true;
7072 }
7073 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007074
7075 // Don't override a property annotation with its getter/setter method.
7076 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7077 parent.kind == CXCursor_ObjCPropertyDecl)
7078 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007079
7080 if (clang_isPreprocessing(cursor.kind)) {
7081 // Items in the preprocessing record are kept separate from items in
7082 // declarations, so we keep a separate token index.
7083 unsigned SavedTokIdx = TokIdx;
7084 TokIdx = PreprocessingTokIdx;
7085
7086 // Skip tokens up until we catch up to the beginning of the preprocessing
7087 // entry.
7088 while (MoreTokens()) {
7089 const unsigned I = NextToken();
7090 SourceLocation TokLoc = GetTokenLoc(I);
7091 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7092 case RangeBefore:
7093 AdvanceToken();
7094 continue;
7095 case RangeAfter:
7096 case RangeOverlap:
7097 break;
7098 }
7099 break;
7100 }
7101
7102 // Look at all of the tokens within this range.
7103 while (MoreTokens()) {
7104 const unsigned I = NextToken();
7105 SourceLocation TokLoc = GetTokenLoc(I);
7106 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7107 case RangeBefore:
7108 llvm_unreachable("Infeasible");
7109 case RangeAfter:
7110 break;
7111 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007112 // For macro expansions, just note where the beginning of the macro
7113 // expansion occurs.
7114 if (cursor.kind == CXCursor_MacroExpansion) {
7115 if (TokLoc == cursorRange.getBegin())
7116 Cursors[I] = cursor;
7117 AdvanceToken();
7118 break;
7119 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007120 // We may have already annotated macro names inside macro definitions.
7121 if (Cursors[I].kind != CXCursor_MacroExpansion)
7122 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007123 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007124 continue;
7125 }
7126 break;
7127 }
7128
7129 // Save the preprocessing token index; restore the non-preprocessing
7130 // token index.
7131 PreprocessingTokIdx = TokIdx;
7132 TokIdx = SavedTokIdx;
7133 return CXChildVisit_Recurse;
7134 }
7135
7136 if (cursorRange.isInvalid())
7137 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007138
7139 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007140 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007141 const enum CXCursorKind K = clang_getCursorKind(parent);
7142 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007143 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7144 // Attributes are annotated out-of-order, skip tokens until we reach it.
7145 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007146 ? clang_getNullCursor() : parent;
7147
7148 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7149
7150 // Avoid having the cursor of an expression "overwrite" the annotation of the
7151 // variable declaration that it belongs to.
7152 // This can happen for C++ constructor expressions whose range generally
7153 // include the variable declaration, e.g.:
7154 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007155 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007156 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007157 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007158 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007159 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7160 E->getBeginLoc() == D->getLocation() &&
7161 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007162 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 AdvanceToken();
7164 }
7165 }
7166 }
7167
7168 // Before recursing into the children keep some state that we are going
7169 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7170 // extra work after the child nodes are visited.
7171 // Note that we don't call VisitChildren here to avoid traversing statements
7172 // code-recursively which can blow the stack.
7173
7174 PostChildrenInfo Info;
7175 Info.Cursor = cursor;
7176 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007177 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007178 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007179 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007180 PostChildrenInfos.push_back(Info);
7181
7182 return CXChildVisit_Recurse;
7183}
7184
7185bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7186 if (PostChildrenInfos.empty())
7187 return false;
7188 const PostChildrenInfo &Info = PostChildrenInfos.back();
7189 if (!clang_equalCursors(Info.Cursor, cursor))
7190 return false;
7191
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007192 HandlePostPonedChildCursors(Info);
7193
Guy Benyei11169dd2012-12-18 14:30:41 +00007194 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7195 const unsigned AfterChildren = NextToken();
7196 SourceRange cursorRange = Info.CursorRange;
7197
7198 // Scan the tokens that are at the end of the cursor, but are not captured
7199 // but the child cursors.
7200 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7201
7202 // Scan the tokens that are at the beginning of the cursor, but are not
7203 // capture by the child cursors.
7204 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7205 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7206 break;
7207
7208 Cursors[I] = cursor;
7209 }
7210
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007211 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7212 // encountered the attribute cursor.
7213 if (clang_isAttribute(cursor.kind))
7214 TokIdx = Info.BeforeReachingCursorIdx;
7215
Guy Benyei11169dd2012-12-18 14:30:41 +00007216 PostChildrenInfos.pop_back();
7217 return false;
7218}
7219
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007220void AnnotateTokensWorker::HandlePostPonedChildCursors(
7221 const PostChildrenInfo &Info) {
7222 for (const auto &ChildAction : Info.ChildActions) {
7223 if (ChildAction.action == PostChildrenAction::Postpone) {
7224 HandlePostPonedChildCursor(ChildAction.cursor,
7225 Info.BeforeChildrenTokenIdx);
7226 }
7227 }
7228}
7229
7230void AnnotateTokensWorker::HandlePostPonedChildCursor(
7231 CXCursor Cursor, unsigned StartTokenIndex) {
7232 const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier;
7233 unsigned I = StartTokenIndex;
7234
7235 // The bracket tokens of a Call or Subscript operator are mapped to
7236 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7237 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7238 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
7239 const CXSourceRange CXRefNameRange =
7240 clang_getCursorReferenceNameRange(Cursor, flags, RefNameRangeNr);
7241 if (clang_Range_isNull(CXRefNameRange))
7242 break; // All ranges handled.
7243
7244 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7245 while (I < NumTokens) {
7246 const SourceLocation TokenLocation = GetTokenLoc(I);
7247 if (!TokenLocation.isValid())
7248 break;
7249
7250 // Adapt the end range, because LocationCompare() reports
7251 // RangeOverlap even for the not-inclusive end location.
7252 const SourceLocation fixedEnd =
7253 RefNameRange.getEnd().getLocWithOffset(-1);
7254 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7255
7256 const RangeComparisonResult ComparisonResult =
7257 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7258
7259 if (ComparisonResult == RangeOverlap) {
7260 Cursors[I++] = Cursor;
7261 } else if (ComparisonResult == RangeBefore) {
7262 ++I; // Not relevant token, check next one.
7263 } else if (ComparisonResult == RangeAfter) {
7264 break; // All tokens updated for current range, check next.
7265 }
7266 }
7267 }
7268}
7269
Guy Benyei11169dd2012-12-18 14:30:41 +00007270static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7271 CXCursor parent,
7272 CXClientData client_data) {
7273 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7274}
7275
7276static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7277 CXClientData client_data) {
7278 return static_cast<AnnotateTokensWorker*>(client_data)->
7279 postVisitChildren(cursor);
7280}
7281
7282namespace {
7283
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007284/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007285/// and mark tokens that are macro arguments. This info is used by the
7286/// AnnotateTokensWorker.
7287class MarkMacroArgTokensVisitor {
7288 SourceManager &SM;
7289 CXToken *Tokens;
7290 unsigned NumTokens;
7291 unsigned CurIdx;
7292
7293public:
7294 MarkMacroArgTokensVisitor(SourceManager &SM,
7295 CXToken *tokens, unsigned numTokens)
7296 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7297
7298 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7299 if (cursor.kind != CXCursor_MacroExpansion)
7300 return CXChildVisit_Continue;
7301
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007302 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007303 if (macroRange.getBegin() == macroRange.getEnd())
7304 return CXChildVisit_Continue; // it's not a function macro.
7305
7306 for (; CurIdx < NumTokens; ++CurIdx) {
7307 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7308 macroRange.getBegin()))
7309 break;
7310 }
7311
7312 if (CurIdx == NumTokens)
7313 return CXChildVisit_Break;
7314
7315 for (; CurIdx < NumTokens; ++CurIdx) {
7316 SourceLocation tokLoc = getTokenLoc(CurIdx);
7317 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7318 break;
7319
7320 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7321 }
7322
7323 if (CurIdx == NumTokens)
7324 return CXChildVisit_Break;
7325
7326 return CXChildVisit_Continue;
7327 }
7328
7329private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007330 CXToken &getTok(unsigned Idx) {
7331 assert(Idx < NumTokens);
7332 return Tokens[Idx];
7333 }
7334 const CXToken &getTok(unsigned Idx) const {
7335 assert(Idx < NumTokens);
7336 return Tokens[Idx];
7337 }
7338
Guy Benyei11169dd2012-12-18 14:30:41 +00007339 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007340 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007341 }
7342
7343 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7344 // The third field is reserved and currently not used. Use it here
7345 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007346 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007347 }
7348};
7349
7350} // end anonymous namespace
7351
7352static CXChildVisitResult
7353MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7354 CXClientData client_data) {
7355 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7356 parent);
7357}
7358
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007359/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007360/// \returns true if lexing was finished, false otherwise.
7361static bool lexNext(Lexer &Lex, Token &Tok,
7362 unsigned &NextIdx, unsigned NumTokens) {
7363 if (NextIdx >= NumTokens)
7364 return true;
7365
7366 ++NextIdx;
7367 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007368 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007369}
7370
Guy Benyei11169dd2012-12-18 14:30:41 +00007371static void annotatePreprocessorTokens(CXTranslationUnit TU,
7372 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007373 CXCursor *Cursors,
7374 CXToken *Tokens,
7375 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007376 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007377
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007378 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007379 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7380 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007381 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007382 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007383 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007384
7385 if (BeginLocInfo.first != EndLocInfo.first)
7386 return;
7387
7388 StringRef Buffer;
7389 bool Invalid = false;
7390 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7391 if (Buffer.empty() || Invalid)
7392 return;
7393
7394 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7395 CXXUnit->getASTContext().getLangOpts(),
7396 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7397 Buffer.end());
7398 Lex.SetCommentRetentionState(true);
7399
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007400 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007401 // Lex tokens in raw mode until we hit the end of the range, to avoid
7402 // entering #includes or expanding macros.
7403 while (true) {
7404 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007405 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7406 break;
7407 unsigned TokIdx = NextIdx-1;
7408 assert(Tok.getLocation() ==
7409 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007410
7411 reprocess:
7412 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007413 // We have found a preprocessing directive. Annotate the tokens
7414 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007415 //
7416 // FIXME: Some simple tests here could identify macro definitions and
7417 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007418
7419 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007420 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7421 break;
7422
Craig Topper69186e72014-06-08 08:38:04 +00007423 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007424 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007425 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7426 break;
7427
7428 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007429 IdentifierInfo &II =
7430 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007431 SourceLocation MappedTokLoc =
7432 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7433 MI = getMacroInfo(II, MappedTokLoc, TU);
7434 }
7435 }
7436
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007437 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007438 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007439 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7440 finished = true;
7441 break;
7442 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007443 // If we are in a macro definition, check if the token was ever a
7444 // macro name and annotate it if that's the case.
7445 if (MI) {
7446 SourceLocation SaveLoc = Tok.getLocation();
7447 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007448 MacroDefinitionRecord *MacroDef =
7449 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007450 Tok.setLocation(SaveLoc);
7451 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007452 Cursors[NextIdx - 1] =
7453 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007454 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007455 } while (!Tok.isAtStartOfLine());
7456
7457 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7458 assert(TokIdx <= LastIdx);
7459 SourceLocation EndLoc =
7460 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7461 CXCursor Cursor =
7462 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7463
7464 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007465 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007466
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007467 if (finished)
7468 break;
7469 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007470 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007471 }
7472}
7473
7474// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007475static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7476 CXToken *Tokens, unsigned NumTokens,
7477 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007478 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007479 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7480 setThreadBackgroundPriority();
7481
7482 // Determine the region of interest, which contains all of the tokens.
7483 SourceRange RegionOfInterest;
7484 RegionOfInterest.setBegin(
7485 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7486 RegionOfInterest.setEnd(
7487 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7488 Tokens[NumTokens-1])));
7489
Guy Benyei11169dd2012-12-18 14:30:41 +00007490 // Relex the tokens within the source range to look for preprocessing
7491 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007492 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007493
7494 // If begin location points inside a macro argument, set it to the expansion
7495 // location so we can have the full context when annotating semantically.
7496 {
7497 SourceManager &SM = CXXUnit->getSourceManager();
7498 SourceLocation Loc =
7499 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7500 if (Loc.isMacroID())
7501 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7502 }
7503
Guy Benyei11169dd2012-12-18 14:30:41 +00007504 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7505 // Search and mark tokens that are macro argument expansions.
7506 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7507 Tokens, NumTokens);
7508 CursorVisitor MacroArgMarker(TU,
7509 MarkMacroArgTokensVisitorDelegate, &Visitor,
7510 /*VisitPreprocessorLast=*/true,
7511 /*VisitIncludedEntities=*/false,
7512 RegionOfInterest);
7513 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7514 }
7515
7516 // Annotate all of the source locations in the region of interest that map to
7517 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007518 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007519
7520 // FIXME: We use a ridiculous stack size here because the data-recursion
7521 // algorithm uses a large stack frame than the non-data recursive version,
7522 // and AnnotationTokensWorker currently transforms the data-recursion
7523 // algorithm back into a traditional recursion by explicitly calling
7524 // VisitChildren(). We will need to remove this explicit recursive call.
7525 W.AnnotateTokens();
7526
7527 // If we ran into any entities that involve context-sensitive keywords,
7528 // take another pass through the tokens to mark them as such.
7529 if (W.hasContextSensitiveKeywords()) {
7530 for (unsigned I = 0; I != NumTokens; ++I) {
7531 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7532 continue;
7533
7534 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7535 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007536 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007537 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7538 if (Property->getPropertyAttributesAsWritten() != 0 &&
7539 llvm::StringSwitch<bool>(II->getName())
7540 .Case("readonly", true)
7541 .Case("assign", true)
7542 .Case("unsafe_unretained", true)
7543 .Case("readwrite", true)
7544 .Case("retain", true)
7545 .Case("copy", true)
7546 .Case("nonatomic", true)
7547 .Case("atomic", true)
7548 .Case("getter", true)
7549 .Case("setter", true)
7550 .Case("strong", true)
7551 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007552 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007553 .Default(false))
7554 Tokens[I].int_data[0] = CXToken_Keyword;
7555 }
7556 continue;
7557 }
7558
7559 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7560 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7561 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7562 if (llvm::StringSwitch<bool>(II->getName())
7563 .Case("in", true)
7564 .Case("out", true)
7565 .Case("inout", true)
7566 .Case("oneway", true)
7567 .Case("bycopy", true)
7568 .Case("byref", true)
7569 .Default(false))
7570 Tokens[I].int_data[0] = CXToken_Keyword;
7571 continue;
7572 }
7573
7574 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7575 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7576 Tokens[I].int_data[0] = CXToken_Keyword;
7577 continue;
7578 }
7579 }
7580 }
7581}
7582
Guy Benyei11169dd2012-12-18 14:30:41 +00007583void clang_annotateTokens(CXTranslationUnit TU,
7584 CXToken *Tokens, unsigned NumTokens,
7585 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007586 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007587 LOG_BAD_TU(TU);
7588 return;
7589 }
7590 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007591 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007592 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007593 }
7594
7595 LOG_FUNC_SECTION {
7596 *Log << TU << ' ';
7597 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7598 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7599 *Log << clang_getRange(bloc, eloc);
7600 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007601
7602 // Any token we don't specifically annotate will have a NULL cursor.
7603 CXCursor C = clang_getNullCursor();
7604 for (unsigned I = 0; I != NumTokens; ++I)
7605 Cursors[I] = C;
7606
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007607 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007608 if (!CXXUnit)
7609 return;
7610
7611 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007612
7613 auto AnnotateTokensImpl = [=]() {
7614 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7615 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007616 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007617 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007618 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7619 }
7620}
7621
Guy Benyei11169dd2012-12-18 14:30:41 +00007622//===----------------------------------------------------------------------===//
7623// Operations for querying linkage of a cursor.
7624//===----------------------------------------------------------------------===//
7625
Guy Benyei11169dd2012-12-18 14:30:41 +00007626CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7627 if (!clang_isDeclaration(cursor.kind))
7628 return CXLinkage_Invalid;
7629
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007630 const Decl *D = cxcursor::getCursorDecl(cursor);
7631 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007632 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007633 case NoLinkage:
7634 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007635 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007636 case InternalLinkage: return CXLinkage_Internal;
7637 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007638 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007639 case ExternalLinkage: return CXLinkage_External;
7640 };
7641
7642 return CXLinkage_Invalid;
7643}
Guy Benyei11169dd2012-12-18 14:30:41 +00007644
7645//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007646// Operations for querying visibility of a cursor.
7647//===----------------------------------------------------------------------===//
7648
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007649CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7650 if (!clang_isDeclaration(cursor.kind))
7651 return CXVisibility_Invalid;
7652
7653 const Decl *D = cxcursor::getCursorDecl(cursor);
7654 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7655 switch (ND->getVisibility()) {
7656 case HiddenVisibility: return CXVisibility_Hidden;
7657 case ProtectedVisibility: return CXVisibility_Protected;
7658 case DefaultVisibility: return CXVisibility_Default;
7659 };
7660
7661 return CXVisibility_Invalid;
7662}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007663
7664//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007665// Operations for querying language of a cursor.
7666//===----------------------------------------------------------------------===//
7667
7668static CXLanguageKind getDeclLanguage(const Decl *D) {
7669 if (!D)
7670 return CXLanguage_C;
7671
7672 switch (D->getKind()) {
7673 default:
7674 break;
7675 case Decl::ImplicitParam:
7676 case Decl::ObjCAtDefsField:
7677 case Decl::ObjCCategory:
7678 case Decl::ObjCCategoryImpl:
7679 case Decl::ObjCCompatibleAlias:
7680 case Decl::ObjCImplementation:
7681 case Decl::ObjCInterface:
7682 case Decl::ObjCIvar:
7683 case Decl::ObjCMethod:
7684 case Decl::ObjCProperty:
7685 case Decl::ObjCPropertyImpl:
7686 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007687 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007688 return CXLanguage_ObjC;
7689 case Decl::CXXConstructor:
7690 case Decl::CXXConversion:
7691 case Decl::CXXDestructor:
7692 case Decl::CXXMethod:
7693 case Decl::CXXRecord:
7694 case Decl::ClassTemplate:
7695 case Decl::ClassTemplatePartialSpecialization:
7696 case Decl::ClassTemplateSpecialization:
7697 case Decl::Friend:
7698 case Decl::FriendTemplate:
7699 case Decl::FunctionTemplate:
7700 case Decl::LinkageSpec:
7701 case Decl::Namespace:
7702 case Decl::NamespaceAlias:
7703 case Decl::NonTypeTemplateParm:
7704 case Decl::StaticAssert:
7705 case Decl::TemplateTemplateParm:
7706 case Decl::TemplateTypeParm:
7707 case Decl::UnresolvedUsingTypename:
7708 case Decl::UnresolvedUsingValue:
7709 case Decl::Using:
7710 case Decl::UsingDirective:
7711 case Decl::UsingShadow:
7712 return CXLanguage_CPlusPlus;
7713 }
7714
7715 return CXLanguage_C;
7716}
7717
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007718static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7719 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007720 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007721
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007722 switch (D->getAvailability()) {
7723 case AR_Available:
7724 case AR_NotYetIntroduced:
7725 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007726 return getCursorAvailabilityForDecl(
7727 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007728 return CXAvailability_Available;
7729
7730 case AR_Deprecated:
7731 return CXAvailability_Deprecated;
7732
7733 case AR_Unavailable:
7734 return CXAvailability_NotAvailable;
7735 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007736
7737 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007738}
7739
Guy Benyei11169dd2012-12-18 14:30:41 +00007740enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7741 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007742 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7743 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007744
7745 return CXAvailability_Available;
7746}
7747
7748static CXVersion convertVersion(VersionTuple In) {
7749 CXVersion Out = { -1, -1, -1 };
7750 if (In.empty())
7751 return Out;
7752
7753 Out.Major = In.getMajor();
7754
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007755 Optional<unsigned> Minor = In.getMinor();
7756 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 Out.Minor = *Minor;
7758 else
7759 return Out;
7760
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007761 Optional<unsigned> Subminor = In.getSubminor();
7762 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007763 Out.Subminor = *Subminor;
7764
7765 return Out;
7766}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007767
Alex Lorenz1345ea22017-06-12 19:06:30 +00007768static void getCursorPlatformAvailabilityForDecl(
7769 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7770 int *always_unavailable, CXString *unavailable_message,
7771 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007772 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007773 for (auto A : D->attrs()) {
7774 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007775 HadAvailAttr = true;
7776 if (always_deprecated)
7777 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007778 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007779 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007780 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007781 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007782 continue;
7783 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007784
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007785 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007786 HadAvailAttr = true;
7787 if (always_unavailable)
7788 *always_unavailable = 1;
7789 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007790 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007791 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7792 }
7793 continue;
7794 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007795
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007796 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007797 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007798 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007799 }
7800 }
7801
7802 if (!HadAvailAttr)
7803 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7804 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007805 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7806 deprecated_message, always_unavailable, unavailable_message,
7807 AvailabilityAttrs);
7808
7809 if (AvailabilityAttrs.empty())
7810 return;
7811
Fangrui Song55fab262018-09-26 22:16:28 +00007812 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007813 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7814 return LHS->getPlatform()->getName() <
7815 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007816 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007817 ASTContext &Ctx = D->getASTContext();
7818 auto It = std::unique(
7819 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7820 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7821 if (LHS->getPlatform() != RHS->getPlatform())
7822 return false;
7823
7824 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7825 LHS->getDeprecated() == RHS->getDeprecated() &&
7826 LHS->getObsoleted() == RHS->getObsoleted() &&
7827 LHS->getMessage() == RHS->getMessage() &&
7828 LHS->getReplacement() == RHS->getReplacement())
7829 return true;
7830
7831 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7832 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7833 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7834 return false;
7835
7836 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7837 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7838
7839 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7840 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7841 if (LHS->getMessage().empty())
7842 LHS->setMessage(Ctx, RHS->getMessage());
7843 if (LHS->getReplacement().empty())
7844 LHS->setReplacement(Ctx, RHS->getReplacement());
7845 }
7846
7847 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7848 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7849 if (LHS->getMessage().empty())
7850 LHS->setMessage(Ctx, RHS->getMessage());
7851 if (LHS->getReplacement().empty())
7852 LHS->setReplacement(Ctx, RHS->getReplacement());
7853 }
7854
7855 return true;
7856 });
7857 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007858}
7859
Alex Lorenz1345ea22017-06-12 19:06:30 +00007860int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007861 CXString *deprecated_message,
7862 int *always_unavailable,
7863 CXString *unavailable_message,
7864 CXPlatformAvailability *availability,
7865 int availability_size) {
7866 if (always_deprecated)
7867 *always_deprecated = 0;
7868 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007869 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007870 if (always_unavailable)
7871 *always_unavailable = 0;
7872 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007873 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007874
Guy Benyei11169dd2012-12-18 14:30:41 +00007875 if (!clang_isDeclaration(cursor.kind))
7876 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007877
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007878 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007879 if (!D)
7880 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007881
Alex Lorenz1345ea22017-06-12 19:06:30 +00007882 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7883 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7884 always_unavailable, unavailable_message,
7885 AvailabilityAttrs);
7886 for (const auto &Avail :
7887 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7888 .take_front(availability_size))) {
7889 availability[Avail.index()].Platform =
7890 cxstring::createDup(Avail.value()->getPlatform()->getName());
7891 availability[Avail.index()].Introduced =
7892 convertVersion(Avail.value()->getIntroduced());
7893 availability[Avail.index()].Deprecated =
7894 convertVersion(Avail.value()->getDeprecated());
7895 availability[Avail.index()].Obsoleted =
7896 convertVersion(Avail.value()->getObsoleted());
7897 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7898 availability[Avail.index()].Message =
7899 cxstring::createDup(Avail.value()->getMessage());
7900 }
7901
7902 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007903}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007904
Guy Benyei11169dd2012-12-18 14:30:41 +00007905void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7906 clang_disposeString(availability->Platform);
7907 clang_disposeString(availability->Message);
7908}
7909
7910CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7911 if (clang_isDeclaration(cursor.kind))
7912 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7913
7914 return CXLanguage_Invalid;
7915}
7916
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007917CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7918 const Decl *D = cxcursor::getCursorDecl(cursor);
7919 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7920 switch (VD->getTLSKind()) {
7921 case VarDecl::TLS_None:
7922 return CXTLS_None;
7923 case VarDecl::TLS_Dynamic:
7924 return CXTLS_Dynamic;
7925 case VarDecl::TLS_Static:
7926 return CXTLS_Static;
7927 }
7928 }
7929
7930 return CXTLS_None;
7931}
7932
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007933 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007934 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007935 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007936static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007937 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007938 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007939
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007940 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007941 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7942 return FunTmpl;
7943
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007944 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007945 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7946 return ClassTmpl;
7947
7948 return D;
7949}
7950
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007951
7952enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7953 StorageClass sc = SC_None;
7954 const Decl *D = getCursorDecl(C);
7955 if (D) {
7956 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7957 sc = FD->getStorageClass();
7958 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7959 sc = VD->getStorageClass();
7960 } else {
7961 return CX_SC_Invalid;
7962 }
7963 } else {
7964 return CX_SC_Invalid;
7965 }
7966 switch (sc) {
7967 case SC_None:
7968 return CX_SC_None;
7969 case SC_Extern:
7970 return CX_SC_Extern;
7971 case SC_Static:
7972 return CX_SC_Static;
7973 case SC_PrivateExtern:
7974 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007975 case SC_Auto:
7976 return CX_SC_Auto;
7977 case SC_Register:
7978 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007979 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007980 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007981}
7982
Guy Benyei11169dd2012-12-18 14:30:41 +00007983CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7984 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007985 if (const Decl *D = getCursorDecl(cursor)) {
7986 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007987 if (!DC)
7988 return clang_getNullCursor();
7989
7990 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7991 getCursorTU(cursor));
7992 }
7993 }
7994
7995 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007996 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007997 return MakeCXCursor(D, getCursorTU(cursor));
7998 }
7999
8000 return clang_getNullCursor();
8001}
8002
8003CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8004 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008005 if (const Decl *D = getCursorDecl(cursor)) {
8006 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 if (!DC)
8008 return clang_getNullCursor();
8009
8010 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8011 getCursorTU(cursor));
8012 }
8013 }
8014
8015 // FIXME: Note that we can't easily compute the lexical context of a
8016 // statement or expression, so we return nothing.
8017 return clang_getNullCursor();
8018}
8019
8020CXFile clang_getIncludedFile(CXCursor cursor) {
8021 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008022 return nullptr;
8023
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008024 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008025 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008026}
8027
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008028unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8029 if (C.kind != CXCursor_ObjCPropertyDecl)
8030 return CXObjCPropertyAttr_noattr;
8031
8032 unsigned Result = CXObjCPropertyAttr_noattr;
8033 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8034 ObjCPropertyDecl::PropertyAttributeKind Attr =
8035 PD->getPropertyAttributesAsWritten();
8036
8037#define SET_CXOBJCPROP_ATTR(A) \
8038 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8039 Result |= CXObjCPropertyAttr_##A
8040 SET_CXOBJCPROP_ATTR(readonly);
8041 SET_CXOBJCPROP_ATTR(getter);
8042 SET_CXOBJCPROP_ATTR(assign);
8043 SET_CXOBJCPROP_ATTR(readwrite);
8044 SET_CXOBJCPROP_ATTR(retain);
8045 SET_CXOBJCPROP_ATTR(copy);
8046 SET_CXOBJCPROP_ATTR(nonatomic);
8047 SET_CXOBJCPROP_ATTR(setter);
8048 SET_CXOBJCPROP_ATTR(atomic);
8049 SET_CXOBJCPROP_ATTR(weak);
8050 SET_CXOBJCPROP_ATTR(strong);
8051 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008052 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008053#undef SET_CXOBJCPROP_ATTR
8054
8055 return Result;
8056}
8057
Michael Wu6e88f532018-08-03 05:38:29 +00008058CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8059 if (C.kind != CXCursor_ObjCPropertyDecl)
8060 return cxstring::createNull();
8061
8062 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8063 Selector sel = PD->getGetterName();
8064 if (sel.isNull())
8065 return cxstring::createNull();
8066
8067 return cxstring::createDup(sel.getAsString());
8068}
8069
8070CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8071 if (C.kind != CXCursor_ObjCPropertyDecl)
8072 return cxstring::createNull();
8073
8074 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8075 Selector sel = PD->getSetterName();
8076 if (sel.isNull())
8077 return cxstring::createNull();
8078
8079 return cxstring::createDup(sel.getAsString());
8080}
8081
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008082unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8083 if (!clang_isDeclaration(C.kind))
8084 return CXObjCDeclQualifier_None;
8085
8086 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8087 const Decl *D = getCursorDecl(C);
8088 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8089 QT = MD->getObjCDeclQualifier();
8090 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8091 QT = PD->getObjCDeclQualifier();
8092 if (QT == Decl::OBJC_TQ_None)
8093 return CXObjCDeclQualifier_None;
8094
8095 unsigned Result = CXObjCDeclQualifier_None;
8096 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8097 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8098 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8099 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8100 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8101 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8102
8103 return Result;
8104}
8105
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008106unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8107 if (!clang_isDeclaration(C.kind))
8108 return 0;
8109
8110 const Decl *D = getCursorDecl(C);
8111 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8112 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8113 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8114 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8115
8116 return 0;
8117}
8118
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008119unsigned clang_Cursor_isVariadic(CXCursor C) {
8120 if (!clang_isDeclaration(C.kind))
8121 return 0;
8122
8123 const Decl *D = getCursorDecl(C);
8124 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8125 return FD->isVariadic();
8126 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8127 return MD->isVariadic();
8128
8129 return 0;
8130}
8131
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008132unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8133 CXString *language, CXString *definedIn,
8134 unsigned *isGenerated) {
8135 if (!clang_isDeclaration(C.kind))
8136 return 0;
8137
8138 const Decl *D = getCursorDecl(C);
8139
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008140 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008141 if (language)
8142 *language = cxstring::createDup(attr->getLanguage());
8143 if (definedIn)
8144 *definedIn = cxstring::createDup(attr->getDefinedIn());
8145 if (isGenerated)
8146 *isGenerated = attr->getGeneratedDeclaration();
8147 return 1;
8148 }
8149 return 0;
8150}
8151
Guy Benyei11169dd2012-12-18 14:30:41 +00008152CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8153 if (!clang_isDeclaration(C.kind))
8154 return clang_getNullRange();
8155
8156 const Decl *D = getCursorDecl(C);
8157 ASTContext &Context = getCursorContext(C);
8158 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8159 if (!RC)
8160 return clang_getNullRange();
8161
8162 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8163}
8164
8165CXString clang_Cursor_getRawCommentText(CXCursor C) {
8166 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008167 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008168
8169 const Decl *D = getCursorDecl(C);
8170 ASTContext &Context = getCursorContext(C);
8171 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8172 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8173 StringRef();
8174
8175 // Don't duplicate the string because RawText points directly into source
8176 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008177 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008178}
8179
8180CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8181 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008182 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008183
8184 const Decl *D = getCursorDecl(C);
8185 const ASTContext &Context = getCursorContext(C);
8186 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8187
8188 if (RC) {
8189 StringRef BriefText = RC->getBriefText(Context);
8190
8191 // Don't duplicate the string because RawComment ensures that this memory
8192 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008193 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008194 }
8195
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008196 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008197}
8198
Guy Benyei11169dd2012-12-18 14:30:41 +00008199CXModule clang_Cursor_getModule(CXCursor C) {
8200 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008201 if (const ImportDecl *ImportD =
8202 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008203 return ImportD->getImportedModule();
8204 }
8205
Craig Topper69186e72014-06-08 08:38:04 +00008206 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008207}
8208
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008209CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8210 if (isNotUsableTU(TU)) {
8211 LOG_BAD_TU(TU);
8212 return nullptr;
8213 }
8214 if (!File)
8215 return nullptr;
8216 FileEntry *FE = static_cast<FileEntry *>(File);
8217
8218 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8219 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8220 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8221
Richard Smithfeb54b62014-10-23 02:01:19 +00008222 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008223}
8224
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008225CXFile clang_Module_getASTFile(CXModule CXMod) {
8226 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008227 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008228 Module *Mod = static_cast<Module*>(CXMod);
8229 return const_cast<FileEntry *>(Mod->getASTFile());
8230}
8231
Guy Benyei11169dd2012-12-18 14:30:41 +00008232CXModule clang_Module_getParent(CXModule CXMod) {
8233 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008234 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008235 Module *Mod = static_cast<Module*>(CXMod);
8236 return Mod->Parent;
8237}
8238
8239CXString clang_Module_getName(CXModule CXMod) {
8240 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008241 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008243 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008244}
8245
8246CXString clang_Module_getFullName(CXModule CXMod) {
8247 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008248 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008249 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008250 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008251}
8252
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008253int clang_Module_isSystem(CXModule CXMod) {
8254 if (!CXMod)
8255 return 0;
8256 Module *Mod = static_cast<Module*>(CXMod);
8257 return Mod->IsSystem;
8258}
8259
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008260unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8261 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008262 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008263 LOG_BAD_TU(TU);
8264 return 0;
8265 }
8266 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008267 return 0;
8268 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008269 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8270 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8271 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008272}
8273
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008274CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8275 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008276 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008277 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008278 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008279 }
8280 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008281 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008282 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008283 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008284
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008285 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8286 if (Index < TopHeaders.size())
8287 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008288
Craig Topper69186e72014-06-08 08:38:04 +00008289 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008290}
8291
Guy Benyei11169dd2012-12-18 14:30:41 +00008292//===----------------------------------------------------------------------===//
8293// C++ AST instrospection.
8294//===----------------------------------------------------------------------===//
8295
Jonathan Coe29565352016-04-27 12:48:25 +00008296unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8297 if (!clang_isDeclaration(C.kind))
8298 return 0;
8299
8300 const Decl *D = cxcursor::getCursorDecl(C);
8301 const CXXConstructorDecl *Constructor =
8302 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8303 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8304}
8305
8306unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8307 if (!clang_isDeclaration(C.kind))
8308 return 0;
8309
8310 const Decl *D = cxcursor::getCursorDecl(C);
8311 const CXXConstructorDecl *Constructor =
8312 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8313 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8314}
8315
8316unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8317 if (!clang_isDeclaration(C.kind))
8318 return 0;
8319
8320 const Decl *D = cxcursor::getCursorDecl(C);
8321 const CXXConstructorDecl *Constructor =
8322 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8323 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8324}
8325
8326unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8327 if (!clang_isDeclaration(C.kind))
8328 return 0;
8329
8330 const Decl *D = cxcursor::getCursorDecl(C);
8331 const CXXConstructorDecl *Constructor =
8332 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8333 // Passing 'false' excludes constructors marked 'explicit'.
8334 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8335}
8336
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008337unsigned clang_CXXField_isMutable(CXCursor C) {
8338 if (!clang_isDeclaration(C.kind))
8339 return 0;
8340
8341 if (const auto D = cxcursor::getCursorDecl(C))
8342 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8343 return FD->isMutable() ? 1 : 0;
8344 return 0;
8345}
8346
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008347unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8348 if (!clang_isDeclaration(C.kind))
8349 return 0;
8350
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008351 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008352 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008353 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008354 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8355}
8356
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008357unsigned clang_CXXMethod_isConst(CXCursor C) {
8358 if (!clang_isDeclaration(C.kind))
8359 return 0;
8360
8361 const Decl *D = cxcursor::getCursorDecl(C);
8362 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008363 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00008364 return (Method && Method->getTypeQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008365}
8366
Jonathan Coe29565352016-04-27 12:48:25 +00008367unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8368 if (!clang_isDeclaration(C.kind))
8369 return 0;
8370
8371 const Decl *D = cxcursor::getCursorDecl(C);
8372 const CXXMethodDecl *Method =
8373 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8374 return (Method && Method->isDefaulted()) ? 1 : 0;
8375}
8376
Guy Benyei11169dd2012-12-18 14:30:41 +00008377unsigned clang_CXXMethod_isStatic(CXCursor C) {
8378 if (!clang_isDeclaration(C.kind))
8379 return 0;
8380
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008381 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008382 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008383 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008384 return (Method && Method->isStatic()) ? 1 : 0;
8385}
8386
8387unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8388 if (!clang_isDeclaration(C.kind))
8389 return 0;
8390
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008391 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008392 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008393 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008394 return (Method && Method->isVirtual()) ? 1 : 0;
8395}
Guy Benyei11169dd2012-12-18 14:30:41 +00008396
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008397unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8398 if (!clang_isDeclaration(C.kind))
8399 return 0;
8400
8401 const auto *D = cxcursor::getCursorDecl(C);
8402 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8403 if (RD)
8404 RD = RD->getDefinition();
8405 return (RD && RD->isAbstract()) ? 1 : 0;
8406}
8407
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008408unsigned clang_EnumDecl_isScoped(CXCursor C) {
8409 if (!clang_isDeclaration(C.kind))
8410 return 0;
8411
8412 const Decl *D = cxcursor::getCursorDecl(C);
8413 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8414 return (Enum && Enum->isScoped()) ? 1 : 0;
8415}
8416
Guy Benyei11169dd2012-12-18 14:30:41 +00008417//===----------------------------------------------------------------------===//
8418// Attribute introspection.
8419//===----------------------------------------------------------------------===//
8420
Guy Benyei11169dd2012-12-18 14:30:41 +00008421CXType clang_getIBOutletCollectionType(CXCursor C) {
8422 if (C.kind != CXCursor_IBOutletCollectionAttr)
8423 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8424
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008425 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008426 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8427
8428 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8429}
Guy Benyei11169dd2012-12-18 14:30:41 +00008430
8431//===----------------------------------------------------------------------===//
8432// Inspecting memory usage.
8433//===----------------------------------------------------------------------===//
8434
8435typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8436
8437static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8438 enum CXTUResourceUsageKind k,
8439 unsigned long amount) {
8440 CXTUResourceUsageEntry entry = { k, amount };
8441 entries.push_back(entry);
8442}
8443
Guy Benyei11169dd2012-12-18 14:30:41 +00008444const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8445 const char *str = "";
8446 switch (kind) {
8447 case CXTUResourceUsage_AST:
8448 str = "ASTContext: expressions, declarations, and types";
8449 break;
8450 case CXTUResourceUsage_Identifiers:
8451 str = "ASTContext: identifiers";
8452 break;
8453 case CXTUResourceUsage_Selectors:
8454 str = "ASTContext: selectors";
8455 break;
8456 case CXTUResourceUsage_GlobalCompletionResults:
8457 str = "Code completion: cached global results";
8458 break;
8459 case CXTUResourceUsage_SourceManagerContentCache:
8460 str = "SourceManager: content cache allocator";
8461 break;
8462 case CXTUResourceUsage_AST_SideTables:
8463 str = "ASTContext: side tables";
8464 break;
8465 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8466 str = "SourceManager: malloc'ed memory buffers";
8467 break;
8468 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8469 str = "SourceManager: mmap'ed memory buffers";
8470 break;
8471 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8472 str = "ExternalASTSource: malloc'ed memory buffers";
8473 break;
8474 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8475 str = "ExternalASTSource: mmap'ed memory buffers";
8476 break;
8477 case CXTUResourceUsage_Preprocessor:
8478 str = "Preprocessor: malloc'ed memory";
8479 break;
8480 case CXTUResourceUsage_PreprocessingRecord:
8481 str = "Preprocessor: PreprocessingRecord";
8482 break;
8483 case CXTUResourceUsage_SourceManager_DataStructures:
8484 str = "SourceManager: data structures and tables";
8485 break;
8486 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8487 str = "Preprocessor: header search tables";
8488 break;
8489 }
8490 return str;
8491}
8492
8493CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008494 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008495 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008496 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008497 return usage;
8498 }
8499
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008500 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008501 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008502 ASTContext &astContext = astUnit->getASTContext();
8503
8504 // How much memory is used by AST nodes and types?
8505 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8506 (unsigned long) astContext.getASTAllocatedMemory());
8507
8508 // How much memory is used by identifiers?
8509 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8510 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8511
8512 // How much memory is used for selectors?
8513 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8514 (unsigned long) astContext.Selectors.getTotalMemory());
8515
8516 // How much memory is used by ASTContext's side tables?
8517 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8518 (unsigned long) astContext.getSideTableAllocatedMemory());
8519
8520 // How much memory is used for caching global code completion results?
8521 unsigned long completionBytes = 0;
8522 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008523 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008524 completionBytes = completionAllocator->getTotalMemory();
8525 }
8526 createCXTUResourceUsageEntry(*entries,
8527 CXTUResourceUsage_GlobalCompletionResults,
8528 completionBytes);
8529
8530 // How much memory is being used by SourceManager's content cache?
8531 createCXTUResourceUsageEntry(*entries,
8532 CXTUResourceUsage_SourceManagerContentCache,
8533 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8534
8535 // How much memory is being used by the MemoryBuffer's in SourceManager?
8536 const SourceManager::MemoryBufferSizes &srcBufs =
8537 astUnit->getSourceManager().getMemoryBufferSizes();
8538
8539 createCXTUResourceUsageEntry(*entries,
8540 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8541 (unsigned long) srcBufs.malloc_bytes);
8542 createCXTUResourceUsageEntry(*entries,
8543 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8544 (unsigned long) srcBufs.mmap_bytes);
8545 createCXTUResourceUsageEntry(*entries,
8546 CXTUResourceUsage_SourceManager_DataStructures,
8547 (unsigned long) astContext.getSourceManager()
8548 .getDataStructureSizes());
8549
8550 // How much memory is being used by the ExternalASTSource?
8551 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8552 const ExternalASTSource::MemoryBufferSizes &sizes =
8553 esrc->getMemoryBufferSizes();
8554
8555 createCXTUResourceUsageEntry(*entries,
8556 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8557 (unsigned long) sizes.malloc_bytes);
8558 createCXTUResourceUsageEntry(*entries,
8559 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8560 (unsigned long) sizes.mmap_bytes);
8561 }
8562
8563 // How much memory is being used by the Preprocessor?
8564 Preprocessor &pp = astUnit->getPreprocessor();
8565 createCXTUResourceUsageEntry(*entries,
8566 CXTUResourceUsage_Preprocessor,
8567 pp.getTotalMemory());
8568
8569 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8570 createCXTUResourceUsageEntry(*entries,
8571 CXTUResourceUsage_PreprocessingRecord,
8572 pRec->getTotalMemory());
8573 }
8574
8575 createCXTUResourceUsageEntry(*entries,
8576 CXTUResourceUsage_Preprocessor_HeaderSearch,
8577 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008578
Guy Benyei11169dd2012-12-18 14:30:41 +00008579 CXTUResourceUsage usage = { (void*) entries.get(),
8580 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008581 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008582 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008583 return usage;
8584}
8585
8586void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8587 if (usage.data)
8588 delete (MemUsageEntries*) usage.data;
8589}
8590
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008591CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8592 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008593 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008594 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008595
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008596 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008597 LOG_BAD_TU(TU);
8598 return skipped;
8599 }
8600
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008601 if (!file)
8602 return skipped;
8603
8604 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8605 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8606 if (!ppRec)
8607 return skipped;
8608
8609 ASTContext &Ctx = astUnit->getASTContext();
8610 SourceManager &sm = Ctx.getSourceManager();
8611 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8612 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008613 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008614
8615 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8616 std::vector<SourceRange> wantedRanges;
8617 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8618 i != ei; ++i) {
8619 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8620 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008621 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8622 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008623 }
8624
8625 skipped->count = wantedRanges.size();
8626 skipped->ranges = new CXSourceRange[skipped->count];
8627 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8628 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8629
8630 return skipped;
8631}
8632
Cameron Desrochersd8091282016-08-18 15:43:55 +00008633CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8634 CXSourceRangeList *skipped = new CXSourceRangeList;
8635 skipped->count = 0;
8636 skipped->ranges = nullptr;
8637
8638 if (isNotUsableTU(TU)) {
8639 LOG_BAD_TU(TU);
8640 return skipped;
8641 }
8642
8643 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8644 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8645 if (!ppRec)
8646 return skipped;
8647
8648 ASTContext &Ctx = astUnit->getASTContext();
8649
8650 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8651
8652 skipped->count = SkippedRanges.size();
8653 skipped->ranges = new CXSourceRange[skipped->count];
8654 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8655 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8656
8657 return skipped;
8658}
8659
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008660void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8661 if (ranges) {
8662 delete[] ranges->ranges;
8663 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008664 }
8665}
8666
Guy Benyei11169dd2012-12-18 14:30:41 +00008667void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8668 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8669 for (unsigned I = 0; I != Usage.numEntries; ++I)
8670 fprintf(stderr, " %s: %lu\n",
8671 clang_getTUResourceUsageName(Usage.entries[I].kind),
8672 Usage.entries[I].amount);
8673
8674 clang_disposeCXTUResourceUsage(Usage);
8675}
8676
8677//===----------------------------------------------------------------------===//
8678// Misc. utility functions.
8679//===----------------------------------------------------------------------===//
8680
Richard Smith0a7b2972018-07-03 21:34:13 +00008681/// Default to using our desired 8 MB stack size on "safety" threads.
8682static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008683
8684namespace clang {
8685
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008686bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008687 unsigned Size) {
8688 if (!Size)
8689 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008690 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008691 return CRC.RunSafelyOnThread(Fn, Size);
8692 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008693}
8694
8695unsigned GetSafetyThreadStackSize() {
8696 return SafetyStackThreadSize;
8697}
8698
8699void SetSafetyThreadStackSize(unsigned Value) {
8700 SafetyStackThreadSize = Value;
8701}
8702
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008703}
Guy Benyei11169dd2012-12-18 14:30:41 +00008704
8705void clang::setThreadBackgroundPriority() {
8706 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8707 return;
8708
Alp Toker1a86ad22014-07-06 06:24:00 +00008709#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008710 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8711#endif
8712}
8713
8714void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8715 if (!Unit)
8716 return;
8717
8718 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8719 DEnd = Unit->stored_diag_end();
8720 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008721 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008722 CXString Msg = clang_formatDiagnostic(&Diag,
8723 clang_defaultDiagnosticDisplayOptions());
8724 fprintf(stderr, "%s\n", clang_getCString(Msg));
8725 clang_disposeString(Msg);
8726 }
Nico Weber1865df42018-04-27 19:11:14 +00008727#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008728 // On Windows, force a flush, since there may be multiple copies of
8729 // stderr and stdout in the file system, all with different buffers
8730 // but writing to the same device.
8731 fflush(stderr);
8732#endif
8733}
8734
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008735MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8736 SourceLocation MacroDefLoc,
8737 CXTranslationUnit TU){
8738 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008739 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008740 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008741 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008742
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008743 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008744 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008745 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008746 if (MD) {
8747 for (MacroDirective::DefInfo
8748 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8749 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8750 return Def.getMacroInfo();
8751 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008752 }
8753
Craig Topper69186e72014-06-08 08:38:04 +00008754 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008755}
8756
Richard Smith66a81862015-05-04 02:25:31 +00008757const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008758 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008759 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008760 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008761 const IdentifierInfo *II = MacroDef->getName();
8762 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008763 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008764
8765 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8766}
8767
Richard Smith66a81862015-05-04 02:25:31 +00008768MacroDefinitionRecord *
8769cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8770 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008771 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008772 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008773 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008774 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008775
8776 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008777 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008778 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8779 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008780 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008781
8782 // Check that the token is inside the definition and not its argument list.
8783 SourceManager &SM = Unit->getSourceManager();
8784 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008785 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008786 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008787 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008788
8789 Preprocessor &PP = Unit->getPreprocessor();
8790 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8791 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008792 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008793
Alp Toker2d57cea2014-05-17 04:53:25 +00008794 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008795 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008796 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008797
8798 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008799 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008800 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008801
Richard Smith20e883e2015-04-29 23:20:19 +00008802 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008803 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008804 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008805
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008806 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008807}
8808
Richard Smith66a81862015-05-04 02:25:31 +00008809MacroDefinitionRecord *
8810cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8811 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008812 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008813 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008814
8815 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008816 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008817 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008818 Preprocessor &PP = Unit->getPreprocessor();
8819 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008820 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008821 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8822 Token Tok;
8823 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008824 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008825
8826 return checkForMacroInMacroDefinition(MI, Tok, TU);
8827}
8828
Guy Benyei11169dd2012-12-18 14:30:41 +00008829CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008830 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008831}
8832
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008833Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8834 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008835 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008836 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008837 if (Unit->isMainFileAST())
8838 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008839 return *this;
8840 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008841 } else {
8842 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008843 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008844 return *this;
8845}
8846
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008847Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8848 *this << FE->getName();
8849 return *this;
8850}
8851
8852Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8853 CXString cursorName = clang_getCursorDisplayName(cursor);
8854 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8855 clang_disposeString(cursorName);
8856 return *this;
8857}
8858
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008859Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8860 CXFile File;
8861 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008862 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008863 CXString FileName = clang_getFileName(File);
8864 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8865 clang_disposeString(FileName);
8866 return *this;
8867}
8868
8869Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8870 CXSourceLocation BLoc = clang_getRangeStart(range);
8871 CXSourceLocation ELoc = clang_getRangeEnd(range);
8872
8873 CXFile BFile;
8874 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008875 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008876
8877 CXFile EFile;
8878 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008879 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008880
8881 CXString BFileName = clang_getFileName(BFile);
8882 if (BFile == EFile) {
8883 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8884 BLine, BColumn, ELine, EColumn);
8885 } else {
8886 CXString EFileName = clang_getFileName(EFile);
8887 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8888 BLine, BColumn)
8889 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8890 ELine, EColumn);
8891 clang_disposeString(EFileName);
8892 }
8893 clang_disposeString(BFileName);
8894 return *this;
8895}
8896
8897Logger &cxindex::Logger::operator<<(CXString Str) {
8898 *this << clang_getCString(Str);
8899 return *this;
8900}
8901
8902Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8903 LogOS << Fmt;
8904 return *this;
8905}
8906
Chandler Carruth37ad2582014-06-27 15:14:39 +00008907static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8908
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008909cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008910 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008911
8912 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8913
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008914 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008915 OS << "[libclang:" << Name << ':';
8916
Alp Toker1a86ad22014-07-06 06:24:00 +00008917#ifdef USE_DARWIN_THREADS
8918 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008919 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8920 OS << tid << ':';
8921#endif
8922
8923 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8924 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008925 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008926
8927 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008928 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008929 OS << "--------------------------------------------------\n";
8930 }
8931}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00008932
8933#ifdef CLANG_TOOL_EXTRA_BUILD
8934// This anchor is used to force the linker to link the clang-tidy plugin.
8935extern volatile int ClangTidyPluginAnchorSource;
8936static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8937 ClangTidyPluginAnchorSource;
8938
8939// This anchor is used to force the linker to link the clang-include-fixer
8940// plugin.
8941extern volatile int ClangIncludeFixerPluginAnchorSource;
8942static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8943 ClangIncludeFixerPluginAnchorSource;
8944#endif