blob: 499d9abf9a8ef024b8cc4b6733a84811ed74f701 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
Guy Benyei11169dd2012-12-18 14:30:41 +000015#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000017#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000029#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000030#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000031#include "clang/Basic/Version.h"
32#include "clang/Frontend/ASTUnit.h"
33#include "clang/Frontend/CompilerInstance.h"
34#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000035#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000036#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "clang/Lex/HeaderSearch.h"
38#include "clang/Lex/Lexer.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000041#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000042#include "llvm/ADT/Optional.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000045#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "llvm/Support/Compiler.h"
47#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000048#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000049#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000052#include "llvm/Support/Program.h"
53#include "llvm/Support/SaveAndRestore.h"
54#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000055#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include "llvm/Support/Threading.h"
57#include "llvm/Support/Timer.h"
58#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000059
Alp Toker1a86ad22014-07-06 06:24:00 +000060#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
61#define USE_DARWIN_THREADS
62#endif
63
64#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000065#include <pthread.h>
66#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000067
68using namespace clang;
69using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000070using namespace clang::cxtu;
71using namespace clang::cxindex;
72
David Blaikieea4395e2017-01-06 19:49:01 +000073CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
74 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000075 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000076 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000077 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000078 CXTranslationUnit D = new CXTranslationUnitImpl();
79 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000080 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000081 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000082 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000083 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000084 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000085 D->ParsingOptions = 0;
86 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000087 return D;
88}
89
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000090bool cxtu::isASTReadError(ASTUnit *AU) {
91 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
92 DEnd = AU->stored_diag_end();
93 D != DEnd; ++D) {
94 if (D->getLevel() >= DiagnosticsEngine::Error &&
95 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
96 diag::DiagCat_AST_Deserialization_Issue)
97 return true;
98 }
99 return false;
100}
101
Guy Benyei11169dd2012-12-18 14:30:41 +0000102cxtu::CXTUOwner::~CXTUOwner() {
103 if (TU)
104 clang_disposeTranslationUnit(TU);
105}
106
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000107/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000108/// the translation unit.
109static RangeComparisonResult RangeCompare(SourceManager &SM,
110 SourceRange R1,
111 SourceRange R2) {
112 assert(R1.isValid() && "First range is invalid?");
113 assert(R2.isValid() && "Second range is invalid?");
114 if (R1.getEnd() != R2.getBegin() &&
115 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
116 return RangeBefore;
117 if (R2.getEnd() != R1.getBegin() &&
118 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
119 return RangeAfter;
120 return RangeOverlap;
121}
122
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000123/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000124/// a given source range.
125static RangeComparisonResult LocationCompare(SourceManager &SM,
126 SourceLocation L, SourceRange R) {
127 assert(R.isValid() && "First range is invalid?");
128 assert(L.isValid() && "Second range is invalid?");
129 if (L == R.getBegin() || L == R.getEnd())
130 return RangeOverlap;
131 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
132 return RangeBefore;
133 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
134 return RangeAfter;
135 return RangeOverlap;
136}
137
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000138/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000139///
140/// Clang internally represents ranges where the end location points to the
141/// start of the token at the end. However, for external clients it is more
142/// useful to have a CXSourceRange be a proper half-open interval. This routine
143/// does the appropriate translation.
144CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
145 const LangOptions &LangOpts,
146 const CharSourceRange &R) {
147 // We want the last character in this location, so we will adjust the
148 // location accordingly.
149 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000150 bool IsTokenRange = R.isTokenRange();
151 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
152 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
153 EndLoc = Expansion.getEnd();
154 IsTokenRange = Expansion.isTokenRange();
155 }
156 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000157 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
158 SM, LangOpts);
159 EndLoc = EndLoc.getLocWithOffset(Length);
160 }
161
Bill Wendlingeade3622013-01-23 08:25:41 +0000162 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000163 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000164 R.getBegin().getRawEncoding(),
165 EndLoc.getRawEncoding()
166 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000167 return Result;
168}
169
170//===----------------------------------------------------------------------===//
171// Cursor visitor.
172//===----------------------------------------------------------------------===//
173
174static SourceRange getRawCursorExtent(CXCursor C);
175static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
176
177
178RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
179 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
180}
181
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000182/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000183/// its children.
184///
185/// \param Cursor the cursor to visit.
186///
187/// \param CheckedRegionOfInterest if true, then the caller already checked
188/// that this cursor is within the region of interest.
189///
190/// \returns true if the visitation should be aborted, false if it
191/// should continue.
192bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
193 if (clang_isInvalid(Cursor.kind))
194 return false;
195
196 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000197 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000198 if (!D) {
199 assert(0 && "Invalid declaration cursor");
200 return true; // abort.
201 }
202
203 // Ignore implicit declarations, unless it's an objc method because
204 // currently we should report implicit methods for properties when indexing.
205 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
206 return false;
207 }
208
209 // If we have a range of interest, and this cursor doesn't intersect with it,
210 // we're done.
211 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
212 SourceRange Range = getRawCursorExtent(Cursor);
213 if (Range.isInvalid() || CompareRegionOfInterest(Range))
214 return false;
215 }
216
217 switch (Visitor(Cursor, Parent, ClientData)) {
218 case CXChildVisit_Break:
219 return true;
220
221 case CXChildVisit_Continue:
222 return false;
223
224 case CXChildVisit_Recurse: {
225 bool ret = VisitChildren(Cursor);
226 if (PostChildrenVisitor)
227 if (PostChildrenVisitor(Cursor, ClientData))
228 return true;
229 return ret;
230 }
231 }
232
233 llvm_unreachable("Invalid CXChildVisitResult!");
234}
235
236static bool visitPreprocessedEntitiesInRange(SourceRange R,
237 PreprocessingRecord &PPRec,
238 CursorVisitor &Visitor) {
239 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
240 FileID FID;
241
242 if (!Visitor.shouldVisitIncludedEntities()) {
243 // If the begin/end of the range lie in the same FileID, do the optimization
244 // where we skip preprocessed entities that do not come from the same FileID.
245 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
246 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
247 FID = FileID();
248 }
249
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000250 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
251 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000252 PPRec, FID);
253}
254
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000255bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000256 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000257 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000258
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000259 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000260 SourceManager &SM = Unit->getSourceManager();
261
262 std::pair<FileID, unsigned>
263 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
264 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
265
266 if (End.first != Begin.first) {
267 // If the end does not reside in the same file, try to recover by
268 // picking the end of the file of begin location.
269 End.first = Begin.first;
270 End.second = SM.getFileIDSize(Begin.first);
271 }
272
273 assert(Begin.first == End.first);
274 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000275 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000276
277 FileID File = Begin.first;
278 unsigned Offset = Begin.second;
279 unsigned Length = End.second - Begin.second;
280
281 if (!VisitDeclsOnly && !VisitPreprocessorLast)
282 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000283 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000285 if (visitDeclsFromFileRegion(File, Offset, Length))
286 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000287
288 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000289 return visitPreprocessedEntitiesInRegion();
290
291 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000292}
293
294static bool isInLexicalContext(Decl *D, DeclContext *DC) {
295 if (!DC)
296 return false;
297
298 for (DeclContext *DeclDC = D->getLexicalDeclContext();
299 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
300 if (DeclDC == DC)
301 return true;
302 }
303 return false;
304}
305
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000306bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000307 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000308 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000309 SourceManager &SM = Unit->getSourceManager();
310 SourceRange Range = RegionOfInterest;
311
312 SmallVector<Decl *, 16> Decls;
313 Unit->findFileRegionDecls(File, Offset, Length, Decls);
314
315 // If we didn't find any file level decls for the file, try looking at the
316 // file that it was included from.
317 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
318 bool Invalid = false;
319 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
320 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000321 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000322
323 SourceLocation Outer;
324 if (SLEntry.isFile())
325 Outer = SLEntry.getFile().getIncludeLoc();
326 else
327 Outer = SLEntry.getExpansion().getExpansionLocStart();
328 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000329 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000330
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000331 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000332 Length = 0;
333 Unit->findFileRegionDecls(File, Offset, Length, Decls);
334 }
335
336 assert(!Decls.empty());
337
338 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000339 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000340 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
341 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000342 Decl *D = *DIt;
343 if (D->getSourceRange().isInvalid())
344 continue;
345
346 if (isInLexicalContext(D, CurDC))
347 continue;
348
349 CurDC = dyn_cast<DeclContext>(D);
350
351 if (TagDecl *TD = dyn_cast<TagDecl>(D))
352 if (!TD->isFreeStanding())
353 continue;
354
355 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
356 if (CompRes == RangeBefore)
357 continue;
358 if (CompRes == RangeAfter)
359 break;
360
361 assert(CompRes == RangeOverlap);
362 VisitedAtLeastOnce = true;
363
364 if (isa<ObjCContainerDecl>(D)) {
365 FileDI_current = &DIt;
366 FileDE_current = DE;
367 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000368 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000369 }
370
371 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000372 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000373 }
374
375 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000376 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000377
378 // No Decls overlapped with the range. Move up the lexical context until there
379 // is a context that contains the range or we reach the translation unit
380 // level.
381 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
382 : (*(DIt-1))->getLexicalDeclContext();
383
384 while (DC && !DC->isTranslationUnit()) {
385 Decl *D = cast<Decl>(DC);
386 SourceRange CurDeclRange = D->getSourceRange();
387 if (CurDeclRange.isInvalid())
388 break;
389
390 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000391 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
392 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 }
394
395 DC = D->getLexicalDeclContext();
396 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000397
398 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000399}
400
401bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
402 if (!AU->getPreprocessor().getPreprocessingRecord())
403 return false;
404
405 PreprocessingRecord &PPRec
406 = *AU->getPreprocessor().getPreprocessingRecord();
407 SourceManager &SM = AU->getSourceManager();
408
409 if (RegionOfInterest.isValid()) {
410 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
411 SourceLocation B = MappedRange.getBegin();
412 SourceLocation E = MappedRange.getEnd();
413
414 if (AU->isInPreambleFileID(B)) {
415 if (SM.isLoadedSourceLocation(E))
416 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
417 PPRec, *this);
418
419 // Beginning of range lies in the preamble but it also extends beyond
420 // it into the main file. Split the range into 2 parts, one covering
421 // the preamble and another covering the main file. This allows subsequent
422 // calls to visitPreprocessedEntitiesInRange to accept a source range that
423 // lies in the same FileID, allowing it to skip preprocessed entities that
424 // do not come from the same FileID.
425 bool breaked =
426 visitPreprocessedEntitiesInRange(
427 SourceRange(B, AU->getEndOfPreambleFileID()),
428 PPRec, *this);
429 if (breaked) return true;
430 return visitPreprocessedEntitiesInRange(
431 SourceRange(AU->getStartOfMainFileID(), E),
432 PPRec, *this);
433 }
434
435 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
436 }
437
438 bool OnlyLocalDecls
439 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
440
441 if (OnlyLocalDecls)
442 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
443 PPRec);
444
445 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
446}
447
448template<typename InputIterator>
449bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
450 InputIterator Last,
451 PreprocessingRecord &PPRec,
452 FileID FID) {
453 for (; First != Last; ++First) {
454 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
455 continue;
456
457 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000458 if (!PPE)
459 continue;
460
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
462 if (Visit(MakeMacroExpansionCursor(ME, TU)))
463 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000464
Guy Benyei11169dd2012-12-18 14:30:41 +0000465 continue;
466 }
Richard Smith66a81862015-05-04 02:25:31 +0000467
468 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000469 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
470 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000471
Guy Benyei11169dd2012-12-18 14:30:41 +0000472 continue;
473 }
474
475 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
476 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
477 return true;
478
479 continue;
480 }
481 }
482
483 return false;
484}
485
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000486/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000487///
488/// \returns true if the visitation should be aborted, false if it
489/// should continue.
490bool CursorVisitor::VisitChildren(CXCursor Cursor) {
491 if (clang_isReference(Cursor.kind) &&
492 Cursor.kind != CXCursor_CXXBaseSpecifier) {
493 // By definition, references have no children.
494 return false;
495 }
496
497 // Set the Parent field to Cursor, then back to its old value once we're
498 // done.
499 SetParentRAII SetParent(Parent, StmtParent, Cursor);
500
501 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000502 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000503 if (!D)
504 return false;
505
506 return VisitAttributes(D) || Visit(D);
507 }
508
509 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000510 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000511 return Visit(S);
512
513 return false;
514 }
515
516 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000517 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000518 return Visit(E);
519
520 return false;
521 }
522
523 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000524 CXTranslationUnit TU = getCursorTU(Cursor);
525 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000526
527 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
528 for (unsigned I = 0; I != 2; ++I) {
529 if (VisitOrder[I]) {
530 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
531 RegionOfInterest.isInvalid()) {
532 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
533 TLEnd = CXXUnit->top_level_end();
534 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000535 const Optional<bool> V = handleDeclForVisitation(*TL);
536 if (!V.hasValue())
537 continue;
538 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000539 }
540 } else if (VisitDeclContext(
541 CXXUnit->getASTContext().getTranslationUnitDecl()))
542 return true;
543 continue;
544 }
545
546 // Walk the preprocessing record.
547 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
548 visitPreprocessedEntitiesInRegion();
549 }
550
551 return false;
552 }
553
554 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000555 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000556 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
557 return Visit(BaseTSInfo->getTypeLoc());
558 }
559 }
560 }
561
562 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000563 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000565 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000566 return Visit(cxcursor::MakeCursorObjCClassRef(
567 ObjT->getInterface(),
568 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 }
570
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000571 // If pointing inside a macro definition, check if the token is an identifier
572 // that was ever defined as a macro. In such a case, create a "pseudo" macro
573 // expansion cursor for that token.
574 SourceLocation BeginLoc = RegionOfInterest.getBegin();
575 if (Cursor.kind == CXCursor_MacroDefinition &&
576 BeginLoc == RegionOfInterest.getEnd()) {
577 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000578 const MacroInfo *MI =
579 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000580 if (MacroDefinitionRecord *MacroDef =
581 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000582 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
583 }
584
Guy Benyei11169dd2012-12-18 14:30:41 +0000585 // Nothing to visit at the moment.
586 return false;
587}
588
589bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
590 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
591 if (Visit(TSInfo->getTypeLoc()))
592 return true;
593
594 if (Stmt *Body = B->getBody())
595 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
596
597 return false;
598}
599
Ted Kremenek03325582013-02-21 01:29:01 +0000600Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000601 if (RegionOfInterest.isValid()) {
602 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
603 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000604 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000605
606 switch (CompareRegionOfInterest(Range)) {
607 case RangeBefore:
608 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000609 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000610
611 case RangeAfter:
612 // This declaration comes after the region of interest; we're done.
613 return false;
614
615 case RangeOverlap:
616 // This declaration overlaps the region of interest; visit it.
617 break;
618 }
619 }
620 return true;
621}
622
623bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
624 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
625
626 // FIXME: Eventually remove. This part of a hack to support proper
627 // iteration over all Decls contained lexically within an ObjC container.
628 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
629 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
630
631 for ( ; I != E; ++I) {
632 Decl *D = *I;
633 if (D->getLexicalDeclContext() != DC)
634 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000635 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000636 if (!V.hasValue())
637 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000638 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 }
640 return false;
641}
642
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000643Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
644 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
645
646 // Ignore synthesized ivars here, otherwise if we have something like:
647 // @synthesize prop = _prop;
648 // and '_prop' is not declared, we will encounter a '_prop' ivar before
649 // encountering the 'prop' synthesize declaration and we will think that
650 // we passed the region-of-interest.
651 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
652 if (ivarD->getSynthesize())
653 return None;
654 }
655
656 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
657 // declarations is a mismatch with the compiler semantics.
658 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
659 auto *ID = cast<ObjCInterfaceDecl>(D);
660 if (!ID->isThisDeclarationADefinition())
661 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
662
663 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
664 auto *PD = cast<ObjCProtocolDecl>(D);
665 if (!PD->isThisDeclarationADefinition())
666 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
667 }
668
669 const Optional<bool> V = shouldVisitCursor(Cursor);
670 if (!V.hasValue())
671 return None;
672 if (!V.getValue())
673 return false;
674 if (Visit(Cursor, true))
675 return true;
676 return None;
677}
678
Guy Benyei11169dd2012-12-18 14:30:41 +0000679bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
680 llvm_unreachable("Translation units are visited directly by Visit()");
681}
682
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000683bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
684 if (VisitTemplateParameters(D->getTemplateParameters()))
685 return true;
686
687 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
688}
689
Guy Benyei11169dd2012-12-18 14:30:41 +0000690bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
691 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
692 return Visit(TSInfo->getTypeLoc());
693
694 return false;
695}
696
697bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
698 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
699 return Visit(TSInfo->getTypeLoc());
700
701 return false;
702}
703
704bool CursorVisitor::VisitTagDecl(TagDecl *D) {
705 return VisitDeclContext(D);
706}
707
708bool CursorVisitor::VisitClassTemplateSpecializationDecl(
709 ClassTemplateSpecializationDecl *D) {
710 bool ShouldVisitBody = false;
711 switch (D->getSpecializationKind()) {
712 case TSK_Undeclared:
713 case TSK_ImplicitInstantiation:
714 // Nothing to visit
715 return false;
716
717 case TSK_ExplicitInstantiationDeclaration:
718 case TSK_ExplicitInstantiationDefinition:
719 break;
720
721 case TSK_ExplicitSpecialization:
722 ShouldVisitBody = true;
723 break;
724 }
725
726 // Visit the template arguments used in the specialization.
727 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
728 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000729 if (TemplateSpecializationTypeLoc TSTLoc =
730 TL.getAs<TemplateSpecializationTypeLoc>()) {
731 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
732 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000733 return true;
734 }
735 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000736
737 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000738}
739
740bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
741 ClassTemplatePartialSpecializationDecl *D) {
742 // FIXME: Visit the "outer" template parameter lists on the TagDecl
743 // before visiting these template parameters.
744 if (VisitTemplateParameters(D->getTemplateParameters()))
745 return true;
746
747 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000748 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
749 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
750 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000751 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
752 return true;
753
754 return VisitCXXRecordDecl(D);
755}
756
757bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
758 // Visit the default argument.
759 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
760 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
761 if (Visit(DefArg->getTypeLoc()))
762 return true;
763
764 return false;
765}
766
767bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
768 if (Expr *Init = D->getInitExpr())
769 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
770 return false;
771}
772
773bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000774 unsigned NumParamList = DD->getNumTemplateParameterLists();
775 for (unsigned i = 0; i < NumParamList; i++) {
776 TemplateParameterList* Params = DD->getTemplateParameterList(i);
777 if (VisitTemplateParameters(Params))
778 return true;
779 }
780
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
782 if (Visit(TSInfo->getTypeLoc()))
783 return true;
784
785 // Visit the nested-name-specifier, if present.
786 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
787 if (VisitNestedNameSpecifierLoc(QualifierLoc))
788 return true;
789
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000790 return false;
791}
792
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000793static bool HasTrailingReturnType(FunctionDecl *ND) {
794 const QualType Ty = ND->getType();
795 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
796 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
797 return FT->hasTrailingReturn();
798 }
799
800 return false;
801}
802
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000803/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000804static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
805 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000806 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
807}
808
Guy Benyei11169dd2012-12-18 14:30:41 +0000809bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000810 unsigned NumParamList = ND->getNumTemplateParameterLists();
811 for (unsigned i = 0; i < NumParamList; i++) {
812 TemplateParameterList* Params = ND->getTemplateParameterList(i);
813 if (VisitTemplateParameters(Params))
814 return true;
815 }
816
Guy Benyei11169dd2012-12-18 14:30:41 +0000817 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
818 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000819 // written. This requires a bit of work.
820 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
821 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000822 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000823
824 // If we have a function declared directly (without the use of a typedef),
825 // visit just the return type. Otherwise, just visit the function's type
826 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000827 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
828 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000829 (!FTL && Visit(TL)))
830 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000831
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000832 // Visit the nested-name-specifier, if present.
833 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
834 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 return true;
836
837 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000838 if (!isa<CXXDestructorDecl>(ND))
839 if (VisitDeclarationNameInfo(ND->getNameInfo()))
840 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000841
842 // FIXME: Visit explicitly-specified template arguments!
843
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000844 // Visit the function parameters, if we have a function type.
845 if (FTL && VisitFunctionTypeLoc(FTL, true))
846 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000847
848 // Visit the function's trailing return type.
849 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
850 return true;
851
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000852 // FIXME: Attributes?
853 }
854
Guy Benyei11169dd2012-12-18 14:30:41 +0000855 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
856 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
857 // Find the initializers that were written in the source.
858 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000859 for (auto *I : Constructor->inits()) {
860 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000861 continue;
862
Aaron Ballman0ad78302014-03-13 17:34:31 +0000863 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 }
865
866 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000867 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
868 &CompareCXXCtorInitializers);
869
Guy Benyei11169dd2012-12-18 14:30:41 +0000870 // Visit the initializers in source order
871 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
872 CXXCtorInitializer *Init = WrittenInits[I];
873 if (Init->isAnyMemberInitializer()) {
874 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
875 Init->getMemberLocation(), TU)))
876 return true;
877 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
878 if (Visit(TInfo->getTypeLoc()))
879 return true;
880 }
881
882 // Visit the initializer value.
883 if (Expr *Initializer = Init->getInit())
884 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
885 return true;
886 }
887 }
888
889 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
890 return true;
891 }
892
893 return false;
894}
895
896bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
897 if (VisitDeclaratorDecl(D))
898 return true;
899
900 if (Expr *BitWidth = D->getBitWidth())
901 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
902
Benjamin Kramer99f97592017-11-15 12:20:41 +0000903 if (Expr *Init = D->getInClassInitializer())
904 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
905
Guy Benyei11169dd2012-12-18 14:30:41 +0000906 return false;
907}
908
909bool CursorVisitor::VisitVarDecl(VarDecl *D) {
910 if (VisitDeclaratorDecl(D))
911 return true;
912
913 if (Expr *Init = D->getInit())
914 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
915
916 return false;
917}
918
919bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
920 if (VisitDeclaratorDecl(D))
921 return true;
922
923 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
924 if (Expr *DefArg = D->getDefaultArgument())
925 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
926
927 return false;
928}
929
930bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
931 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
932 // before visiting these template parameters.
933 if (VisitTemplateParameters(D->getTemplateParameters()))
934 return true;
935
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000936 auto* FD = D->getTemplatedDecl();
937 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000938}
939
940bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
941 // FIXME: Visit the "outer" template parameter lists on the TagDecl
942 // before visiting these template parameters.
943 if (VisitTemplateParameters(D->getTemplateParameters()))
944 return true;
945
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000946 auto* CD = D->getTemplatedDecl();
947 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000948}
949
950bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
951 if (VisitTemplateParameters(D->getTemplateParameters()))
952 return true;
953
954 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
955 VisitTemplateArgumentLoc(D->getDefaultArgument()))
956 return true;
957
958 return false;
959}
960
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000961bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
962 // Visit the bound, if it's explicit.
963 if (D->hasExplicitBound()) {
964 if (auto TInfo = D->getTypeSourceInfo()) {
965 if (Visit(TInfo->getTypeLoc()))
966 return true;
967 }
968 }
969
970 return false;
971}
972
Guy Benyei11169dd2012-12-18 14:30:41 +0000973bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000974 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 if (Visit(TSInfo->getTypeLoc()))
976 return true;
977
David Majnemer59f77922016-06-24 04:05:48 +0000978 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000979 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000980 return true;
981 }
982
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000983 return ND->isThisDeclarationADefinition() &&
984 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000985}
986
987template <typename DeclIt>
988static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
989 SourceManager &SM, SourceLocation EndLoc,
990 SmallVectorImpl<Decl *> &Decls) {
991 DeclIt next = *DI_current;
992 while (++next != DE_current) {
993 Decl *D_next = *next;
994 if (!D_next)
995 break;
996 SourceLocation L = D_next->getLocStart();
997 if (!L.isValid())
998 break;
999 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1000 *DI_current = next;
1001 Decls.push_back(D_next);
1002 continue;
1003 }
1004 break;
1005 }
1006}
1007
Guy Benyei11169dd2012-12-18 14:30:41 +00001008bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1009 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1010 // an @implementation can lexically contain Decls that are not properly
1011 // nested in the AST. When we identify such cases, we need to retrofit
1012 // this nesting here.
1013 if (!DI_current && !FileDI_current)
1014 return VisitDeclContext(D);
1015
1016 // Scan the Decls that immediately come after the container
1017 // in the current DeclContext. If any fall within the
1018 // container's lexical region, stash them into a vector
1019 // for later processing.
1020 SmallVector<Decl *, 24> DeclsInContainer;
1021 SourceLocation EndLoc = D->getSourceRange().getEnd();
1022 SourceManager &SM = AU->getSourceManager();
1023 if (EndLoc.isValid()) {
1024 if (DI_current) {
1025 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1026 DeclsInContainer);
1027 } else {
1028 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1029 DeclsInContainer);
1030 }
1031 }
1032
1033 // The common case.
1034 if (DeclsInContainer.empty())
1035 return VisitDeclContext(D);
1036
1037 // Get all the Decls in the DeclContext, and sort them with the
1038 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001039 for (auto *SubDecl : D->decls()) {
1040 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1041 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001042 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001043 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 }
1045
1046 // Now sort the Decls so that they appear in lexical order.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001047 llvm::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1048 [&SM](Decl *A, Decl *B) {
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001049 SourceLocation L_A = A->getLocStart();
1050 SourceLocation L_B = B->getLocStart();
Mandeep Singh Grangfa51e1d2017-11-29 20:55:13 +00001051 return L_A != L_B ?
1052 SM.isBeforeInTranslationUnit(L_A, L_B) :
1053 SM.isBeforeInTranslationUnit(A->getLocEnd(), B->getLocEnd());
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001054 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001055
1056 // Now visit the decls.
1057 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1058 E = DeclsInContainer.end(); I != E; ++I) {
1059 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001060 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001061 if (!V.hasValue())
1062 continue;
1063 if (!V.getValue())
1064 return false;
1065 if (Visit(Cursor, true))
1066 return true;
1067 }
1068 return false;
1069}
1070
1071bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1072 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1073 TU)))
1074 return true;
1075
Douglas Gregore9d95f12015-07-07 03:57:35 +00001076 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1077 return true;
1078
Guy Benyei11169dd2012-12-18 14:30:41 +00001079 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1080 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1081 E = ND->protocol_end(); I != E; ++I, ++PL)
1082 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1083 return true;
1084
1085 return VisitObjCContainerDecl(ND);
1086}
1087
1088bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1089 if (!PID->isThisDeclarationADefinition())
1090 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1091
1092 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1093 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1094 E = PID->protocol_end(); I != E; ++I, ++PL)
1095 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1096 return true;
1097
1098 return VisitObjCContainerDecl(PID);
1099}
1100
1101bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1102 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1103 return true;
1104
1105 // FIXME: This implements a workaround with @property declarations also being
1106 // installed in the DeclContext for the @interface. Eventually this code
1107 // should be removed.
1108 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1109 if (!CDecl || !CDecl->IsClassExtension())
1110 return false;
1111
1112 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1113 if (!ID)
1114 return false;
1115
1116 IdentifierInfo *PropertyId = PD->getIdentifier();
1117 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001118 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1119 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001120
1121 if (!prevDecl)
1122 return false;
1123
1124 // Visit synthesized methods since they will be skipped when visiting
1125 // the @interface.
1126 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1127 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1128 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1129 return true;
1130
1131 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1132 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1133 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1134 return true;
1135
1136 return false;
1137}
1138
Douglas Gregore9d95f12015-07-07 03:57:35 +00001139bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1140 if (!typeParamList)
1141 return false;
1142
1143 for (auto *typeParam : *typeParamList) {
1144 // Visit the type parameter.
1145 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1146 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001147 }
1148
1149 return false;
1150}
1151
Guy Benyei11169dd2012-12-18 14:30:41 +00001152bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1153 if (!D->isThisDeclarationADefinition()) {
1154 // Forward declaration is treated like a reference.
1155 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1156 }
1157
Douglas Gregore9d95f12015-07-07 03:57:35 +00001158 // Objective-C type parameters.
1159 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1160 return true;
1161
Guy Benyei11169dd2012-12-18 14:30:41 +00001162 // Issue callbacks for super class.
1163 if (D->getSuperClass() &&
1164 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1165 D->getSuperClassLoc(),
1166 TU)))
1167 return true;
1168
Douglas Gregore9d95f12015-07-07 03:57:35 +00001169 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1170 if (Visit(SuperClassTInfo->getTypeLoc()))
1171 return true;
1172
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1174 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1175 E = D->protocol_end(); I != E; ++I, ++PL)
1176 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1177 return true;
1178
1179 return VisitObjCContainerDecl(D);
1180}
1181
1182bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1183 return VisitObjCContainerDecl(D);
1184}
1185
1186bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1187 // 'ID' could be null when dealing with invalid code.
1188 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1189 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1190 return true;
1191
1192 return VisitObjCImplDecl(D);
1193}
1194
1195bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1196#if 0
1197 // Issue callbacks for super class.
1198 // FIXME: No source location information!
1199 if (D->getSuperClass() &&
1200 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1201 D->getSuperClassLoc(),
1202 TU)))
1203 return true;
1204#endif
1205
1206 return VisitObjCImplDecl(D);
1207}
1208
1209bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1210 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1211 if (PD->isIvarNameSpecified())
1212 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1213
1214 return false;
1215}
1216
1217bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1218 return VisitDeclContext(D);
1219}
1220
1221bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1222 // Visit nested-name-specifier.
1223 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1224 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1225 return true;
1226
1227 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1228 D->getTargetNameLoc(), TU));
1229}
1230
1231bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1232 // Visit nested-name-specifier.
1233 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1234 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1235 return true;
1236 }
1237
1238 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1239 return true;
1240
1241 return VisitDeclarationNameInfo(D->getNameInfo());
1242}
1243
1244bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1245 // Visit nested-name-specifier.
1246 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1247 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1248 return true;
1249
1250 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1251 D->getIdentLocation(), TU));
1252}
1253
1254bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1255 // Visit nested-name-specifier.
1256 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1257 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1258 return true;
1259 }
1260
1261 return VisitDeclarationNameInfo(D->getNameInfo());
1262}
1263
1264bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1265 UnresolvedUsingTypenameDecl *D) {
1266 // Visit nested-name-specifier.
1267 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1268 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1269 return true;
1270
1271 return false;
1272}
1273
Olivier Goffart81978012016-06-09 16:15:55 +00001274bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1275 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1276 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001277 if (StringLiteral *Message = D->getMessage())
1278 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1279 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001280 return false;
1281}
1282
Olivier Goffartd211c642016-11-04 06:29:27 +00001283bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1284 if (NamedDecl *FriendD = D->getFriendDecl()) {
1285 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1286 return true;
1287 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1288 if (Visit(TI->getTypeLoc()))
1289 return true;
1290 }
1291 return false;
1292}
1293
Guy Benyei11169dd2012-12-18 14:30:41 +00001294bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1295 switch (Name.getName().getNameKind()) {
1296 case clang::DeclarationName::Identifier:
1297 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001298 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 case clang::DeclarationName::CXXOperatorName:
1300 case clang::DeclarationName::CXXUsingDirective:
1301 return false;
Richard Smith35845152017-02-07 01:37:30 +00001302
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 case clang::DeclarationName::CXXConstructorName:
1304 case clang::DeclarationName::CXXDestructorName:
1305 case clang::DeclarationName::CXXConversionFunctionName:
1306 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1307 return Visit(TSInfo->getTypeLoc());
1308 return false;
1309
1310 case clang::DeclarationName::ObjCZeroArgSelector:
1311 case clang::DeclarationName::ObjCOneArgSelector:
1312 case clang::DeclarationName::ObjCMultiArgSelector:
1313 // FIXME: Per-identifier location info?
1314 return false;
1315 }
1316
1317 llvm_unreachable("Invalid DeclarationName::Kind!");
1318}
1319
1320bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1321 SourceRange Range) {
1322 // FIXME: This whole routine is a hack to work around the lack of proper
1323 // source information in nested-name-specifiers (PR5791). Since we do have
1324 // a beginning source location, we can visit the first component of the
1325 // nested-name-specifier, if it's a single-token component.
1326 if (!NNS)
1327 return false;
1328
1329 // Get the first component in the nested-name-specifier.
1330 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1331 NNS = Prefix;
1332
1333 switch (NNS->getKind()) {
1334 case NestedNameSpecifier::Namespace:
1335 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1336 TU));
1337
1338 case NestedNameSpecifier::NamespaceAlias:
1339 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1340 Range.getBegin(), TU));
1341
1342 case NestedNameSpecifier::TypeSpec: {
1343 // If the type has a form where we know that the beginning of the source
1344 // range matches up with a reference cursor. Visit the appropriate reference
1345 // cursor.
1346 const Type *T = NNS->getAsType();
1347 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1348 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1349 if (const TagType *Tag = dyn_cast<TagType>(T))
1350 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1351 if (const TemplateSpecializationType *TST
1352 = dyn_cast<TemplateSpecializationType>(T))
1353 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1354 break;
1355 }
1356
1357 case NestedNameSpecifier::TypeSpecWithTemplate:
1358 case NestedNameSpecifier::Global:
1359 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001360 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001361 break;
1362 }
1363
1364 return false;
1365}
1366
1367bool
1368CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1369 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1370 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1371 Qualifiers.push_back(Qualifier);
1372
1373 while (!Qualifiers.empty()) {
1374 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1375 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1376 switch (NNS->getKind()) {
1377 case NestedNameSpecifier::Namespace:
1378 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1379 Q.getLocalBeginLoc(),
1380 TU)))
1381 return true;
1382
1383 break;
1384
1385 case NestedNameSpecifier::NamespaceAlias:
1386 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1387 Q.getLocalBeginLoc(),
1388 TU)))
1389 return true;
1390
1391 break;
1392
1393 case NestedNameSpecifier::TypeSpec:
1394 case NestedNameSpecifier::TypeSpecWithTemplate:
1395 if (Visit(Q.getTypeLoc()))
1396 return true;
1397
1398 break;
1399
1400 case NestedNameSpecifier::Global:
1401 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001402 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 break;
1404 }
1405 }
1406
1407 return false;
1408}
1409
1410bool CursorVisitor::VisitTemplateParameters(
1411 const TemplateParameterList *Params) {
1412 if (!Params)
1413 return false;
1414
1415 for (TemplateParameterList::const_iterator P = Params->begin(),
1416 PEnd = Params->end();
1417 P != PEnd; ++P) {
1418 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1419 return true;
1420 }
1421
1422 return false;
1423}
1424
1425bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1426 switch (Name.getKind()) {
1427 case TemplateName::Template:
1428 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1429
1430 case TemplateName::OverloadedTemplate:
1431 // Visit the overloaded template set.
1432 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1433 return true;
1434
1435 return false;
1436
1437 case TemplateName::DependentTemplate:
1438 // FIXME: Visit nested-name-specifier.
1439 return false;
1440
1441 case TemplateName::QualifiedTemplate:
1442 // FIXME: Visit nested-name-specifier.
1443 return Visit(MakeCursorTemplateRef(
1444 Name.getAsQualifiedTemplateName()->getDecl(),
1445 Loc, TU));
1446
1447 case TemplateName::SubstTemplateTemplateParm:
1448 return Visit(MakeCursorTemplateRef(
1449 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1450 Loc, TU));
1451
1452 case TemplateName::SubstTemplateTemplateParmPack:
1453 return Visit(MakeCursorTemplateRef(
1454 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1455 Loc, TU));
1456 }
1457
1458 llvm_unreachable("Invalid TemplateName::Kind!");
1459}
1460
1461bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1462 switch (TAL.getArgument().getKind()) {
1463 case TemplateArgument::Null:
1464 case TemplateArgument::Integral:
1465 case TemplateArgument::Pack:
1466 return false;
1467
1468 case TemplateArgument::Type:
1469 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1470 return Visit(TSInfo->getTypeLoc());
1471 return false;
1472
1473 case TemplateArgument::Declaration:
1474 if (Expr *E = TAL.getSourceDeclExpression())
1475 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1476 return false;
1477
1478 case TemplateArgument::NullPtr:
1479 if (Expr *E = TAL.getSourceNullPtrExpression())
1480 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1481 return false;
1482
1483 case TemplateArgument::Expression:
1484 if (Expr *E = TAL.getSourceExpression())
1485 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1486 return false;
1487
1488 case TemplateArgument::Template:
1489 case TemplateArgument::TemplateExpansion:
1490 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1491 return true;
1492
1493 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1494 TAL.getTemplateNameLoc());
1495 }
1496
1497 llvm_unreachable("Invalid TemplateArgument::Kind!");
1498}
1499
1500bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1501 return VisitDeclContext(D);
1502}
1503
1504bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1505 return Visit(TL.getUnqualifiedLoc());
1506}
1507
1508bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1509 ASTContext &Context = AU->getASTContext();
1510
1511 // Some builtin types (such as Objective-C's "id", "sel", and
1512 // "Class") have associated declarations. Create cursors for those.
1513 QualType VisitType;
1514 switch (TL.getTypePtr()->getKind()) {
1515
1516 case BuiltinType::Void:
1517 case BuiltinType::NullPtr:
1518 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001519#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1520 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001521#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001522 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001523 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001524 case BuiltinType::OCLClkEvent:
1525 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001526 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001527#define BUILTIN_TYPE(Id, SingletonId)
1528#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1529#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1530#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1531#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1532#include "clang/AST/BuiltinTypes.def"
1533 break;
1534
1535 case BuiltinType::ObjCId:
1536 VisitType = Context.getObjCIdType();
1537 break;
1538
1539 case BuiltinType::ObjCClass:
1540 VisitType = Context.getObjCClassType();
1541 break;
1542
1543 case BuiltinType::ObjCSel:
1544 VisitType = Context.getObjCSelType();
1545 break;
1546 }
1547
1548 if (!VisitType.isNull()) {
1549 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1550 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1551 TU));
1552 }
1553
1554 return false;
1555}
1556
1557bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1558 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1559}
1560
1561bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1562 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1563}
1564
1565bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1566 if (TL.isDefinition())
1567 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1568
1569 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1570}
1571
1572bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1573 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1574}
1575
1576bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001577 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001578}
1579
Manman Rene6be26c2016-09-13 17:25:08 +00001580bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1581 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1582 return true;
1583 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1584 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1585 TU)))
1586 return true;
1587 }
1588
1589 return false;
1590}
1591
Guy Benyei11169dd2012-12-18 14:30:41 +00001592bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1593 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1594 return true;
1595
Douglas Gregore9d95f12015-07-07 03:57:35 +00001596 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1597 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1598 return true;
1599 }
1600
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1602 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1603 TU)))
1604 return true;
1605 }
1606
1607 return false;
1608}
1609
1610bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1611 return Visit(TL.getPointeeLoc());
1612}
1613
1614bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1615 return Visit(TL.getInnerLoc());
1616}
1617
1618bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1619 return Visit(TL.getPointeeLoc());
1620}
1621
1622bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1623 return Visit(TL.getPointeeLoc());
1624}
1625
1626bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1627 return Visit(TL.getPointeeLoc());
1628}
1629
1630bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1631 return Visit(TL.getPointeeLoc());
1632}
1633
1634bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1635 return Visit(TL.getPointeeLoc());
1636}
1637
1638bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1639 return Visit(TL.getModifiedLoc());
1640}
1641
1642bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1643 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001644 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 return true;
1646
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001647 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1648 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1650 return true;
1651
1652 return false;
1653}
1654
1655bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1656 if (Visit(TL.getElementLoc()))
1657 return true;
1658
1659 if (Expr *Size = TL.getSizeExpr())
1660 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1661
1662 return false;
1663}
1664
Reid Kleckner8a365022013-06-24 17:51:48 +00001665bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1666 return Visit(TL.getOriginalLoc());
1667}
1668
Reid Kleckner0503a872013-12-05 01:23:43 +00001669bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1670 return Visit(TL.getOriginalLoc());
1671}
1672
Richard Smith600b5262017-01-26 20:40:47 +00001673bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1674 DeducedTemplateSpecializationTypeLoc TL) {
1675 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1676 TL.getTemplateNameLoc()))
1677 return true;
1678
1679 return false;
1680}
1681
Guy Benyei11169dd2012-12-18 14:30:41 +00001682bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1683 TemplateSpecializationTypeLoc TL) {
1684 // Visit the template name.
1685 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1686 TL.getTemplateNameLoc()))
1687 return true;
1688
1689 // Visit the template arguments.
1690 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1691 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1692 return true;
1693
1694 return false;
1695}
1696
1697bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1698 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1699}
1700
1701bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1702 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1703 return Visit(TSInfo->getTypeLoc());
1704
1705 return false;
1706}
1707
1708bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1709 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1710 return Visit(TSInfo->getTypeLoc());
1711
1712 return false;
1713}
1714
1715bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001716 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001717}
1718
1719bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1720 DependentTemplateSpecializationTypeLoc TL) {
1721 // Visit the nested-name-specifier, if there is one.
1722 if (TL.getQualifierLoc() &&
1723 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1724 return true;
1725
1726 // Visit the template arguments.
1727 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1728 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1729 return true;
1730
1731 return false;
1732}
1733
1734bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1735 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1736 return true;
1737
1738 return Visit(TL.getNamedTypeLoc());
1739}
1740
1741bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1742 return Visit(TL.getPatternLoc());
1743}
1744
1745bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1746 if (Expr *E = TL.getUnderlyingExpr())
1747 return Visit(MakeCXCursor(E, StmtParent, TU));
1748
1749 return false;
1750}
1751
1752bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1753 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1754}
1755
1756bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1757 return Visit(TL.getValueLoc());
1758}
1759
Xiuli Pan9c14e282016-01-09 12:53:17 +00001760bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1761 return Visit(TL.getValueLoc());
1762}
1763
Guy Benyei11169dd2012-12-18 14:30:41 +00001764#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1765bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1766 return Visit##PARENT##Loc(TL); \
1767}
1768
1769DEFAULT_TYPELOC_IMPL(Complex, Type)
1770DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1771DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1772DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1773DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001774DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001775DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001776DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1777DEFAULT_TYPELOC_IMPL(Vector, Type)
1778DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1779DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1780DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1781DEFAULT_TYPELOC_IMPL(Record, TagType)
1782DEFAULT_TYPELOC_IMPL(Enum, TagType)
1783DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1784DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1785DEFAULT_TYPELOC_IMPL(Auto, Type)
1786
1787bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1788 // Visit the nested-name-specifier, if present.
1789 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1790 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1791 return true;
1792
1793 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001794 for (const auto &I : D->bases()) {
1795 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 return true;
1797 }
1798 }
1799
1800 return VisitTagDecl(D);
1801}
1802
1803bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001804 for (const auto *I : D->attrs())
Erik Verbruggenc068e902018-04-24 08:39:46 +00001805 if (!I->isImplicit() && Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001806 return true;
1807
1808 return false;
1809}
1810
1811//===----------------------------------------------------------------------===//
1812// Data-recursive visitor methods.
1813//===----------------------------------------------------------------------===//
1814
1815namespace {
1816#define DEF_JOB(NAME, DATA, KIND)\
1817class NAME : public VisitorJob {\
1818public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001819 NAME(const DATA *d, CXCursor parent) : \
1820 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001821 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001822 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001823};
1824
1825DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1826DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1827DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1828DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001829DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1830DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1831DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1832#undef DEF_JOB
1833
James Y Knight04ec5bf2015-12-24 02:59:37 +00001834class ExplicitTemplateArgsVisit : public VisitorJob {
1835public:
1836 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1837 const TemplateArgumentLoc *End, CXCursor parent)
1838 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1839 End) {}
1840 static bool classof(const VisitorJob *VJ) {
1841 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1842 }
1843 const TemplateArgumentLoc *begin() const {
1844 return static_cast<const TemplateArgumentLoc *>(data[0]);
1845 }
1846 const TemplateArgumentLoc *end() {
1847 return static_cast<const TemplateArgumentLoc *>(data[1]);
1848 }
1849};
Guy Benyei11169dd2012-12-18 14:30:41 +00001850class DeclVisit : public VisitorJob {
1851public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001852 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001853 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001854 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001855 static bool classof(const VisitorJob *VJ) {
1856 return VJ->getKind() == DeclVisitKind;
1857 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001858 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001859 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001860};
1861class TypeLocVisit : public VisitorJob {
1862public:
1863 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1864 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1865 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1866
1867 static bool classof(const VisitorJob *VJ) {
1868 return VJ->getKind() == TypeLocVisitKind;
1869 }
1870
1871 TypeLoc get() const {
1872 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001873 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001874 }
1875};
1876
1877class LabelRefVisit : public VisitorJob {
1878public:
1879 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1880 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1881 labelLoc.getPtrEncoding()) {}
1882
1883 static bool classof(const VisitorJob *VJ) {
1884 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1885 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001886 const LabelDecl *get() const {
1887 return static_cast<const LabelDecl *>(data[0]);
1888 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001889 SourceLocation getLoc() const {
1890 return SourceLocation::getFromPtrEncoding(data[1]); }
1891};
1892
1893class NestedNameSpecifierLocVisit : public VisitorJob {
1894public:
1895 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1896 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1897 Qualifier.getNestedNameSpecifier(),
1898 Qualifier.getOpaqueData()) { }
1899
1900 static bool classof(const VisitorJob *VJ) {
1901 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1902 }
1903
1904 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001905 return NestedNameSpecifierLoc(
1906 const_cast<NestedNameSpecifier *>(
1907 static_cast<const NestedNameSpecifier *>(data[0])),
1908 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001909 }
1910};
1911
1912class DeclarationNameInfoVisit : public VisitorJob {
1913public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001914 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001915 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001916 static bool classof(const VisitorJob *VJ) {
1917 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1918 }
1919 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001920 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 switch (S->getStmtClass()) {
1922 default:
1923 llvm_unreachable("Unhandled Stmt");
1924 case clang::Stmt::MSDependentExistsStmtClass:
1925 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1926 case Stmt::CXXDependentScopeMemberExprClass:
1927 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1928 case Stmt::DependentScopeDeclRefExprClass:
1929 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001930 case Stmt::OMPCriticalDirectiveClass:
1931 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001932 }
1933 }
1934};
1935class MemberRefVisit : public VisitorJob {
1936public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001937 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001938 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1939 L.getPtrEncoding()) {}
1940 static bool classof(const VisitorJob *VJ) {
1941 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1942 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001943 const FieldDecl *get() const {
1944 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001945 }
1946 SourceLocation getLoc() const {
1947 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1948 }
1949};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001950class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001951 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001952 VisitorWorkList &WL;
1953 CXCursor Parent;
1954public:
1955 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1956 : WL(wl), Parent(parent) {}
1957
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001958 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1959 void VisitBlockExpr(const BlockExpr *B);
1960 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1961 void VisitCompoundStmt(const CompoundStmt *S);
1962 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1963 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1964 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1965 void VisitCXXNewExpr(const CXXNewExpr *E);
1966 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1967 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1968 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1969 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1970 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1971 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1972 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1973 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001974 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001975 void VisitDeclRefExpr(const DeclRefExpr *D);
1976 void VisitDeclStmt(const DeclStmt *S);
1977 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1978 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1979 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1980 void VisitForStmt(const ForStmt *FS);
1981 void VisitGotoStmt(const GotoStmt *GS);
1982 void VisitIfStmt(const IfStmt *If);
1983 void VisitInitListExpr(const InitListExpr *IE);
1984 void VisitMemberExpr(const MemberExpr *M);
1985 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1986 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1987 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1988 void VisitOverloadExpr(const OverloadExpr *E);
1989 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1990 void VisitStmt(const Stmt *S);
1991 void VisitSwitchStmt(const SwitchStmt *S);
1992 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001993 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1994 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1995 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1996 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1997 void VisitVAArgExpr(const VAArgExpr *E);
1998 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1999 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2000 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2001 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002002 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002003 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002004 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002005 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002006 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002007 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002008 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002009 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002010 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002011 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002012 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002013 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002014 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002015 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002016 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002017 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002018 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002019 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002020 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002021 void
2022 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002023 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002024 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002025 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002026 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002027 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002028 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002029 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002030 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002031 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002032 void
2033 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002034 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002035 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002036 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002037 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002038 void VisitOMPDistributeParallelForDirective(
2039 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002040 void VisitOMPDistributeParallelForSimdDirective(
2041 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002042 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002043 void VisitOMPTargetParallelForSimdDirective(
2044 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002045 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002046 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002047 void VisitOMPTeamsDistributeSimdDirective(
2048 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002049 void VisitOMPTeamsDistributeParallelForSimdDirective(
2050 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002051 void VisitOMPTeamsDistributeParallelForDirective(
2052 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002053 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002054 void VisitOMPTargetTeamsDistributeDirective(
2055 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002056 void VisitOMPTargetTeamsDistributeParallelForDirective(
2057 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002058 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2059 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002060 void VisitOMPTargetTeamsDistributeSimdDirective(
2061 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002062
Guy Benyei11169dd2012-12-18 14:30:41 +00002063private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002064 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002065 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002066 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2067 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002068 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2069 void AddStmt(const Stmt *S);
2070 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002071 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002072 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002073 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002074};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002075} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002076
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002077void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 // 'S' should always be non-null, since it comes from the
2079 // statement we are visiting.
2080 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2081}
2082
2083void
2084EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2085 if (Qualifier)
2086 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2087}
2088
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002089void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002090 if (S)
2091 WL.push_back(StmtVisit(S, Parent));
2092}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002093void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002094 if (D)
2095 WL.push_back(DeclVisit(D, Parent, isFirst));
2096}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002097void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2098 unsigned NumTemplateArgs) {
2099 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002100}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002101void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002102 if (D)
2103 WL.push_back(MemberRefVisit(D, L, Parent));
2104}
2105void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2106 if (TI)
2107 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2108 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002109void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002110 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002111 for (const Stmt *SubStmt : S->children()) {
2112 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002113 }
2114 if (size == WL.size())
2115 return;
2116 // Now reverse the entries we just added. This will match the DFS
2117 // ordering performed by the worklist.
2118 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2119 std::reverse(I, E);
2120}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002121namespace {
2122class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2123 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002124 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002125 template <typename T>
2126 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002127public:
2128 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2129#define OPENMP_CLAUSE(Name, Class) \
2130 void Visit##Class(const Class *C);
2131#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002132 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002133 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002134};
2135
Alexey Bataev3392d762016-02-16 11:18:12 +00002136void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2137 const OMPClauseWithPreInit *C) {
2138 Visitor->AddStmt(C->getPreInitStmt());
2139}
2140
Alexey Bataev005248a2016-02-25 05:25:57 +00002141void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2142 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002143 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002144 Visitor->AddStmt(C->getPostUpdateExpr());
2145}
2146
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002147void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002148 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002149 Visitor->AddStmt(C->getCondition());
2150}
2151
Alexey Bataev3778b602014-07-17 07:32:53 +00002152void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2153 Visitor->AddStmt(C->getCondition());
2154}
2155
Alexey Bataev568a8332014-03-06 06:15:19 +00002156void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002157 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002158 Visitor->AddStmt(C->getNumThreads());
2159}
2160
Alexey Bataev62c87d22014-03-21 04:51:18 +00002161void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2162 Visitor->AddStmt(C->getSafelen());
2163}
2164
Alexey Bataev66b15b52015-08-21 11:14:16 +00002165void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2166 Visitor->AddStmt(C->getSimdlen());
2167}
2168
Alexander Musman8bd31e62014-05-27 15:12:19 +00002169void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2170 Visitor->AddStmt(C->getNumForLoops());
2171}
2172
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002173void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002174
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002175void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2176
Alexey Bataev56dafe82014-06-20 07:16:17 +00002177void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002178 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002179 Visitor->AddStmt(C->getChunkSize());
2180}
2181
Alexey Bataev10e775f2015-07-30 11:36:16 +00002182void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2183 Visitor->AddStmt(C->getNumForLoops());
2184}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002185
Alexey Bataev236070f2014-06-20 11:19:47 +00002186void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2187
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002188void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2189
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002190void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2191
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002192void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2193
Alexey Bataevdea47612014-07-23 07:46:59 +00002194void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2195
Alexey Bataev67a4f222014-07-23 10:25:33 +00002196void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2197
Alexey Bataev459dec02014-07-24 06:46:57 +00002198void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2199
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002200void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2201
Alexey Bataev346265e2015-09-25 10:37:12 +00002202void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2203
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002204void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2205
Alexey Bataevb825de12015-12-07 10:51:44 +00002206void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2207
Michael Wonge710d542015-08-07 16:16:36 +00002208void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2209 Visitor->AddStmt(C->getDevice());
2210}
2211
Kelvin Li099bb8c2015-11-24 20:50:12 +00002212void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002213 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002214 Visitor->AddStmt(C->getNumTeams());
2215}
2216
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002217void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002218 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002219 Visitor->AddStmt(C->getThreadLimit());
2220}
2221
Alexey Bataeva0569352015-12-01 10:17:31 +00002222void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2223 Visitor->AddStmt(C->getPriority());
2224}
2225
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002226void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2227 Visitor->AddStmt(C->getGrainsize());
2228}
2229
Alexey Bataev382967a2015-12-08 12:06:20 +00002230void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2231 Visitor->AddStmt(C->getNumTasks());
2232}
2233
Alexey Bataev28c75412015-12-15 08:19:24 +00002234void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2235 Visitor->AddStmt(C->getHint());
2236}
2237
Alexey Bataev756c1962013-09-24 03:17:45 +00002238template<typename T>
2239void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002240 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002241 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002242 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002243}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002244
2245void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002246 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002247 for (const auto *E : C->private_copies()) {
2248 Visitor->AddStmt(E);
2249 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002250}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002251void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2252 const OMPFirstprivateClause *C) {
2253 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002254 VisitOMPClauseWithPreInit(C);
2255 for (const auto *E : C->private_copies()) {
2256 Visitor->AddStmt(E);
2257 }
2258 for (const auto *E : C->inits()) {
2259 Visitor->AddStmt(E);
2260 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002261}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002262void OMPClauseEnqueue::VisitOMPLastprivateClause(
2263 const OMPLastprivateClause *C) {
2264 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002265 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002266 for (auto *E : C->private_copies()) {
2267 Visitor->AddStmt(E);
2268 }
2269 for (auto *E : C->source_exprs()) {
2270 Visitor->AddStmt(E);
2271 }
2272 for (auto *E : C->destination_exprs()) {
2273 Visitor->AddStmt(E);
2274 }
2275 for (auto *E : C->assignment_ops()) {
2276 Visitor->AddStmt(E);
2277 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002278}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002279void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002280 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002281}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002282void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2283 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002284 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002285 for (auto *E : C->privates()) {
2286 Visitor->AddStmt(E);
2287 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002288 for (auto *E : C->lhs_exprs()) {
2289 Visitor->AddStmt(E);
2290 }
2291 for (auto *E : C->rhs_exprs()) {
2292 Visitor->AddStmt(E);
2293 }
2294 for (auto *E : C->reduction_ops()) {
2295 Visitor->AddStmt(E);
2296 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002297}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002298void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2299 const OMPTaskReductionClause *C) {
2300 VisitOMPClauseList(C);
2301 VisitOMPClauseWithPostUpdate(C);
2302 for (auto *E : C->privates()) {
2303 Visitor->AddStmt(E);
2304 }
2305 for (auto *E : C->lhs_exprs()) {
2306 Visitor->AddStmt(E);
2307 }
2308 for (auto *E : C->rhs_exprs()) {
2309 Visitor->AddStmt(E);
2310 }
2311 for (auto *E : C->reduction_ops()) {
2312 Visitor->AddStmt(E);
2313 }
2314}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002315void OMPClauseEnqueue::VisitOMPInReductionClause(
2316 const OMPInReductionClause *C) {
2317 VisitOMPClauseList(C);
2318 VisitOMPClauseWithPostUpdate(C);
2319 for (auto *E : C->privates()) {
2320 Visitor->AddStmt(E);
2321 }
2322 for (auto *E : C->lhs_exprs()) {
2323 Visitor->AddStmt(E);
2324 }
2325 for (auto *E : C->rhs_exprs()) {
2326 Visitor->AddStmt(E);
2327 }
2328 for (auto *E : C->reduction_ops()) {
2329 Visitor->AddStmt(E);
2330 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002331 for (auto *E : C->taskgroup_descriptors())
2332 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002333}
Alexander Musman8dba6642014-04-22 13:09:42 +00002334void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2335 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002336 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002337 for (const auto *E : C->privates()) {
2338 Visitor->AddStmt(E);
2339 }
Alexander Musman3276a272015-03-21 10:12:56 +00002340 for (const auto *E : C->inits()) {
2341 Visitor->AddStmt(E);
2342 }
2343 for (const auto *E : C->updates()) {
2344 Visitor->AddStmt(E);
2345 }
2346 for (const auto *E : C->finals()) {
2347 Visitor->AddStmt(E);
2348 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002349 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002350 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002351}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002352void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2353 VisitOMPClauseList(C);
2354 Visitor->AddStmt(C->getAlignment());
2355}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002356void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2357 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002358 for (auto *E : C->source_exprs()) {
2359 Visitor->AddStmt(E);
2360 }
2361 for (auto *E : C->destination_exprs()) {
2362 Visitor->AddStmt(E);
2363 }
2364 for (auto *E : C->assignment_ops()) {
2365 Visitor->AddStmt(E);
2366 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002367}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002368void
2369OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2370 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002371 for (auto *E : C->source_exprs()) {
2372 Visitor->AddStmt(E);
2373 }
2374 for (auto *E : C->destination_exprs()) {
2375 Visitor->AddStmt(E);
2376 }
2377 for (auto *E : C->assignment_ops()) {
2378 Visitor->AddStmt(E);
2379 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002380}
Alexey Bataev6125da92014-07-21 11:26:11 +00002381void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2382 VisitOMPClauseList(C);
2383}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002384void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2385 VisitOMPClauseList(C);
2386}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002387void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2388 VisitOMPClauseList(C);
2389}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002390void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2391 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002392 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002393 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002394}
Alexey Bataev3392d762016-02-16 11:18:12 +00002395void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2396 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002397void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2398 VisitOMPClauseList(C);
2399}
Samuel Antaoec172c62016-05-26 17:49:04 +00002400void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2401 VisitOMPClauseList(C);
2402}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002403void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2404 VisitOMPClauseList(C);
2405}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002406void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2407 VisitOMPClauseList(C);
2408}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002409}
Alexey Bataev756c1962013-09-24 03:17:45 +00002410
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002411void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2412 unsigned size = WL.size();
2413 OMPClauseEnqueue Visitor(this);
2414 Visitor.Visit(S);
2415 if (size == WL.size())
2416 return;
2417 // Now reverse the entries we just added. This will match the DFS
2418 // ordering performed by the worklist.
2419 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2420 std::reverse(I, E);
2421}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002422void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2424}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002425void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 AddDecl(B->getBlockDecl());
2427}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002428void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 EnqueueChildren(E);
2430 AddTypeLoc(E->getTypeSourceInfo());
2431}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002432void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002433 for (auto &I : llvm::reverse(S->body()))
2434 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002435}
2436void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002437VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 AddStmt(S->getSubStmt());
2439 AddDeclarationNameInfo(S);
2440 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2441 AddNestedNameSpecifierLoc(QualifierLoc);
2442}
2443
2444void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002445VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002446 if (E->hasExplicitTemplateArgs())
2447 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 AddDeclarationNameInfo(E);
2449 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2450 AddNestedNameSpecifierLoc(QualifierLoc);
2451 if (!E->isImplicitAccess())
2452 AddStmt(E->getBase());
2453}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002454void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 // Enqueue the initializer , if any.
2456 AddStmt(E->getInitializer());
2457 // Enqueue the array size, if any.
2458 AddStmt(E->getArraySize());
2459 // Enqueue the allocated type.
2460 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2461 // Enqueue the placement arguments.
2462 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2463 AddStmt(E->getPlacementArg(I-1));
2464}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002465void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2467 AddStmt(CE->getArg(I-1));
2468 AddStmt(CE->getCallee());
2469 AddStmt(CE->getArg(0));
2470}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002471void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2472 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 // Visit the name of the type being destroyed.
2474 AddTypeLoc(E->getDestroyedTypeInfo());
2475 // Visit the scope type that looks disturbingly like the nested-name-specifier
2476 // but isn't.
2477 AddTypeLoc(E->getScopeTypeInfo());
2478 // Visit the nested-name-specifier.
2479 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2480 AddNestedNameSpecifierLoc(QualifierLoc);
2481 // Visit base expression.
2482 AddStmt(E->getBase());
2483}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002484void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2485 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 AddTypeLoc(E->getTypeSourceInfo());
2487}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002488void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2489 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 EnqueueChildren(E);
2491 AddTypeLoc(E->getTypeSourceInfo());
2492}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002493void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 EnqueueChildren(E);
2495 if (E->isTypeOperand())
2496 AddTypeLoc(E->getTypeOperandSourceInfo());
2497}
2498
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002499void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2500 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 EnqueueChildren(E);
2502 AddTypeLoc(E->getTypeSourceInfo());
2503}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002504void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 EnqueueChildren(E);
2506 if (E->isTypeOperand())
2507 AddTypeLoc(E->getTypeOperandSourceInfo());
2508}
2509
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002510void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 EnqueueChildren(S);
2512 AddDecl(S->getExceptionDecl());
2513}
2514
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002515void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002516 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002517 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002518 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002519}
2520
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002521void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002522 if (DR->hasExplicitTemplateArgs())
2523 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 WL.push_back(DeclRefExprParts(DR, Parent));
2525}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002526void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2527 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002528 if (E->hasExplicitTemplateArgs())
2529 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 AddDeclarationNameInfo(E);
2531 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2532}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002533void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 unsigned size = WL.size();
2535 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002536 for (const auto *D : S->decls()) {
2537 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 isFirst = false;
2539 }
2540 if (size == WL.size())
2541 return;
2542 // Now reverse the entries we just added. This will match the DFS
2543 // ordering performed by the worklist.
2544 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2545 std::reverse(I, E);
2546}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002547void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002549 for (const DesignatedInitExpr::Designator &D :
2550 llvm::reverse(E->designators())) {
2551 if (D.isFieldDesignator()) {
2552 if (FieldDecl *Field = D.getField())
2553 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 continue;
2555 }
David Majnemerf7e36092016-06-23 00:15:04 +00002556 if (D.isArrayDesignator()) {
2557 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 continue;
2559 }
David Majnemerf7e36092016-06-23 00:15:04 +00002560 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2561 AddStmt(E->getArrayRangeEnd(D));
2562 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 }
2564}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002565void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 EnqueueChildren(E);
2567 AddTypeLoc(E->getTypeInfoAsWritten());
2568}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002569void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 AddStmt(FS->getBody());
2571 AddStmt(FS->getInc());
2572 AddStmt(FS->getCond());
2573 AddDecl(FS->getConditionVariable());
2574 AddStmt(FS->getInit());
2575}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002576void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2578}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002579void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 AddStmt(If->getElse());
2581 AddStmt(If->getThen());
2582 AddStmt(If->getCond());
2583 AddDecl(If->getConditionVariable());
2584}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002585void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 // We care about the syntactic form of the initializer list, only.
2587 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2588 IE = Syntactic;
2589 EnqueueChildren(IE);
2590}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002591void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 WL.push_back(MemberExprParts(M, Parent));
2593
2594 // If the base of the member access expression is an implicit 'this', don't
2595 // visit it.
2596 // FIXME: If we ever want to show these implicit accesses, this will be
2597 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002598 if (M->isImplicitAccess())
2599 return;
2600
2601 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002602 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002603 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2604 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2605 if (FD->isAnonymousStructOrUnion()) {
2606 AddStmt(SubME->getBase());
2607 return;
2608 }
2609 }
2610 }
2611
2612 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002613}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002614void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 AddTypeLoc(E->getEncodedTypeSourceInfo());
2616}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002617void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 EnqueueChildren(M);
2619 AddTypeLoc(M->getClassReceiverTypeInfo());
2620}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002621void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 // Visit the components of the offsetof expression.
2623 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 const OffsetOfNode &Node = E->getComponent(I-1);
2625 switch (Node.getKind()) {
2626 case OffsetOfNode::Array:
2627 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2628 break;
2629 case OffsetOfNode::Field:
2630 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2631 break;
2632 case OffsetOfNode::Identifier:
2633 case OffsetOfNode::Base:
2634 continue;
2635 }
2636 }
2637 // Visit the type into which we're computing the offset.
2638 AddTypeLoc(E->getTypeSourceInfo());
2639}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002640void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002641 if (E->hasExplicitTemplateArgs())
2642 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 WL.push_back(OverloadExprParts(E, Parent));
2644}
2645void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002646 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 EnqueueChildren(E);
2648 if (E->isArgumentType())
2649 AddTypeLoc(E->getArgumentTypeInfo());
2650}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002651void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 EnqueueChildren(S);
2653}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002654void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 AddStmt(S->getBody());
2656 AddStmt(S->getCond());
2657 AddDecl(S->getConditionVariable());
2658}
2659
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002660void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 AddStmt(W->getBody());
2662 AddStmt(W->getCond());
2663 AddDecl(W->getConditionVariable());
2664}
2665
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002666void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 for (unsigned I = E->getNumArgs(); I > 0; --I)
2668 AddTypeLoc(E->getArg(I-1));
2669}
2670
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002671void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 AddTypeLoc(E->getQueriedTypeSourceInfo());
2673}
2674
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002675void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 EnqueueChildren(E);
2677}
2678
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002679void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 VisitOverloadExpr(U);
2681 if (!U->isImplicitAccess())
2682 AddStmt(U->getBase());
2683}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002684void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 AddStmt(E->getSubExpr());
2686 AddTypeLoc(E->getWrittenTypeInfo());
2687}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002688void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 WL.push_back(SizeOfPackExprParts(E, Parent));
2690}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002691void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 // If the opaque value has a source expression, just transparently
2693 // visit that. This is useful for (e.g.) pseudo-object expressions.
2694 if (Expr *SourceExpr = E->getSourceExpr())
2695 return Visit(SourceExpr);
2696}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002697void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 AddStmt(E->getBody());
2699 WL.push_back(LambdaExprParts(E, Parent));
2700}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002701void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 // Treat the expression like its syntactic form.
2703 Visit(E->getSyntacticForm());
2704}
2705
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002706void EnqueueVisitor::VisitOMPExecutableDirective(
2707 const OMPExecutableDirective *D) {
2708 EnqueueChildren(D);
2709 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2710 E = D->clauses().end();
2711 I != E; ++I)
2712 EnqueueChildren(*I);
2713}
2714
Alexander Musman3aaab662014-08-19 11:27:13 +00002715void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2716 VisitOMPExecutableDirective(D);
2717}
2718
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002719void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2720 VisitOMPExecutableDirective(D);
2721}
2722
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002723void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002724 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002725}
2726
Alexey Bataevf29276e2014-06-18 04:14:57 +00002727void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002728 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002729}
2730
Alexander Musmanf82886e2014-09-18 05:12:34 +00002731void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2732 VisitOMPLoopDirective(D);
2733}
2734
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002735void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2736 VisitOMPExecutableDirective(D);
2737}
2738
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002739void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2740 VisitOMPExecutableDirective(D);
2741}
2742
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002743void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2744 VisitOMPExecutableDirective(D);
2745}
2746
Alexander Musman80c22892014-07-17 08:54:58 +00002747void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2748 VisitOMPExecutableDirective(D);
2749}
2750
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002751void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2752 VisitOMPExecutableDirective(D);
2753 AddDeclarationNameInfo(D);
2754}
2755
Alexey Bataev4acb8592014-07-07 13:01:15 +00002756void
2757EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002758 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002759}
2760
Alexander Musmane4e893b2014-09-23 09:33:00 +00002761void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2762 const OMPParallelForSimdDirective *D) {
2763 VisitOMPLoopDirective(D);
2764}
2765
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002766void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2767 const OMPParallelSectionsDirective *D) {
2768 VisitOMPExecutableDirective(D);
2769}
2770
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002771void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2772 VisitOMPExecutableDirective(D);
2773}
2774
Alexey Bataev68446b72014-07-18 07:47:19 +00002775void
2776EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2777 VisitOMPExecutableDirective(D);
2778}
2779
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002780void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2781 VisitOMPExecutableDirective(D);
2782}
2783
Alexey Bataev2df347a2014-07-18 10:17:07 +00002784void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2785 VisitOMPExecutableDirective(D);
2786}
2787
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002788void EnqueueVisitor::VisitOMPTaskgroupDirective(
2789 const OMPTaskgroupDirective *D) {
2790 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002791 if (const Expr *E = D->getReductionRef())
2792 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002793}
2794
Alexey Bataev6125da92014-07-21 11:26:11 +00002795void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2796 VisitOMPExecutableDirective(D);
2797}
2798
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002799void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2800 VisitOMPExecutableDirective(D);
2801}
2802
Alexey Bataev0162e452014-07-22 10:10:35 +00002803void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2804 VisitOMPExecutableDirective(D);
2805}
2806
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002807void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2808 VisitOMPExecutableDirective(D);
2809}
2810
Michael Wong65f367f2015-07-21 13:44:28 +00002811void EnqueueVisitor::VisitOMPTargetDataDirective(const
2812 OMPTargetDataDirective *D) {
2813 VisitOMPExecutableDirective(D);
2814}
2815
Samuel Antaodf67fc42016-01-19 19:15:56 +00002816void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2817 const OMPTargetEnterDataDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819}
2820
Samuel Antao72590762016-01-19 20:04:50 +00002821void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2822 const OMPTargetExitDataDirective *D) {
2823 VisitOMPExecutableDirective(D);
2824}
2825
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002826void EnqueueVisitor::VisitOMPTargetParallelDirective(
2827 const OMPTargetParallelDirective *D) {
2828 VisitOMPExecutableDirective(D);
2829}
2830
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002831void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2832 const OMPTargetParallelForDirective *D) {
2833 VisitOMPLoopDirective(D);
2834}
2835
Alexey Bataev13314bf2014-10-09 04:18:56 +00002836void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2837 VisitOMPExecutableDirective(D);
2838}
2839
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002840void EnqueueVisitor::VisitOMPCancellationPointDirective(
2841 const OMPCancellationPointDirective *D) {
2842 VisitOMPExecutableDirective(D);
2843}
2844
Alexey Bataev80909872015-07-02 11:25:17 +00002845void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2846 VisitOMPExecutableDirective(D);
2847}
2848
Alexey Bataev49f6e782015-12-01 04:18:41 +00002849void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2850 VisitOMPLoopDirective(D);
2851}
2852
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002853void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2854 const OMPTaskLoopSimdDirective *D) {
2855 VisitOMPLoopDirective(D);
2856}
2857
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002858void EnqueueVisitor::VisitOMPDistributeDirective(
2859 const OMPDistributeDirective *D) {
2860 VisitOMPLoopDirective(D);
2861}
2862
Carlo Bertolli9925f152016-06-27 14:55:37 +00002863void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2864 const OMPDistributeParallelForDirective *D) {
2865 VisitOMPLoopDirective(D);
2866}
2867
Kelvin Li4a39add2016-07-05 05:00:15 +00002868void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2869 const OMPDistributeParallelForSimdDirective *D) {
2870 VisitOMPLoopDirective(D);
2871}
2872
Kelvin Li787f3fc2016-07-06 04:45:38 +00002873void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2874 const OMPDistributeSimdDirective *D) {
2875 VisitOMPLoopDirective(D);
2876}
2877
Kelvin Lia579b912016-07-14 02:54:56 +00002878void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2879 const OMPTargetParallelForSimdDirective *D) {
2880 VisitOMPLoopDirective(D);
2881}
2882
Kelvin Li986330c2016-07-20 22:57:10 +00002883void EnqueueVisitor::VisitOMPTargetSimdDirective(
2884 const OMPTargetSimdDirective *D) {
2885 VisitOMPLoopDirective(D);
2886}
2887
Kelvin Li02532872016-08-05 14:37:37 +00002888void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2889 const OMPTeamsDistributeDirective *D) {
2890 VisitOMPLoopDirective(D);
2891}
2892
Kelvin Li4e325f72016-10-25 12:50:55 +00002893void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2894 const OMPTeamsDistributeSimdDirective *D) {
2895 VisitOMPLoopDirective(D);
2896}
2897
Kelvin Li579e41c2016-11-30 23:51:03 +00002898void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2899 const OMPTeamsDistributeParallelForSimdDirective *D) {
2900 VisitOMPLoopDirective(D);
2901}
2902
Kelvin Li7ade93f2016-12-09 03:24:30 +00002903void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2904 const OMPTeamsDistributeParallelForDirective *D) {
2905 VisitOMPLoopDirective(D);
2906}
2907
Kelvin Libf594a52016-12-17 05:48:59 +00002908void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2909 const OMPTargetTeamsDirective *D) {
2910 VisitOMPExecutableDirective(D);
2911}
2912
Kelvin Li83c451e2016-12-25 04:52:54 +00002913void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2914 const OMPTargetTeamsDistributeDirective *D) {
2915 VisitOMPLoopDirective(D);
2916}
2917
Kelvin Li80e8f562016-12-29 22:16:30 +00002918void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2919 const OMPTargetTeamsDistributeParallelForDirective *D) {
2920 VisitOMPLoopDirective(D);
2921}
2922
Kelvin Li1851df52017-01-03 05:23:48 +00002923void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2924 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2925 VisitOMPLoopDirective(D);
2926}
2927
Kelvin Lida681182017-01-10 18:08:18 +00002928void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2929 const OMPTargetTeamsDistributeSimdDirective *D) {
2930 VisitOMPLoopDirective(D);
2931}
2932
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002933void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2935}
2936
2937bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2938 if (RegionOfInterest.isValid()) {
2939 SourceRange Range = getRawCursorExtent(C);
2940 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2941 return false;
2942 }
2943 return true;
2944}
2945
2946bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2947 while (!WL.empty()) {
2948 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002949 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002950
2951 // Set the Parent field, then back to its old value once we're done.
2952 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2953
2954 switch (LI.getKind()) {
2955 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002956 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 if (!D)
2958 continue;
2959
2960 // For now, perform default visitation for Decls.
2961 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2962 cast<DeclVisit>(&LI)->isFirst())))
2963 return true;
2964
2965 continue;
2966 }
2967 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002968 for (const TemplateArgumentLoc &Arg :
2969 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2970 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 return true;
2972 }
2973 continue;
2974 }
2975 case VisitorJob::TypeLocVisitKind: {
2976 // Perform default visitation for TypeLocs.
2977 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2978 return true;
2979 continue;
2980 }
2981 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002982 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 if (LabelStmt *stmt = LS->getStmt()) {
2984 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2985 TU))) {
2986 return true;
2987 }
2988 }
2989 continue;
2990 }
2991
2992 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2993 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2994 if (VisitNestedNameSpecifierLoc(V->get()))
2995 return true;
2996 continue;
2997 }
2998
2999 case VisitorJob::DeclarationNameInfoVisitKind: {
3000 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3001 ->get()))
3002 return true;
3003 continue;
3004 }
3005 case VisitorJob::MemberRefVisitKind: {
3006 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3007 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3008 return true;
3009 continue;
3010 }
3011 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003012 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 if (!S)
3014 continue;
3015
3016 // Update the current cursor.
3017 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3018 if (!IsInRegionOfInterest(Cursor))
3019 continue;
3020 switch (Visitor(Cursor, Parent, ClientData)) {
3021 case CXChildVisit_Break: return true;
3022 case CXChildVisit_Continue: break;
3023 case CXChildVisit_Recurse:
3024 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003025 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003026 EnqueueWorkList(WL, S);
3027 break;
3028 }
3029 continue;
3030 }
3031 case VisitorJob::MemberExprPartsKind: {
3032 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003033 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003034
3035 // Visit the nested-name-specifier
3036 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3037 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3038 return true;
3039
3040 // Visit the declaration name.
3041 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3042 return true;
3043
3044 // Visit the explicitly-specified template arguments, if any.
3045 if (M->hasExplicitTemplateArgs()) {
3046 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3047 *ArgEnd = Arg + M->getNumTemplateArgs();
3048 Arg != ArgEnd; ++Arg) {
3049 if (VisitTemplateArgumentLoc(*Arg))
3050 return true;
3051 }
3052 }
3053 continue;
3054 }
3055 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003056 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 // Visit nested-name-specifier, if present.
3058 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3059 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3060 return true;
3061 // Visit declaration name.
3062 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3063 return true;
3064 continue;
3065 }
3066 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003067 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 // Visit the nested-name-specifier.
3069 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3070 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3071 return true;
3072 // Visit the declaration name.
3073 if (VisitDeclarationNameInfo(O->getNameInfo()))
3074 return true;
3075 // Visit the overloaded declaration reference.
3076 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3077 return true;
3078 continue;
3079 }
3080 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003081 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 NamedDecl *Pack = E->getPack();
3083 if (isa<TemplateTypeParmDecl>(Pack)) {
3084 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3085 E->getPackLoc(), TU)))
3086 return true;
3087
3088 continue;
3089 }
3090
3091 if (isa<TemplateTemplateParmDecl>(Pack)) {
3092 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3093 E->getPackLoc(), TU)))
3094 return true;
3095
3096 continue;
3097 }
3098
3099 // Non-type template parameter packs and function parameter packs are
3100 // treated like DeclRefExpr cursors.
3101 continue;
3102 }
3103
3104 case VisitorJob::LambdaExprPartsKind: {
3105 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003106 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3108 CEnd = E->explicit_capture_end();
3109 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003110 // FIXME: Lambda init-captures.
3111 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003112 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003113
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3115 C->getLocation(),
3116 TU)))
3117 return true;
3118 }
3119
3120 // Visit parameters and return type, if present.
3121 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3122 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3123 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3124 // Visit the whole type.
3125 if (Visit(TL))
3126 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003127 } else if (FunctionProtoTypeLoc Proto =
3128 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 if (E->hasExplicitParameters()) {
3130 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003131 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3132 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 return true;
3134 } else {
3135 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003136 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 return true;
3138 }
3139 }
3140 }
3141 break;
3142 }
3143
3144 case VisitorJob::PostChildrenVisitKind:
3145 if (PostChildrenVisitor(Parent, ClientData))
3146 return true;
3147 break;
3148 }
3149 }
3150 return false;
3151}
3152
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003153bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003154 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 if (!WorkListFreeList.empty()) {
3156 WL = WorkListFreeList.back();
3157 WL->clear();
3158 WorkListFreeList.pop_back();
3159 }
3160 else {
3161 WL = new VisitorWorkList();
3162 WorkListCache.push_back(WL);
3163 }
3164 EnqueueWorkList(*WL, S);
3165 bool result = RunVisitorWorkList(*WL);
3166 WorkListFreeList.push_back(WL);
3167 return result;
3168}
3169
3170namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003171typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003172RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3173 const DeclarationNameInfo &NI, SourceRange QLoc,
3174 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003175 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3176 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3177 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3178
3179 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3180
3181 RefNamePieces Pieces;
3182
3183 if (WantQualifier && QLoc.isValid())
3184 Pieces.push_back(QLoc);
3185
3186 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3187 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003188
3189 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3190 Pieces.push_back(*TemplateArgsLoc);
3191
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 if (Kind == DeclarationName::CXXOperatorName) {
3193 Pieces.push_back(SourceLocation::getFromRawEncoding(
3194 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3195 Pieces.push_back(SourceLocation::getFromRawEncoding(
3196 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3197 }
3198
3199 if (WantSinglePiece) {
3200 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3201 Pieces.clear();
3202 Pieces.push_back(R);
3203 }
3204
3205 return Pieces;
3206}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003207}
Guy Benyei11169dd2012-12-18 14:30:41 +00003208
3209//===----------------------------------------------------------------------===//
3210// Misc. API hooks.
3211//===----------------------------------------------------------------------===//
3212
Chad Rosier05c71aa2013-03-27 18:28:23 +00003213static void fatal_error_handler(void *user_data, const std::string& reason,
3214 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003215 // Write the result out to stderr avoiding errs() because raw_ostreams can
3216 // call report_fatal_error.
3217 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3218 ::abort();
3219}
3220
Chandler Carruth66660742014-06-27 16:37:27 +00003221namespace {
3222struct RegisterFatalErrorHandler {
3223 RegisterFatalErrorHandler() {
3224 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3225 }
3226};
3227}
3228
3229static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3230
Guy Benyei11169dd2012-12-18 14:30:41 +00003231CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3232 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003233 // We use crash recovery to make some of our APIs more reliable, implicitly
3234 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003235 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3236 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003237
Chandler Carruth66660742014-06-27 16:37:27 +00003238 // Look through the managed static to trigger construction of the managed
3239 // static which registers our fatal error handler. This ensures it is only
3240 // registered once.
3241 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003242
Adrian Prantlbc068582015-07-08 01:00:30 +00003243 // Initialize targets for clang module support.
3244 llvm::InitializeAllTargets();
3245 llvm::InitializeAllTargetMCs();
3246 llvm::InitializeAllAsmPrinters();
3247 llvm::InitializeAllAsmParsers();
3248
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003249 CIndexer *CIdxr = new CIndexer();
3250
Guy Benyei11169dd2012-12-18 14:30:41 +00003251 if (excludeDeclarationsFromPCH)
3252 CIdxr->setOnlyLocalDecls();
3253 if (displayDiagnostics)
3254 CIdxr->setDisplayDiagnostics();
3255
3256 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3257 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3258 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3259 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3260 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3261 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3262
3263 return CIdxr;
3264}
3265
3266void clang_disposeIndex(CXIndex CIdx) {
3267 if (CIdx)
3268 delete static_cast<CIndexer *>(CIdx);
3269}
3270
3271void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3272 if (CIdx)
3273 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3274}
3275
3276unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3277 if (CIdx)
3278 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3279 return 0;
3280}
3281
Alex Lorenz08615792017-12-04 21:56:36 +00003282void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3283 const char *Path) {
3284 if (CIdx)
3285 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3286}
3287
Guy Benyei11169dd2012-12-18 14:30:41 +00003288void clang_toggleCrashRecovery(unsigned isEnabled) {
3289 if (isEnabled)
3290 llvm::CrashRecoveryContext::Enable();
3291 else
3292 llvm::CrashRecoveryContext::Disable();
3293}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003294
Guy Benyei11169dd2012-12-18 14:30:41 +00003295CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3296 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003297 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003298 enum CXErrorCode Result =
3299 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003300 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003301 assert((TU && Result == CXError_Success) ||
3302 (!TU && Result != CXError_Success));
3303 return TU;
3304}
3305
3306enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3307 const char *ast_filename,
3308 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003309 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003310 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003311
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003312 if (!CIdx || !ast_filename || !out_TU)
3313 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003314
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003315 LOG_FUNC_SECTION {
3316 *Log << ast_filename;
3317 }
3318
Guy Benyei11169dd2012-12-18 14:30:41 +00003319 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3320 FileSystemOptions FileSystemOpts;
3321
Justin Bognerd512c1e2014-10-15 00:33:06 +00003322 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3323 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003324 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003325 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3326 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003327 FileSystemOpts, /*UseDebugInfo=*/false,
3328 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003329 /*CaptureDiagnostics=*/true,
3330 /*AllowPCHWithCompilerErrors=*/true,
3331 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003332 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003333 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003334}
3335
3336unsigned clang_defaultEditingTranslationUnitOptions() {
3337 return CXTranslationUnit_PrecompiledPreamble |
3338 CXTranslationUnit_CacheCompletionResults;
3339}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003340
Guy Benyei11169dd2012-12-18 14:30:41 +00003341CXTranslationUnit
3342clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3343 const char *source_filename,
3344 int num_command_line_args,
3345 const char * const *command_line_args,
3346 unsigned num_unsaved_files,
3347 struct CXUnsavedFile *unsaved_files) {
3348 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3349 return clang_parseTranslationUnit(CIdx, source_filename,
3350 command_line_args, num_command_line_args,
3351 unsaved_files, num_unsaved_files,
3352 Options);
3353}
3354
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003355static CXErrorCode
3356clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3357 const char *const *command_line_args,
3358 int num_command_line_args,
3359 ArrayRef<CXUnsavedFile> unsaved_files,
3360 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003361 // Set up the initial return values.
3362 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003363 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003364
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003365 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003366 if (!CIdx || !out_TU)
3367 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003368
Guy Benyei11169dd2012-12-18 14:30:41 +00003369 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3370
3371 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3372 setThreadBackgroundPriority();
3373
3374 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003375 bool CreatePreambleOnFirstParse =
3376 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 // FIXME: Add a flag for modules.
3378 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003379 = (options & (CXTranslationUnit_Incomplete |
3380 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003381 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003382 = options & CXTranslationUnit_CacheCompletionResults;
3383 bool IncludeBriefCommentsInCodeCompletion
3384 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003385 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3386 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003387 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3388 if (options & CXTranslationUnit_SkipFunctionBodies) {
3389 SkipFunctionBodies =
3390 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3391 ? SkipFunctionBodiesScope::Preamble
3392 : SkipFunctionBodiesScope::PreambleAndMainFile;
3393 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003394
3395 // Configure the diagnostics.
3396 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003397 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003398
Manuel Klimek016c0242016-03-01 10:56:19 +00003399 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003400 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003401
Guy Benyei11169dd2012-12-18 14:30:41 +00003402 // Recover resources if we crash before exiting this function.
3403 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3404 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003405 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003406
Ahmed Charlesb8984322014-03-07 20:03:18 +00003407 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3408 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003409
3410 // Recover resources if we crash before exiting this function.
3411 llvm::CrashRecoveryContextCleanupRegistrar<
3412 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3413
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003414 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003415 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003416 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003417 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003418 }
3419
Ahmed Charlesb8984322014-03-07 20:03:18 +00003420 std::unique_ptr<std::vector<const char *>> Args(
3421 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003422
3423 // Recover resources if we crash before exiting this method.
3424 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3425 ArgsCleanup(Args.get());
3426
3427 // Since the Clang C library is primarily used by batch tools dealing with
3428 // (often very broken) source code, where spell-checking can have a
3429 // significant negative impact on performance (particularly when
3430 // precompiled headers are involved), we disable it by default.
3431 // Only do this if we haven't found a spell-checking-related argument.
3432 bool FoundSpellCheckingArgument = false;
3433 for (int I = 0; I != num_command_line_args; ++I) {
3434 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3435 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3436 FoundSpellCheckingArgument = true;
3437 break;
3438 }
3439 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003440 Args->insert(Args->end(), command_line_args,
3441 command_line_args + num_command_line_args);
3442
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003443 if (!FoundSpellCheckingArgument)
3444 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3445
Guy Benyei11169dd2012-12-18 14:30:41 +00003446 // The 'source_filename' argument is optional. If the caller does not
3447 // specify it then it is assumed that the source file is specified
3448 // in the actual argument list.
3449 // Put the source file after command_line_args otherwise if '-x' flag is
3450 // present it will be unused.
3451 if (source_filename)
3452 Args->push_back(source_filename);
3453
3454 // Do we need the detailed preprocessing record?
3455 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3456 Args->push_back("-Xclang");
3457 Args->push_back("-detailed-preprocessing-record");
3458 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003459
3460 // Suppress any editor placeholder diagnostics.
3461 Args->push_back("-fallow-editor-placeholders");
3462
Guy Benyei11169dd2012-12-18 14:30:41 +00003463 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003464 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003465 // Unless the user specified that they want the preamble on the first parse
3466 // set it up to be created on the first reparse. This makes the first parse
3467 // faster, trading for a slower (first) reparse.
3468 unsigned PrecompilePreambleAfterNParses =
3469 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003470
Alex Lorenz08615792017-12-04 21:56:36 +00003471 LibclangInvocationReporter InvocationReporter(
3472 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003473 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3474 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003475 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003476 Args->data(), Args->data() + Args->size(),
3477 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003478 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3479 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003480 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3481 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003482 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003483 /*UserFilesAreVolatile=*/true, ForSerialization,
3484 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3485 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003486
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003487 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003488 if (!Unit && !ErrUnit)
3489 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003490
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 if (NumErrors != Diags->getClient()->getNumErrors()) {
3492 // Make sure to check that 'Unit' is non-NULL.
3493 if (CXXIdx->getDisplayDiagnostics())
3494 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3495 }
3496
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003497 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3498 return CXError_ASTReadError;
3499
David Blaikieea4395e2017-01-06 19:49:01 +00003500 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003501 if (CXTranslationUnitImpl *TU = *out_TU) {
3502 TU->ParsingOptions = options;
3503 TU->Arguments.reserve(Args->size());
3504 for (const char *Arg : *Args)
3505 TU->Arguments.push_back(Arg);
3506 return CXError_Success;
3507 }
3508 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003509}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003510
3511CXTranslationUnit
3512clang_parseTranslationUnit(CXIndex CIdx,
3513 const char *source_filename,
3514 const char *const *command_line_args,
3515 int num_command_line_args,
3516 struct CXUnsavedFile *unsaved_files,
3517 unsigned num_unsaved_files,
3518 unsigned options) {
3519 CXTranslationUnit TU;
3520 enum CXErrorCode Result = clang_parseTranslationUnit2(
3521 CIdx, source_filename, command_line_args, num_command_line_args,
3522 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003523 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003524 assert((TU && Result == CXError_Success) ||
3525 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003526 return TU;
3527}
3528
3529enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003530 CXIndex CIdx, const char *source_filename,
3531 const char *const *command_line_args, int num_command_line_args,
3532 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3533 unsigned options, CXTranslationUnit *out_TU) {
3534 SmallVector<const char *, 4> Args;
3535 Args.push_back("clang");
3536 Args.append(command_line_args, command_line_args + num_command_line_args);
3537 return clang_parseTranslationUnit2FullArgv(
3538 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3539 num_unsaved_files, options, out_TU);
3540}
3541
3542enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3543 CXIndex CIdx, const char *source_filename,
3544 const char *const *command_line_args, int num_command_line_args,
3545 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3546 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003547 LOG_FUNC_SECTION {
3548 *Log << source_filename << ": ";
3549 for (int i = 0; i != num_command_line_args; ++i)
3550 *Log << command_line_args[i] << " ";
3551 }
3552
Alp Toker9d85b182014-07-07 01:23:14 +00003553 if (num_unsaved_files && !unsaved_files)
3554 return CXError_InvalidArguments;
3555
Alp Toker5c532982014-07-07 22:42:03 +00003556 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003557 auto ParseTranslationUnitImpl = [=, &result] {
3558 result = clang_parseTranslationUnit_Impl(
3559 CIdx, source_filename, command_line_args, num_command_line_args,
3560 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3561 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003562
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 llvm::CrashRecoveryContext CRC;
3564
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003565 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003566 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3567 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3568 fprintf(stderr, " 'command_line_args' : [");
3569 for (int i = 0; i != num_command_line_args; ++i) {
3570 if (i)
3571 fprintf(stderr, ", ");
3572 fprintf(stderr, "'%s'", command_line_args[i]);
3573 }
3574 fprintf(stderr, "],\n");
3575 fprintf(stderr, " 'unsaved_files' : [");
3576 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3577 if (i)
3578 fprintf(stderr, ", ");
3579 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3580 unsaved_files[i].Length);
3581 }
3582 fprintf(stderr, "],\n");
3583 fprintf(stderr, " 'options' : %d,\n", options);
3584 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003585
3586 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003587 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003588 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003589 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003590 }
Alp Toker5c532982014-07-07 22:42:03 +00003591
3592 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003593}
3594
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003595CXString clang_Type_getObjCEncoding(CXType CT) {
3596 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3597 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3598 std::string encoding;
3599 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3600 encoding);
3601
3602 return cxstring::createDup(encoding);
3603}
3604
3605static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3606 if (C.kind == CXCursor_MacroDefinition) {
3607 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3608 return MDR->getName();
3609 } else if (C.kind == CXCursor_MacroExpansion) {
3610 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3611 return ME.getName();
3612 }
3613 return nullptr;
3614}
3615
3616unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3617 const IdentifierInfo *II = getMacroIdentifier(C);
3618 if (!II) {
3619 return false;
3620 }
3621 ASTUnit *ASTU = getCursorASTUnit(C);
3622 Preprocessor &PP = ASTU->getPreprocessor();
3623 if (const MacroInfo *MI = PP.getMacroInfo(II))
3624 return MI->isFunctionLike();
3625 return false;
3626}
3627
3628unsigned clang_Cursor_isMacroBuiltin(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->isBuiltinMacro();
3637 return false;
3638}
3639
3640unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3641 const Decl *D = getCursorDecl(C);
3642 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3643 if (!FD) {
3644 return false;
3645 }
3646 return FD->isInlined();
3647}
3648
3649static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3650 if (callExpr->getNumArgs() != 1) {
3651 return nullptr;
3652 }
3653
3654 StringLiteral *S = nullptr;
3655 auto *arg = callExpr->getArg(0);
3656 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3657 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3658 auto *subExpr = I->getSubExprAsWritten();
3659
3660 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3661 return nullptr;
3662 }
3663
3664 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3665 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3666 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3667 } else {
3668 return nullptr;
3669 }
3670 return S;
3671}
3672
David Blaikie59272572016-04-13 18:23:33 +00003673struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003674 CXEvalResultKind EvalType;
3675 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003676 unsigned long long unsignedVal;
3677 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003678 double floatVal;
3679 char *stringVal;
3680 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003681 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003682 ~ExprEvalResult() {
3683 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3684 EvalType != CXEval_Int) {
3685 delete EvalData.stringVal;
3686 }
3687 }
3688};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003689
3690void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003691 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003692}
3693
3694CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3695 if (!E) {
3696 return CXEval_UnExposed;
3697 }
3698 return ((ExprEvalResult *)E)->EvalType;
3699}
3700
3701int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003702 return clang_EvalResult_getAsLongLong(E);
3703}
3704
3705long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003706 if (!E) {
3707 return 0;
3708 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003709 ExprEvalResult *Result = (ExprEvalResult*)E;
3710 if (Result->IsUnsignedInt)
3711 return Result->EvalData.unsignedVal;
3712 return Result->EvalData.intVal;
3713}
3714
3715unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3716 return ((ExprEvalResult *)E)->IsUnsignedInt;
3717}
3718
3719unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3720 if (!E) {
3721 return 0;
3722 }
3723
3724 ExprEvalResult *Result = (ExprEvalResult*)E;
3725 if (Result->IsUnsignedInt)
3726 return Result->EvalData.unsignedVal;
3727 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003728}
3729
3730double clang_EvalResult_getAsDouble(CXEvalResult E) {
3731 if (!E) {
3732 return 0;
3733 }
3734 return ((ExprEvalResult *)E)->EvalData.floatVal;
3735}
3736
3737const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3738 if (!E) {
3739 return nullptr;
3740 }
3741 return ((ExprEvalResult *)E)->EvalData.stringVal;
3742}
3743
3744static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3745 Expr::EvalResult ER;
3746 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003747 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003748 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003749
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003750 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003751 if (!expr->EvaluateAsRValue(ER, ctx))
3752 return nullptr;
3753
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003754 QualType rettype;
3755 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003756 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003757 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003758 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003759
David Blaikiebbc00882016-04-13 18:36:19 +00003760 if (ER.Val.isInt()) {
3761 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003762
3763 auto& val = ER.Val.getInt();
3764 if (val.isUnsigned()) {
3765 result->IsUnsignedInt = true;
3766 result->EvalData.unsignedVal = val.getZExtValue();
3767 } else {
3768 result->EvalData.intVal = val.getExtValue();
3769 }
3770
David Blaikiebbc00882016-04-13 18:36:19 +00003771 return result.release();
3772 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003773
David Blaikiebbc00882016-04-13 18:36:19 +00003774 if (ER.Val.isFloat()) {
3775 llvm::SmallVector<char, 100> Buffer;
3776 ER.Val.getFloat().toString(Buffer);
3777 std::string floatStr(Buffer.data(), Buffer.size());
3778 result->EvalType = CXEval_Float;
3779 bool ignored;
3780 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003781 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003782 llvm::APFloat::rmNearestTiesToEven, &ignored);
3783 result->EvalData.floatVal = apFloat.convertToDouble();
3784 return result.release();
3785 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003786
David Blaikiebbc00882016-04-13 18:36:19 +00003787 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3788 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3789 auto *subExpr = I->getSubExprAsWritten();
3790 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3791 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003792 const StringLiteral *StrE = nullptr;
3793 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003794 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003795
3796 if (ObjCExpr) {
3797 StrE = ObjCExpr->getString();
3798 result->EvalType = CXEval_ObjCStrLiteral;
3799 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003800 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003801 result->EvalType = CXEval_StrLiteral;
3802 }
3803
3804 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003805 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003806 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3807 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003808 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003809 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003810 }
3811 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3812 expr->getStmtClass() == Stmt::StringLiteralClass) {
3813 const StringLiteral *StrE = nullptr;
3814 const ObjCStringLiteral *ObjCExpr;
3815 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003816
David Blaikiebbc00882016-04-13 18:36:19 +00003817 if (ObjCExpr) {
3818 StrE = ObjCExpr->getString();
3819 result->EvalType = CXEval_ObjCStrLiteral;
3820 } else {
3821 StrE = cast<StringLiteral>(expr);
3822 result->EvalType = CXEval_StrLiteral;
3823 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003824
David Blaikiebbc00882016-04-13 18:36:19 +00003825 std::string strRef(StrE->getString().str());
3826 result->EvalData.stringVal = new char[strRef.size() + 1];
3827 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3828 result->EvalData.stringVal[strRef.size()] = '\0';
3829 return result.release();
3830 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003831
David Blaikiebbc00882016-04-13 18:36:19 +00003832 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3833 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003834
David Blaikiebbc00882016-04-13 18:36:19 +00003835 rettype = CC->getType();
3836 if (rettype.getAsString() == "CFStringRef" &&
3837 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003838
David Blaikiebbc00882016-04-13 18:36:19 +00003839 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3840 StringLiteral *S = getCFSTR_value(callExpr);
3841 if (S) {
3842 std::string strLiteral(S->getString().str());
3843 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003844
David Blaikiebbc00882016-04-13 18:36:19 +00003845 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3846 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3847 strLiteral.size());
3848 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003849 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003850 }
3851 }
3852
David Blaikiebbc00882016-04-13 18:36:19 +00003853 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3854 callExpr = static_cast<CallExpr *>(expr);
3855 rettype = callExpr->getCallReturnType(ctx);
3856
3857 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3858 return nullptr;
3859
3860 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3861 if (callExpr->getNumArgs() == 1 &&
3862 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3863 return nullptr;
3864 } else if (rettype.getAsString() == "CFStringRef") {
3865
3866 StringLiteral *S = getCFSTR_value(callExpr);
3867 if (S) {
3868 std::string strLiteral(S->getString().str());
3869 result->EvalType = CXEval_CFStr;
3870 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3871 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3872 strLiteral.size());
3873 result->EvalData.stringVal[strLiteral.size()] = '\0';
3874 return result.release();
3875 }
3876 }
3877 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3878 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3879 ValueDecl *V = D->getDecl();
3880 if (V->getKind() == Decl::Function) {
3881 std::string strName = V->getNameAsString();
3882 result->EvalType = CXEval_Other;
3883 result->EvalData.stringVal = new char[strName.size() + 1];
3884 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3885 result->EvalData.stringVal[strName.size()] = '\0';
3886 return result.release();
3887 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003888 }
3889
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003890 return nullptr;
3891}
3892
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003893CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003894 const Decl *D = getCursorDecl(C);
3895 if (D) {
3896 const Expr *expr = nullptr;
3897 if (auto *Var = dyn_cast<VarDecl>(D)) {
3898 expr = Var->getInit();
3899 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3900 expr = Field->getInClassInitializer();
3901 }
3902 if (expr)
3903 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3904 evaluateExpr(const_cast<Expr *>(expr), C)));
3905 return nullptr;
3906 }
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003907
3908 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3909 if (compoundStmt) {
3910 Expr *expr = nullptr;
3911 for (auto *bodyIterator : compoundStmt->body()) {
3912 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3913 break;
3914 }
3915 }
3916 if (expr)
3917 return const_cast<CXEvalResult>(
3918 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
3919 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003920 return nullptr;
3921}
3922
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003923unsigned clang_Cursor_hasAttrs(CXCursor C) {
3924 const Decl *D = getCursorDecl(C);
3925 if (!D) {
3926 return 0;
3927 }
3928
3929 if (D->hasAttrs()) {
3930 return 1;
3931 }
3932
3933 return 0;
3934}
Guy Benyei11169dd2012-12-18 14:30:41 +00003935unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3936 return CXSaveTranslationUnit_None;
3937}
3938
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003939static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3940 const char *FileName,
3941 unsigned options) {
3942 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3944 setThreadBackgroundPriority();
3945
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003946 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3947 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003948}
3949
3950int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3951 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003952 LOG_FUNC_SECTION {
3953 *Log << TU << ' ' << FileName;
3954 }
3955
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003956 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003957 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003958 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003959 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003960
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003961 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3963 if (!CXXUnit->hasSema())
3964 return CXSaveError_InvalidTU;
3965
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003966 CXSaveError result;
3967 auto SaveTranslationUnitImpl = [=, &result]() {
3968 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3969 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003970
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003971 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003972 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003973
3974 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3975 PrintLibclangResourceUsage(TU);
3976
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003977 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 }
3979
3980 // We have an AST that has invalid nodes due to compiler errors.
3981 // Use a crash recovery thread for protection.
3982
3983 llvm::CrashRecoveryContext CRC;
3984
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003985 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003986 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3987 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3988 fprintf(stderr, " 'options' : %d,\n", options);
3989 fprintf(stderr, "}\n");
3990
3991 return CXSaveError_Unknown;
3992
3993 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3994 PrintLibclangResourceUsage(TU);
3995 }
3996
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003997 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003998}
3999
4000void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4001 if (CTUnit) {
4002 // If the translation unit has been marked as unsafe to free, just discard
4003 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004004 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4005 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 return;
4007
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004008 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004009 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004010 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4011 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004012 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004013 delete CTUnit;
4014 }
4015}
4016
Erik Verbruggen346066b2017-05-30 14:25:54 +00004017unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4018 if (CTUnit) {
4019 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4020
4021 if (Unit && Unit->isUnsafeToFree())
4022 return false;
4023
4024 Unit->ResetForParse();
4025 return true;
4026 }
4027
4028 return false;
4029}
4030
Guy Benyei11169dd2012-12-18 14:30:41 +00004031unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4032 return CXReparse_None;
4033}
4034
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004035static CXErrorCode
4036clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4037 ArrayRef<CXUnsavedFile> unsaved_files,
4038 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004039 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004040 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004041 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004042 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004043 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004044
4045 // Reset the associated diagnostics.
4046 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004047 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004048
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004049 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4051 setThreadBackgroundPriority();
4052
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004053 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004054 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004055
4056 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4057 new std::vector<ASTUnit::RemappedFile>());
4058
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 // Recover resources if we crash before exiting this function.
4060 llvm::CrashRecoveryContextCleanupRegistrar<
4061 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004062
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004063 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004064 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004065 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004066 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004068
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004069 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4070 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004071 return CXError_Success;
4072 if (isASTReadError(CXXUnit))
4073 return CXError_ASTReadError;
4074 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004075}
4076
4077int clang_reparseTranslationUnit(CXTranslationUnit TU,
4078 unsigned num_unsaved_files,
4079 struct CXUnsavedFile *unsaved_files,
4080 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004081 LOG_FUNC_SECTION {
4082 *Log << TU;
4083 }
4084
Alp Toker9d85b182014-07-07 01:23:14 +00004085 if (num_unsaved_files && !unsaved_files)
4086 return CXError_InvalidArguments;
4087
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004088 CXErrorCode result;
4089 auto ReparseTranslationUnitImpl = [=, &result]() {
4090 result = clang_reparseTranslationUnit_Impl(
4091 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4092 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004093
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 llvm::CrashRecoveryContext CRC;
4095
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004096 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004098 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004099 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4101 PrintLibclangResourceUsage(TU);
4102
Alp Toker5c532982014-07-07 22:42:03 +00004103 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004104}
4105
4106
4107CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004108 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004109 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004110 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004111 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004112
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004113 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004114 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004115}
4116
4117CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004118 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004119 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004120 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004121 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004122
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004123 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4125}
4126
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004127CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4128 if (isNotUsableTU(CTUnit)) {
4129 LOG_BAD_TU(CTUnit);
4130 return nullptr;
4131 }
4132
4133 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4134 impl->TranslationUnit = CTUnit;
4135 return impl;
4136}
4137
4138CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4139 if (!TargetInfo)
4140 return cxstring::createEmpty();
4141
4142 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4143 assert(!isNotUsableTU(CTUnit) &&
4144 "Unexpected unusable translation unit in TargetInfo");
4145
4146 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4147 std::string Triple =
4148 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4149 return cxstring::createDup(Triple);
4150}
4151
4152int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4153 if (!TargetInfo)
4154 return -1;
4155
4156 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4157 assert(!isNotUsableTU(CTUnit) &&
4158 "Unexpected unusable translation unit in TargetInfo");
4159
4160 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4161 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4162}
4163
4164void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4165 if (!TargetInfo)
4166 return;
4167
4168 delete TargetInfo;
4169}
4170
Guy Benyei11169dd2012-12-18 14:30:41 +00004171//===----------------------------------------------------------------------===//
4172// CXFile Operations.
4173//===----------------------------------------------------------------------===//
4174
Guy Benyei11169dd2012-12-18 14:30:41 +00004175CXString clang_getFileName(CXFile SFile) {
4176 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004177 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004178
4179 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004180 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004181}
4182
4183time_t clang_getFileTime(CXFile SFile) {
4184 if (!SFile)
4185 return 0;
4186
4187 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4188 return FEnt->getModificationTime();
4189}
4190
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004191CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004192 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004193 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004194 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004195 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004196
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004197 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004198
4199 FileManager &FMgr = CXXUnit->getFileManager();
4200 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4201}
4202
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004203const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4204 size_t *size) {
4205 if (isNotUsableTU(TU)) {
4206 LOG_BAD_TU(TU);
4207 return nullptr;
4208 }
4209
4210 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4211 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4212 bool Invalid = true;
4213 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4214 if (Invalid) {
4215 if (size)
4216 *size = 0;
4217 return nullptr;
4218 }
4219 if (size)
4220 *size = buf->getBufferSize();
4221 return buf->getBufferStart();
4222}
4223
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004224unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4225 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004226 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004227 LOG_BAD_TU(TU);
4228 return 0;
4229 }
4230
4231 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 return 0;
4233
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004234 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 FileEntry *FEnt = static_cast<FileEntry *>(file);
4236 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4237 .isFileMultipleIncludeGuarded(FEnt);
4238}
4239
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004240int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4241 if (!file || !outID)
4242 return 1;
4243
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004244 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004245 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4246 outID->data[0] = ID.getDevice();
4247 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004248 outID->data[2] = FEnt->getModificationTime();
4249 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004250}
4251
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004252int clang_File_isEqual(CXFile file1, CXFile file2) {
4253 if (file1 == file2)
4254 return true;
4255
4256 if (!file1 || !file2)
4257 return false;
4258
4259 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4260 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4261 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4262}
4263
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004264CXString clang_File_tryGetRealPathName(CXFile SFile) {
4265 if (!SFile)
4266 return cxstring::createNull();
4267
4268 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4269 return cxstring::createRef(FEnt->tryGetRealPathName());
4270}
4271
Guy Benyei11169dd2012-12-18 14:30:41 +00004272//===----------------------------------------------------------------------===//
4273// CXCursor Operations.
4274//===----------------------------------------------------------------------===//
4275
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004276static const Decl *getDeclFromExpr(const Stmt *E) {
4277 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 return getDeclFromExpr(CE->getSubExpr());
4279
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004280 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004282 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004284 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004285 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004286 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004287 if (PRE->isExplicitProperty())
4288 return PRE->getExplicitProperty();
4289 // It could be messaging both getter and setter as in:
4290 // ++myobj.myprop;
4291 // in which case prefer to associate the setter since it is less obvious
4292 // from inspecting the source that the setter is going to get called.
4293 if (PRE->isMessagingSetter())
4294 return PRE->getImplicitPropertySetter();
4295 return PRE->getImplicitPropertyGetter();
4296 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004297 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004299 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 if (Expr *Src = OVE->getSourceExpr())
4301 return getDeclFromExpr(Src);
4302
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004303 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004305 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004306 if (!CE->isElidable())
4307 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004308 if (const CXXInheritedCtorInitExpr *CE =
4309 dyn_cast<CXXInheritedCtorInitExpr>(E))
4310 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004311 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 return OME->getMethodDecl();
4313
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004314 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004316 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4318 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004319 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4321 isa<ParmVarDecl>(SizeOfPack->getPack()))
4322 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004323
4324 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004325}
4326
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004327static SourceLocation getLocationFromExpr(const Expr *E) {
4328 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 return getLocationFromExpr(CE->getSubExpr());
4330
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004331 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004333 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004335 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004336 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004337 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004339 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004340 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004341 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 return PropRef->getLocation();
4343
4344 return E->getLocStart();
4345}
4346
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004347extern "C" {
4348
Guy Benyei11169dd2012-12-18 14:30:41 +00004349unsigned clang_visitChildren(CXCursor parent,
4350 CXCursorVisitor visitor,
4351 CXClientData client_data) {
4352 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4353 /*VisitPreprocessorLast=*/false);
4354 return CursorVis.VisitChildren(parent);
4355}
4356
4357#ifndef __has_feature
4358#define __has_feature(x) 0
4359#endif
4360#if __has_feature(blocks)
4361typedef enum CXChildVisitResult
4362 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4363
4364static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4365 CXClientData client_data) {
4366 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4367 return block(cursor, parent);
4368}
4369#else
4370// If we are compiled with a compiler that doesn't have native blocks support,
4371// define and call the block manually, so the
4372typedef struct _CXChildVisitResult
4373{
4374 void *isa;
4375 int flags;
4376 int reserved;
4377 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4378 CXCursor);
4379} *CXCursorVisitorBlock;
4380
4381static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4382 CXClientData client_data) {
4383 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4384 return block->invoke(block, cursor, parent);
4385}
4386#endif
4387
4388
4389unsigned clang_visitChildrenWithBlock(CXCursor parent,
4390 CXCursorVisitorBlock block) {
4391 return clang_visitChildren(parent, visitWithBlock, block);
4392}
4393
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004394static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004395 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004396 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004397
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004398 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004400 if (const ObjCPropertyImplDecl *PropImpl =
4401 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004403 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004404
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004405 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004407 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004408
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004409 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 }
4411
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004412 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004413 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004414
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004415 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4417 // and returns different names. NamedDecl returns the class name and
4418 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004419 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004420
4421 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004422 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004423
4424 SmallString<1024> S;
4425 llvm::raw_svector_ostream os(S);
4426 ND->printName(os);
4427
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004428 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004429}
4430
4431CXString clang_getCursorSpelling(CXCursor C) {
4432 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004433 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004434
4435 if (clang_isReference(C.kind)) {
4436 switch (C.kind) {
4437 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004438 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004439 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 }
4441 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004442 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004443 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 }
4445 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004446 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004448 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 }
4450 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004451 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004452 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 }
4454 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004455 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 assert(Type && "Missing type decl");
4457
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004458 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 getAsString());
4460 }
4461 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004462 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 assert(Template && "Missing template decl");
4464
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004465 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 }
4467
4468 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004469 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 assert(NS && "Missing namespace decl");
4471
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004472 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 }
4474
4475 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004476 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 assert(Field && "Missing member decl");
4478
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004479 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 }
4481
4482 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004483 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 assert(Label && "Missing label");
4485
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004486 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 }
4488
4489 case CXCursor_OverloadedDeclRef: {
4490 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004491 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4492 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004493 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004494 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004496 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004497 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 OverloadedTemplateStorage *Ovl
4499 = Storage.get<OverloadedTemplateStorage*>();
4500 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004501 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004502 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 }
4504
4505 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004506 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 assert(Var && "Missing variable decl");
4508
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004509 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 }
4511
4512 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004513 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 }
4515 }
4516
4517 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004518 const Expr *E = getCursorExpr(C);
4519
4520 if (C.kind == CXCursor_ObjCStringLiteral ||
4521 C.kind == CXCursor_StringLiteral) {
4522 const StringLiteral *SLit;
4523 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4524 SLit = OSL->getString();
4525 } else {
4526 SLit = cast<StringLiteral>(E);
4527 }
4528 SmallString<256> Buf;
4529 llvm::raw_svector_ostream OS(Buf);
4530 SLit->outputString(OS);
4531 return cxstring::createDup(OS.str());
4532 }
4533
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004534 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 if (D)
4536 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004537 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 }
4539
4540 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004541 const Stmt *S = getCursorStmt(C);
4542 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004543 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004544
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004545 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 }
4547
4548 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004549 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 ->getNameStart());
4551
4552 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004553 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 ->getNameStart());
4555
4556 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004557 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004558
4559 if (clang_isDeclaration(C.kind))
4560 return getDeclSpelling(getCursorDecl(C));
4561
4562 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004563 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004564 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 }
4566
4567 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004568 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004569 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 }
4571
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004572 if (C.kind == CXCursor_PackedAttr) {
4573 return cxstring::createRef("packed");
4574 }
4575
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004576 if (C.kind == CXCursor_VisibilityAttr) {
4577 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4578 switch (AA->getVisibility()) {
4579 case VisibilityAttr::VisibilityType::Default:
4580 return cxstring::createRef("default");
4581 case VisibilityAttr::VisibilityType::Hidden:
4582 return cxstring::createRef("hidden");
4583 case VisibilityAttr::VisibilityType::Protected:
4584 return cxstring::createRef("protected");
4585 }
4586 llvm_unreachable("unknown visibility type");
4587 }
4588
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004589 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004590}
4591
4592CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4593 unsigned pieceIndex,
4594 unsigned options) {
4595 if (clang_Cursor_isNull(C))
4596 return clang_getNullRange();
4597
4598 ASTContext &Ctx = getCursorContext(C);
4599
4600 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004601 const Stmt *S = getCursorStmt(C);
4602 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 if (pieceIndex > 0)
4604 return clang_getNullRange();
4605 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4606 }
4607
4608 return clang_getNullRange();
4609 }
4610
4611 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004612 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4614 if (pieceIndex >= ME->getNumSelectorLocs())
4615 return clang_getNullRange();
4616 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4617 }
4618 }
4619
4620 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4621 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004622 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4624 if (pieceIndex >= MD->getNumSelectorLocs())
4625 return clang_getNullRange();
4626 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4627 }
4628 }
4629
4630 if (C.kind == CXCursor_ObjCCategoryDecl ||
4631 C.kind == CXCursor_ObjCCategoryImplDecl) {
4632 if (pieceIndex > 0)
4633 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004634 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4636 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004637 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4639 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4640 }
4641
4642 if (C.kind == CXCursor_ModuleImportDecl) {
4643 if (pieceIndex > 0)
4644 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004645 if (const ImportDecl *ImportD =
4646 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4648 if (!Locs.empty())
4649 return cxloc::translateSourceRange(Ctx,
4650 SourceRange(Locs.front(), Locs.back()));
4651 }
4652 return clang_getNullRange();
4653 }
4654
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004655 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004656 C.kind == CXCursor_ConversionFunction ||
4657 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004658 if (pieceIndex > 0)
4659 return clang_getNullRange();
4660 if (const FunctionDecl *FD =
4661 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4662 DeclarationNameInfo FunctionName = FD->getNameInfo();
4663 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4664 }
4665 return clang_getNullRange();
4666 }
4667
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 // FIXME: A CXCursor_InclusionDirective should give the location of the
4669 // filename, but we don't keep track of this.
4670
4671 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4672 // but we don't keep track of this.
4673
4674 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4675 // but we don't keep track of this.
4676
4677 // Default handling, give the location of the cursor.
4678
4679 if (pieceIndex > 0)
4680 return clang_getNullRange();
4681
4682 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4683 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4684 return cxloc::translateSourceRange(Ctx, Loc);
4685}
4686
Eli Bendersky44a206f2014-07-31 18:04:56 +00004687CXString clang_Cursor_getMangling(CXCursor C) {
4688 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4689 return cxstring::createEmpty();
4690
Eli Bendersky44a206f2014-07-31 18:04:56 +00004691 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004692 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004693 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4694 return cxstring::createEmpty();
4695
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004696 ASTContext &Ctx = D->getASTContext();
4697 index::CodegenNameGenerator CGNameGen(Ctx);
4698 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004699}
4700
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004701CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4702 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4703 return nullptr;
4704
4705 const Decl *D = getCursorDecl(C);
4706 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4707 return nullptr;
4708
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004709 ASTContext &Ctx = D->getASTContext();
4710 index::CodegenNameGenerator CGNameGen(Ctx);
4711 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004712 return cxstring::createSet(Manglings);
4713}
4714
Dave Lee1a532c92017-09-22 16:58:57 +00004715CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4716 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4717 return nullptr;
4718
4719 const Decl *D = getCursorDecl(C);
4720 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4721 return nullptr;
4722
4723 ASTContext &Ctx = D->getASTContext();
4724 index::CodegenNameGenerator CGNameGen(Ctx);
4725 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4726 return cxstring::createSet(Manglings);
4727}
4728
Jonathan Coe45ef5032018-01-16 10:19:56 +00004729CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4730 if (clang_Cursor_isNull(C))
4731 return 0;
4732 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4733}
4734
4735void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4736 if (Policy)
4737 delete static_cast<PrintingPolicy *>(Policy);
4738}
4739
4740unsigned
4741clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4742 enum CXPrintingPolicyProperty Property) {
4743 if (!Policy)
4744 return 0;
4745
4746 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4747 switch (Property) {
4748 case CXPrintingPolicy_Indentation:
4749 return P->Indentation;
4750 case CXPrintingPolicy_SuppressSpecifiers:
4751 return P->SuppressSpecifiers;
4752 case CXPrintingPolicy_SuppressTagKeyword:
4753 return P->SuppressTagKeyword;
4754 case CXPrintingPolicy_IncludeTagDefinition:
4755 return P->IncludeTagDefinition;
4756 case CXPrintingPolicy_SuppressScope:
4757 return P->SuppressScope;
4758 case CXPrintingPolicy_SuppressUnwrittenScope:
4759 return P->SuppressUnwrittenScope;
4760 case CXPrintingPolicy_SuppressInitializers:
4761 return P->SuppressInitializers;
4762 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4763 return P->ConstantArraySizeAsWritten;
4764 case CXPrintingPolicy_AnonymousTagLocations:
4765 return P->AnonymousTagLocations;
4766 case CXPrintingPolicy_SuppressStrongLifetime:
4767 return P->SuppressStrongLifetime;
4768 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4769 return P->SuppressLifetimeQualifiers;
4770 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4771 return P->SuppressTemplateArgsInCXXConstructors;
4772 case CXPrintingPolicy_Bool:
4773 return P->Bool;
4774 case CXPrintingPolicy_Restrict:
4775 return P->Restrict;
4776 case CXPrintingPolicy_Alignof:
4777 return P->Alignof;
4778 case CXPrintingPolicy_UnderscoreAlignof:
4779 return P->UnderscoreAlignof;
4780 case CXPrintingPolicy_UseVoidForZeroParams:
4781 return P->UseVoidForZeroParams;
4782 case CXPrintingPolicy_TerseOutput:
4783 return P->TerseOutput;
4784 case CXPrintingPolicy_PolishForDeclaration:
4785 return P->PolishForDeclaration;
4786 case CXPrintingPolicy_Half:
4787 return P->Half;
4788 case CXPrintingPolicy_MSWChar:
4789 return P->MSWChar;
4790 case CXPrintingPolicy_IncludeNewlines:
4791 return P->IncludeNewlines;
4792 case CXPrintingPolicy_MSVCFormatting:
4793 return P->MSVCFormatting;
4794 case CXPrintingPolicy_ConstantsAsWritten:
4795 return P->ConstantsAsWritten;
4796 case CXPrintingPolicy_SuppressImplicitBase:
4797 return P->SuppressImplicitBase;
4798 case CXPrintingPolicy_FullyQualifiedName:
4799 return P->FullyQualifiedName;
4800 }
4801
4802 assert(false && "Invalid CXPrintingPolicyProperty");
4803 return 0;
4804}
4805
4806void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4807 enum CXPrintingPolicyProperty Property,
4808 unsigned Value) {
4809 if (!Policy)
4810 return;
4811
4812 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4813 switch (Property) {
4814 case CXPrintingPolicy_Indentation:
4815 P->Indentation = Value;
4816 return;
4817 case CXPrintingPolicy_SuppressSpecifiers:
4818 P->SuppressSpecifiers = Value;
4819 return;
4820 case CXPrintingPolicy_SuppressTagKeyword:
4821 P->SuppressTagKeyword = Value;
4822 return;
4823 case CXPrintingPolicy_IncludeTagDefinition:
4824 P->IncludeTagDefinition = Value;
4825 return;
4826 case CXPrintingPolicy_SuppressScope:
4827 P->SuppressScope = Value;
4828 return;
4829 case CXPrintingPolicy_SuppressUnwrittenScope:
4830 P->SuppressUnwrittenScope = Value;
4831 return;
4832 case CXPrintingPolicy_SuppressInitializers:
4833 P->SuppressInitializers = Value;
4834 return;
4835 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4836 P->ConstantArraySizeAsWritten = Value;
4837 return;
4838 case CXPrintingPolicy_AnonymousTagLocations:
4839 P->AnonymousTagLocations = Value;
4840 return;
4841 case CXPrintingPolicy_SuppressStrongLifetime:
4842 P->SuppressStrongLifetime = Value;
4843 return;
4844 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4845 P->SuppressLifetimeQualifiers = Value;
4846 return;
4847 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4848 P->SuppressTemplateArgsInCXXConstructors = Value;
4849 return;
4850 case CXPrintingPolicy_Bool:
4851 P->Bool = Value;
4852 return;
4853 case CXPrintingPolicy_Restrict:
4854 P->Restrict = Value;
4855 return;
4856 case CXPrintingPolicy_Alignof:
4857 P->Alignof = Value;
4858 return;
4859 case CXPrintingPolicy_UnderscoreAlignof:
4860 P->UnderscoreAlignof = Value;
4861 return;
4862 case CXPrintingPolicy_UseVoidForZeroParams:
4863 P->UseVoidForZeroParams = Value;
4864 return;
4865 case CXPrintingPolicy_TerseOutput:
4866 P->TerseOutput = Value;
4867 return;
4868 case CXPrintingPolicy_PolishForDeclaration:
4869 P->PolishForDeclaration = Value;
4870 return;
4871 case CXPrintingPolicy_Half:
4872 P->Half = Value;
4873 return;
4874 case CXPrintingPolicy_MSWChar:
4875 P->MSWChar = Value;
4876 return;
4877 case CXPrintingPolicy_IncludeNewlines:
4878 P->IncludeNewlines = Value;
4879 return;
4880 case CXPrintingPolicy_MSVCFormatting:
4881 P->MSVCFormatting = Value;
4882 return;
4883 case CXPrintingPolicy_ConstantsAsWritten:
4884 P->ConstantsAsWritten = Value;
4885 return;
4886 case CXPrintingPolicy_SuppressImplicitBase:
4887 P->SuppressImplicitBase = Value;
4888 return;
4889 case CXPrintingPolicy_FullyQualifiedName:
4890 P->FullyQualifiedName = Value;
4891 return;
4892 }
4893
4894 assert(false && "Invalid CXPrintingPolicyProperty");
4895}
4896
4897CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4898 if (clang_Cursor_isNull(C))
4899 return cxstring::createEmpty();
4900
4901 if (clang_isDeclaration(C.kind)) {
4902 const Decl *D = getCursorDecl(C);
4903 if (!D)
4904 return cxstring::createEmpty();
4905
4906 SmallString<128> Str;
4907 llvm::raw_svector_ostream OS(Str);
4908 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4909 D->print(OS, UserPolicy ? *UserPolicy
4910 : getCursorContext(C).getPrintingPolicy());
4911
4912 return cxstring::createDup(OS.str());
4913 }
4914
4915 return cxstring::createEmpty();
4916}
4917
Guy Benyei11169dd2012-12-18 14:30:41 +00004918CXString clang_getCursorDisplayName(CXCursor C) {
4919 if (!clang_isDeclaration(C.kind))
4920 return clang_getCursorSpelling(C);
4921
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004922 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004924 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004925
4926 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004927 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 D = FunTmpl->getTemplatedDecl();
4929
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004930 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004931 SmallString<64> Str;
4932 llvm::raw_svector_ostream OS(Str);
4933 OS << *Function;
4934 if (Function->getPrimaryTemplate())
4935 OS << "<>";
4936 OS << "(";
4937 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4938 if (I)
4939 OS << ", ";
4940 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4941 }
4942
4943 if (Function->isVariadic()) {
4944 if (Function->getNumParams())
4945 OS << ", ";
4946 OS << "...";
4947 }
4948 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004949 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004950 }
4951
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004952 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004953 SmallString<64> Str;
4954 llvm::raw_svector_ostream OS(Str);
4955 OS << *ClassTemplate;
4956 OS << "<";
4957 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4958 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4959 if (I)
4960 OS << ", ";
4961
4962 NamedDecl *Param = Params->getParam(I);
4963 if (Param->getIdentifier()) {
4964 OS << Param->getIdentifier()->getName();
4965 continue;
4966 }
4967
4968 // There is no parameter name, which makes this tricky. Try to come up
4969 // with something useful that isn't too long.
4970 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4971 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4972 else if (NonTypeTemplateParmDecl *NTTP
4973 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4974 OS << NTTP->getType().getAsString(Policy);
4975 else
4976 OS << "template<...> class";
4977 }
4978
4979 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004980 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 }
4982
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004983 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4985 // If the type was explicitly written, use that.
4986 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004987 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004988
Benjamin Kramer9170e912013-02-22 15:46:01 +00004989 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 llvm::raw_svector_ostream OS(Str);
4991 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00004992 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
4993 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004994 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 }
4996
4997 return clang_getCursorSpelling(C);
4998}
4999
5000CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5001 switch (Kind) {
5002 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005003 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005005 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005007 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005008 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005009 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005011 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005013 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005015 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005017 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005019 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005021 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005023 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005025 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005027 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005029 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005031 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005033 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005035 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005037 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005039 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005041 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005043 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005045 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005047 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005049 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005051 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005053 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005055 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005057 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005059 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005061 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005063 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005065 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005066 case CXCursor_FixedPointLiteral:
5067 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005069 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005071 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005073 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005075 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005077 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005079 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005081 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005082 case CXCursor_OMPArraySectionExpr:
5083 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005085 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005087 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005089 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005091 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005093 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005097 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005101 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005134 case CXCursor_ObjCAvailabilityCheckExpr:
5135 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005136 case CXCursor_ObjCSelfExpr:
5137 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005226 case CXCursor_SEHLeaveStmt:
5227 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005256 case CXCursor_PackedAttr:
5257 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005258 case CXCursor_PureAttr:
5259 return cxstring::createRef("attribute(pure)");
5260 case CXCursor_ConstAttr:
5261 return cxstring::createRef("attribute(const)");
5262 case CXCursor_NoDuplicateAttr:
5263 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005264 case CXCursor_CUDAConstantAttr:
5265 return cxstring::createRef("attribute(constant)");
5266 case CXCursor_CUDADeviceAttr:
5267 return cxstring::createRef("attribute(device)");
5268 case CXCursor_CUDAGlobalAttr:
5269 return cxstring::createRef("attribute(global)");
5270 case CXCursor_CUDAHostAttr:
5271 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005272 case CXCursor_CUDASharedAttr:
5273 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005274 case CXCursor_VisibilityAttr:
5275 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005276 case CXCursor_DLLExport:
5277 return cxstring::createRef("attribute(dllexport)");
5278 case CXCursor_DLLImport:
5279 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005297 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005307 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005309 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005311 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005313 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005315 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005317 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005319 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005321 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005323 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005325 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005327 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005328 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005329 return cxstring::createRef("OMPParallelDirective");
5330 case CXCursor_OMPSimdDirective:
5331 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005332 case CXCursor_OMPForDirective:
5333 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005334 case CXCursor_OMPForSimdDirective:
5335 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005336 case CXCursor_OMPSectionsDirective:
5337 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005338 case CXCursor_OMPSectionDirective:
5339 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005340 case CXCursor_OMPSingleDirective:
5341 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005342 case CXCursor_OMPMasterDirective:
5343 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005344 case CXCursor_OMPCriticalDirective:
5345 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005346 case CXCursor_OMPParallelForDirective:
5347 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005348 case CXCursor_OMPParallelForSimdDirective:
5349 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005350 case CXCursor_OMPParallelSectionsDirective:
5351 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005352 case CXCursor_OMPTaskDirective:
5353 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005354 case CXCursor_OMPTaskyieldDirective:
5355 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005356 case CXCursor_OMPBarrierDirective:
5357 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005358 case CXCursor_OMPTaskwaitDirective:
5359 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005360 case CXCursor_OMPTaskgroupDirective:
5361 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005362 case CXCursor_OMPFlushDirective:
5363 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005364 case CXCursor_OMPOrderedDirective:
5365 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005366 case CXCursor_OMPAtomicDirective:
5367 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005368 case CXCursor_OMPTargetDirective:
5369 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005370 case CXCursor_OMPTargetDataDirective:
5371 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005372 case CXCursor_OMPTargetEnterDataDirective:
5373 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005374 case CXCursor_OMPTargetExitDataDirective:
5375 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005376 case CXCursor_OMPTargetParallelDirective:
5377 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005378 case CXCursor_OMPTargetParallelForDirective:
5379 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005380 case CXCursor_OMPTargetUpdateDirective:
5381 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005382 case CXCursor_OMPTeamsDirective:
5383 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005384 case CXCursor_OMPCancellationPointDirective:
5385 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005386 case CXCursor_OMPCancelDirective:
5387 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005388 case CXCursor_OMPTaskLoopDirective:
5389 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005390 case CXCursor_OMPTaskLoopSimdDirective:
5391 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005392 case CXCursor_OMPDistributeDirective:
5393 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005394 case CXCursor_OMPDistributeParallelForDirective:
5395 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005396 case CXCursor_OMPDistributeParallelForSimdDirective:
5397 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005398 case CXCursor_OMPDistributeSimdDirective:
5399 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005400 case CXCursor_OMPTargetParallelForSimdDirective:
5401 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005402 case CXCursor_OMPTargetSimdDirective:
5403 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005404 case CXCursor_OMPTeamsDistributeDirective:
5405 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005406 case CXCursor_OMPTeamsDistributeSimdDirective:
5407 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005408 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5409 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005410 case CXCursor_OMPTeamsDistributeParallelForDirective:
5411 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005412 case CXCursor_OMPTargetTeamsDirective:
5413 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005414 case CXCursor_OMPTargetTeamsDistributeDirective:
5415 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005416 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5417 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005418 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5419 return cxstring::createRef(
5420 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005421 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5422 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005423 case CXCursor_OverloadCandidate:
5424 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005425 case CXCursor_TypeAliasTemplateDecl:
5426 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005427 case CXCursor_StaticAssert:
5428 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005429 case CXCursor_FriendDecl:
5430 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005431 }
5432
5433 llvm_unreachable("Unhandled CXCursorKind");
5434}
5435
5436struct GetCursorData {
5437 SourceLocation TokenBeginLoc;
5438 bool PointsAtMacroArgExpansion;
5439 bool VisitedObjCPropertyImplDecl;
5440 SourceLocation VisitedDeclaratorDeclStartLoc;
5441 CXCursor &BestCursor;
5442
5443 GetCursorData(SourceManager &SM,
5444 SourceLocation tokenBegin, CXCursor &outputCursor)
5445 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5446 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5447 VisitedObjCPropertyImplDecl = false;
5448 }
5449};
5450
5451static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5452 CXCursor parent,
5453 CXClientData client_data) {
5454 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5455 CXCursor *BestCursor = &Data->BestCursor;
5456
5457 // If we point inside a macro argument we should provide info of what the
5458 // token is so use the actual cursor, don't replace it with a macro expansion
5459 // cursor.
5460 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5461 return CXChildVisit_Recurse;
5462
5463 if (clang_isDeclaration(cursor.kind)) {
5464 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005465 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005466 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5467 if (MD->isImplicit())
5468 return CXChildVisit_Break;
5469
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005470 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005471 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5472 // Check that when we have multiple @class references in the same line,
5473 // that later ones do not override the previous ones.
5474 // If we have:
5475 // @class Foo, Bar;
5476 // source ranges for both start at '@', so 'Bar' will end up overriding
5477 // 'Foo' even though the cursor location was at 'Foo'.
5478 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5479 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005480 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005481 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5482 if (PrevID != ID &&
5483 !PrevID->isThisDeclarationADefinition() &&
5484 !ID->isThisDeclarationADefinition())
5485 return CXChildVisit_Break;
5486 }
5487
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005488 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005489 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5490 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5491 // Check that when we have multiple declarators in the same line,
5492 // that later ones do not override the previous ones.
5493 // If we have:
5494 // int Foo, Bar;
5495 // source ranges for both start at 'int', so 'Bar' will end up overriding
5496 // 'Foo' even though the cursor location was at 'Foo'.
5497 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5498 return CXChildVisit_Break;
5499 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5500
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005501 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005502 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5503 (void)PropImp;
5504 // Check that when we have multiple @synthesize in the same line,
5505 // that later ones do not override the previous ones.
5506 // If we have:
5507 // @synthesize Foo, Bar;
5508 // source ranges for both start at '@', so 'Bar' will end up overriding
5509 // 'Foo' even though the cursor location was at 'Foo'.
5510 if (Data->VisitedObjCPropertyImplDecl)
5511 return CXChildVisit_Break;
5512 Data->VisitedObjCPropertyImplDecl = true;
5513 }
5514 }
5515
5516 if (clang_isExpression(cursor.kind) &&
5517 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005518 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 // Avoid having the cursor of an expression replace the declaration cursor
5520 // when the expression source range overlaps the declaration range.
5521 // This can happen for C++ constructor expressions whose range generally
5522 // include the variable declaration, e.g.:
5523 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5524 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5525 D->getLocation() == Data->TokenBeginLoc)
5526 return CXChildVisit_Break;
5527 }
5528 }
5529
5530 // If our current best cursor is the construction of a temporary object,
5531 // don't replace that cursor with a type reference, because we want
5532 // clang_getCursor() to point at the constructor.
5533 if (clang_isExpression(BestCursor->kind) &&
5534 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5535 cursor.kind == CXCursor_TypeRef) {
5536 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5537 // as having the actual point on the type reference.
5538 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5539 return CXChildVisit_Recurse;
5540 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005541
5542 // If we already have an Objective-C superclass reference, don't
5543 // update it further.
5544 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5545 return CXChildVisit_Break;
5546
Guy Benyei11169dd2012-12-18 14:30:41 +00005547 *BestCursor = cursor;
5548 return CXChildVisit_Recurse;
5549}
5550
5551CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005552 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005553 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005555 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005556
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005557 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005558 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5559
5560 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5561 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5562
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005563 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005564 CXFile SearchFile;
5565 unsigned SearchLine, SearchColumn;
5566 CXFile ResultFile;
5567 unsigned ResultLine, ResultColumn;
5568 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5569 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5570 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005571
5572 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5573 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005574 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005575 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005576 SearchFileName = clang_getFileName(SearchFile);
5577 ResultFileName = clang_getFileName(ResultFile);
5578 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5579 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005580 *Log << llvm::format("(%s:%d:%d) = %s",
5581 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5582 clang_getCString(KindSpelling))
5583 << llvm::format("(%s:%d:%d):%s%s",
5584 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5585 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005586 clang_disposeString(SearchFileName);
5587 clang_disposeString(ResultFileName);
5588 clang_disposeString(KindSpelling);
5589 clang_disposeString(USR);
5590
5591 CXCursor Definition = clang_getCursorDefinition(Result);
5592 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5593 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5594 CXString DefinitionKindSpelling
5595 = clang_getCursorKindSpelling(Definition.kind);
5596 CXFile DefinitionFile;
5597 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005598 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005599 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005600 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005601 *Log << llvm::format(" -> %s(%s:%d:%d)",
5602 clang_getCString(DefinitionKindSpelling),
5603 clang_getCString(DefinitionFileName),
5604 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005605 clang_disposeString(DefinitionFileName);
5606 clang_disposeString(DefinitionKindSpelling);
5607 }
5608 }
5609
5610 return Result;
5611}
5612
5613CXCursor clang_getNullCursor(void) {
5614 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5615}
5616
5617unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005618 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5619 // can't set consistently. For example, when visiting a DeclStmt we will set
5620 // it but we don't set it on the result of clang_getCursorDefinition for
5621 // a reference of the same declaration.
5622 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5623 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5624 // to provide that kind of info.
5625 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005626 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005627 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005628 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005629
Guy Benyei11169dd2012-12-18 14:30:41 +00005630 return X == Y;
5631}
5632
5633unsigned clang_hashCursor(CXCursor C) {
5634 unsigned Index = 0;
5635 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5636 Index = 1;
5637
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005638 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005639 std::make_pair(C.kind, C.data[Index]));
5640}
5641
5642unsigned clang_isInvalid(enum CXCursorKind K) {
5643 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5644}
5645
5646unsigned clang_isDeclaration(enum CXCursorKind K) {
5647 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005648 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5649}
5650
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005651unsigned clang_isInvalidDeclaration(CXCursor C) {
5652 if (clang_isDeclaration(C.kind)) {
5653 if (const Decl *D = getCursorDecl(C))
5654 return D->isInvalidDecl();
5655 }
5656
5657 return 0;
5658}
5659
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005660unsigned clang_isReference(enum CXCursorKind K) {
5661 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5662}
Guy Benyei11169dd2012-12-18 14:30:41 +00005663
5664unsigned clang_isExpression(enum CXCursorKind K) {
5665 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5666}
5667
5668unsigned clang_isStatement(enum CXCursorKind K) {
5669 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5670}
5671
5672unsigned clang_isAttribute(enum CXCursorKind K) {
5673 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5674}
5675
5676unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5677 return K == CXCursor_TranslationUnit;
5678}
5679
5680unsigned clang_isPreprocessing(enum CXCursorKind K) {
5681 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5682}
5683
5684unsigned clang_isUnexposed(enum CXCursorKind K) {
5685 switch (K) {
5686 case CXCursor_UnexposedDecl:
5687 case CXCursor_UnexposedExpr:
5688 case CXCursor_UnexposedStmt:
5689 case CXCursor_UnexposedAttr:
5690 return true;
5691 default:
5692 return false;
5693 }
5694}
5695
5696CXCursorKind clang_getCursorKind(CXCursor C) {
5697 return C.kind;
5698}
5699
5700CXSourceLocation clang_getCursorLocation(CXCursor C) {
5701 if (clang_isReference(C.kind)) {
5702 switch (C.kind) {
5703 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005704 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005705 = getCursorObjCSuperClassRef(C);
5706 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5707 }
5708
5709 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005710 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005711 = getCursorObjCProtocolRef(C);
5712 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5713 }
5714
5715 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005716 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005717 = getCursorObjCClassRef(C);
5718 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5719 }
5720
5721 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005722 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005723 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5724 }
5725
5726 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005727 std::pair<const TemplateDecl *, SourceLocation> P =
5728 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005729 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5730 }
5731
5732 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005733 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5735 }
5736
5737 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005738 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005739 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5740 }
5741
5742 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005743 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005744 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5745 }
5746
5747 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005748 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005749 if (!BaseSpec)
5750 return clang_getNullLocation();
5751
5752 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5753 return cxloc::translateSourceLocation(getCursorContext(C),
5754 TSInfo->getTypeLoc().getBeginLoc());
5755
5756 return cxloc::translateSourceLocation(getCursorContext(C),
5757 BaseSpec->getLocStart());
5758 }
5759
5760 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005761 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005762 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5763 }
5764
5765 case CXCursor_OverloadedDeclRef:
5766 return cxloc::translateSourceLocation(getCursorContext(C),
5767 getCursorOverloadedDeclRef(C).second);
5768
5769 default:
5770 // FIXME: Need a way to enumerate all non-reference cases.
5771 llvm_unreachable("Missed a reference kind");
5772 }
5773 }
5774
5775 if (clang_isExpression(C.kind))
5776 return cxloc::translateSourceLocation(getCursorContext(C),
5777 getLocationFromExpr(getCursorExpr(C)));
5778
5779 if (clang_isStatement(C.kind))
5780 return cxloc::translateSourceLocation(getCursorContext(C),
5781 getCursorStmt(C)->getLocStart());
5782
5783 if (C.kind == CXCursor_PreprocessingDirective) {
5784 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5785 return cxloc::translateSourceLocation(getCursorContext(C), L);
5786 }
5787
5788 if (C.kind == CXCursor_MacroExpansion) {
5789 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005790 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005791 return cxloc::translateSourceLocation(getCursorContext(C), L);
5792 }
5793
5794 if (C.kind == CXCursor_MacroDefinition) {
5795 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5796 return cxloc::translateSourceLocation(getCursorContext(C), L);
5797 }
5798
5799 if (C.kind == CXCursor_InclusionDirective) {
5800 SourceLocation L
5801 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5802 return cxloc::translateSourceLocation(getCursorContext(C), L);
5803 }
5804
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005805 if (clang_isAttribute(C.kind)) {
5806 SourceLocation L
5807 = cxcursor::getCursorAttr(C)->getLocation();
5808 return cxloc::translateSourceLocation(getCursorContext(C), L);
5809 }
5810
Guy Benyei11169dd2012-12-18 14:30:41 +00005811 if (!clang_isDeclaration(C.kind))
5812 return clang_getNullLocation();
5813
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005814 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005815 if (!D)
5816 return clang_getNullLocation();
5817
5818 SourceLocation Loc = D->getLocation();
5819 // FIXME: Multiple variables declared in a single declaration
5820 // currently lack the information needed to correctly determine their
5821 // ranges when accounting for the type-specifier. We use context
5822 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5823 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005824 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005825 if (!cxcursor::isFirstInDeclGroup(C))
5826 Loc = VD->getLocation();
5827 }
5828
5829 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005830 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005831 Loc = MD->getSelectorStartLoc();
5832
5833 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5834}
5835
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005836} // end extern "C"
5837
Guy Benyei11169dd2012-12-18 14:30:41 +00005838CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5839 assert(TU);
5840
5841 // Guard against an invalid SourceLocation, or we may assert in one
5842 // of the following calls.
5843 if (SLoc.isInvalid())
5844 return clang_getNullCursor();
5845
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005846 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005847
5848 // Translate the given source location to make it point at the beginning of
5849 // the token under the cursor.
5850 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5851 CXXUnit->getASTContext().getLangOpts());
5852
5853 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5854 if (SLoc.isValid()) {
5855 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5856 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5857 /*VisitPreprocessorLast=*/true,
5858 /*VisitIncludedEntities=*/false,
5859 SourceLocation(SLoc));
5860 CursorVis.visitFileRegion();
5861 }
5862
5863 return Result;
5864}
5865
5866static SourceRange getRawCursorExtent(CXCursor C) {
5867 if (clang_isReference(C.kind)) {
5868 switch (C.kind) {
5869 case CXCursor_ObjCSuperClassRef:
5870 return getCursorObjCSuperClassRef(C).second;
5871
5872 case CXCursor_ObjCProtocolRef:
5873 return getCursorObjCProtocolRef(C).second;
5874
5875 case CXCursor_ObjCClassRef:
5876 return getCursorObjCClassRef(C).second;
5877
5878 case CXCursor_TypeRef:
5879 return getCursorTypeRef(C).second;
5880
5881 case CXCursor_TemplateRef:
5882 return getCursorTemplateRef(C).second;
5883
5884 case CXCursor_NamespaceRef:
5885 return getCursorNamespaceRef(C).second;
5886
5887 case CXCursor_MemberRef:
5888 return getCursorMemberRef(C).second;
5889
5890 case CXCursor_CXXBaseSpecifier:
5891 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5892
5893 case CXCursor_LabelRef:
5894 return getCursorLabelRef(C).second;
5895
5896 case CXCursor_OverloadedDeclRef:
5897 return getCursorOverloadedDeclRef(C).second;
5898
5899 case CXCursor_VariableRef:
5900 return getCursorVariableRef(C).second;
5901
5902 default:
5903 // FIXME: Need a way to enumerate all non-reference cases.
5904 llvm_unreachable("Missed a reference kind");
5905 }
5906 }
5907
5908 if (clang_isExpression(C.kind))
5909 return getCursorExpr(C)->getSourceRange();
5910
5911 if (clang_isStatement(C.kind))
5912 return getCursorStmt(C)->getSourceRange();
5913
5914 if (clang_isAttribute(C.kind))
5915 return getCursorAttr(C)->getRange();
5916
5917 if (C.kind == CXCursor_PreprocessingDirective)
5918 return cxcursor::getCursorPreprocessingDirective(C);
5919
5920 if (C.kind == CXCursor_MacroExpansion) {
5921 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005922 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005923 return TU->mapRangeFromPreamble(Range);
5924 }
5925
5926 if (C.kind == CXCursor_MacroDefinition) {
5927 ASTUnit *TU = getCursorASTUnit(C);
5928 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5929 return TU->mapRangeFromPreamble(Range);
5930 }
5931
5932 if (C.kind == CXCursor_InclusionDirective) {
5933 ASTUnit *TU = getCursorASTUnit(C);
5934 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5935 return TU->mapRangeFromPreamble(Range);
5936 }
5937
5938 if (C.kind == CXCursor_TranslationUnit) {
5939 ASTUnit *TU = getCursorASTUnit(C);
5940 FileID MainID = TU->getSourceManager().getMainFileID();
5941 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5942 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5943 return SourceRange(Start, End);
5944 }
5945
5946 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005947 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005948 if (!D)
5949 return SourceRange();
5950
5951 SourceRange R = D->getSourceRange();
5952 // FIXME: Multiple variables declared in a single declaration
5953 // currently lack the information needed to correctly determine their
5954 // ranges when accounting for the type-specifier. We use context
5955 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5956 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005957 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005958 if (!cxcursor::isFirstInDeclGroup(C))
5959 R.setBegin(VD->getLocation());
5960 }
5961 return R;
5962 }
5963 return SourceRange();
5964}
5965
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005966/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00005967/// the decl-specifier-seq for declarations.
5968static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5969 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005970 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005971 if (!D)
5972 return SourceRange();
5973
5974 SourceRange R = D->getSourceRange();
5975
5976 // Adjust the start of the location for declarations preceded by
5977 // declaration specifiers.
5978 SourceLocation StartLoc;
5979 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5980 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5981 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005982 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005983 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5984 StartLoc = TI->getTypeLoc().getLocStart();
5985 }
5986
5987 if (StartLoc.isValid() && R.getBegin().isValid() &&
5988 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5989 R.setBegin(StartLoc);
5990
5991 // FIXME: Multiple variables declared in a single declaration
5992 // currently lack the information needed to correctly determine their
5993 // ranges when accounting for the type-specifier. We use context
5994 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5995 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005996 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005997 if (!cxcursor::isFirstInDeclGroup(C))
5998 R.setBegin(VD->getLocation());
5999 }
6000
6001 return R;
6002 }
6003
6004 return getRawCursorExtent(C);
6005}
6006
Guy Benyei11169dd2012-12-18 14:30:41 +00006007CXSourceRange clang_getCursorExtent(CXCursor C) {
6008 SourceRange R = getRawCursorExtent(C);
6009 if (R.isInvalid())
6010 return clang_getNullRange();
6011
6012 return cxloc::translateSourceRange(getCursorContext(C), R);
6013}
6014
6015CXCursor clang_getCursorReferenced(CXCursor C) {
6016 if (clang_isInvalid(C.kind))
6017 return clang_getNullCursor();
6018
6019 CXTranslationUnit tu = getCursorTU(C);
6020 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006021 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006022 if (!D)
6023 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006024 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006025 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006026 if (const ObjCPropertyImplDecl *PropImpl =
6027 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006028 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6029 return MakeCXCursor(Property, tu);
6030
6031 return C;
6032 }
6033
6034 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006035 const Expr *E = getCursorExpr(C);
6036 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 if (D) {
6038 CXCursor declCursor = MakeCXCursor(D, tu);
6039 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6040 declCursor);
6041 return declCursor;
6042 }
6043
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006044 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006045 return MakeCursorOverloadedDeclRef(Ovl, tu);
6046
6047 return clang_getNullCursor();
6048 }
6049
6050 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006051 const Stmt *S = getCursorStmt(C);
6052 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006053 if (LabelDecl *label = Goto->getLabel())
6054 if (LabelStmt *labelS = label->getStmt())
6055 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6056
6057 return clang_getNullCursor();
6058 }
Richard Smith66a81862015-05-04 02:25:31 +00006059
Guy Benyei11169dd2012-12-18 14:30:41 +00006060 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006061 if (const MacroDefinitionRecord *Def =
6062 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006063 return MakeMacroDefinitionCursor(Def, tu);
6064 }
6065
6066 if (!clang_isReference(C.kind))
6067 return clang_getNullCursor();
6068
6069 switch (C.kind) {
6070 case CXCursor_ObjCSuperClassRef:
6071 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6072
6073 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006074 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6075 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006076 return MakeCXCursor(Def, tu);
6077
6078 return MakeCXCursor(Prot, tu);
6079 }
6080
6081 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006082 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6083 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006084 return MakeCXCursor(Def, tu);
6085
6086 return MakeCXCursor(Class, tu);
6087 }
6088
6089 case CXCursor_TypeRef:
6090 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6091
6092 case CXCursor_TemplateRef:
6093 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6094
6095 case CXCursor_NamespaceRef:
6096 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6097
6098 case CXCursor_MemberRef:
6099 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6100
6101 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006102 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006103 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6104 tu ));
6105 }
6106
6107 case CXCursor_LabelRef:
6108 // FIXME: We end up faking the "parent" declaration here because we
6109 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006110 return MakeCXCursor(getCursorLabelRef(C).first,
6111 cxtu::getASTUnit(tu)->getASTContext()
6112 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006113 tu);
6114
6115 case CXCursor_OverloadedDeclRef:
6116 return C;
6117
6118 case CXCursor_VariableRef:
6119 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6120
6121 default:
6122 // We would prefer to enumerate all non-reference cursor kinds here.
6123 llvm_unreachable("Unhandled reference cursor kind");
6124 }
6125}
6126
6127CXCursor clang_getCursorDefinition(CXCursor C) {
6128 if (clang_isInvalid(C.kind))
6129 return clang_getNullCursor();
6130
6131 CXTranslationUnit TU = getCursorTU(C);
6132
6133 bool WasReference = false;
6134 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6135 C = clang_getCursorReferenced(C);
6136 WasReference = true;
6137 }
6138
6139 if (C.kind == CXCursor_MacroExpansion)
6140 return clang_getCursorReferenced(C);
6141
6142 if (!clang_isDeclaration(C.kind))
6143 return clang_getNullCursor();
6144
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006145 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006146 if (!D)
6147 return clang_getNullCursor();
6148
6149 switch (D->getKind()) {
6150 // Declaration kinds that don't really separate the notions of
6151 // declaration and definition.
6152 case Decl::Namespace:
6153 case Decl::Typedef:
6154 case Decl::TypeAlias:
6155 case Decl::TypeAliasTemplate:
6156 case Decl::TemplateTypeParm:
6157 case Decl::EnumConstant:
6158 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006159 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006160 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006161 case Decl::IndirectField:
6162 case Decl::ObjCIvar:
6163 case Decl::ObjCAtDefsField:
6164 case Decl::ImplicitParam:
6165 case Decl::ParmVar:
6166 case Decl::NonTypeTemplateParm:
6167 case Decl::TemplateTemplateParm:
6168 case Decl::ObjCCategoryImpl:
6169 case Decl::ObjCImplementation:
6170 case Decl::AccessSpec:
6171 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006172 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006173 case Decl::ObjCPropertyImpl:
6174 case Decl::FileScopeAsm:
6175 case Decl::StaticAssert:
6176 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006177 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006178 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006179 case Decl::Label: // FIXME: Is this right??
6180 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006181 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006182 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006183 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006184 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006185 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006186 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006187 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006188 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006189 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006190 return C;
6191
6192 // Declaration kinds that don't make any sense here, but are
6193 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006194 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006195 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006196 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006197 break;
6198
6199 // Declaration kinds for which the definition is not resolvable.
6200 case Decl::UnresolvedUsingTypename:
6201 case Decl::UnresolvedUsingValue:
6202 break;
6203
6204 case Decl::UsingDirective:
6205 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6206 TU);
6207
6208 case Decl::NamespaceAlias:
6209 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6210
6211 case Decl::Enum:
6212 case Decl::Record:
6213 case Decl::CXXRecord:
6214 case Decl::ClassTemplateSpecialization:
6215 case Decl::ClassTemplatePartialSpecialization:
6216 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6217 return MakeCXCursor(Def, TU);
6218 return clang_getNullCursor();
6219
6220 case Decl::Function:
6221 case Decl::CXXMethod:
6222 case Decl::CXXConstructor:
6223 case Decl::CXXDestructor:
6224 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006225 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006226 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006227 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006228 return clang_getNullCursor();
6229 }
6230
Larisse Voufo39a1e502013-08-06 01:03:05 +00006231 case Decl::Var:
6232 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006233 case Decl::VarTemplatePartialSpecialization:
6234 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006236 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006237 return MakeCXCursor(Def, TU);
6238 return clang_getNullCursor();
6239 }
6240
6241 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006242 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006243 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6244 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6245 return clang_getNullCursor();
6246 }
6247
6248 case Decl::ClassTemplate: {
6249 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6250 ->getDefinition())
6251 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6252 TU);
6253 return clang_getNullCursor();
6254 }
6255
Larisse Voufo39a1e502013-08-06 01:03:05 +00006256 case Decl::VarTemplate: {
6257 if (VarDecl *Def =
6258 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6259 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6260 return clang_getNullCursor();
6261 }
6262
Guy Benyei11169dd2012-12-18 14:30:41 +00006263 case Decl::Using:
6264 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6265 D->getLocation(), TU);
6266
6267 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006268 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006269 return clang_getCursorDefinition(
6270 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6271 TU));
6272
6273 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006274 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006275 if (Method->isThisDeclarationADefinition())
6276 return C;
6277
6278 // Dig out the method definition in the associated
6279 // @implementation, if we have it.
6280 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006281 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006282 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6283 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6284 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6285 Method->isInstanceMethod()))
6286 if (Def->isThisDeclarationADefinition())
6287 return MakeCXCursor(Def, TU);
6288
6289 return clang_getNullCursor();
6290 }
6291
6292 case Decl::ObjCCategory:
6293 if (ObjCCategoryImplDecl *Impl
6294 = cast<ObjCCategoryDecl>(D)->getImplementation())
6295 return MakeCXCursor(Impl, TU);
6296 return clang_getNullCursor();
6297
6298 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006299 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006300 return MakeCXCursor(Def, TU);
6301 return clang_getNullCursor();
6302
6303 case Decl::ObjCInterface: {
6304 // There are two notions of a "definition" for an Objective-C
6305 // class: the interface and its implementation. When we resolved a
6306 // reference to an Objective-C class, produce the @interface as
6307 // the definition; when we were provided with the interface,
6308 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006309 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006310 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006311 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006312 return MakeCXCursor(Def, TU);
6313 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6314 return MakeCXCursor(Impl, TU);
6315 return clang_getNullCursor();
6316 }
6317
6318 case Decl::ObjCProperty:
6319 // FIXME: We don't really know where to find the
6320 // ObjCPropertyImplDecls that implement this property.
6321 return clang_getNullCursor();
6322
6323 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006324 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006325 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006326 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006327 return MakeCXCursor(Def, TU);
6328
6329 return clang_getNullCursor();
6330
6331 case Decl::Friend:
6332 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6333 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6334 return clang_getNullCursor();
6335
6336 case Decl::FriendTemplate:
6337 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6338 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6339 return clang_getNullCursor();
6340 }
6341
6342 return clang_getNullCursor();
6343}
6344
6345unsigned clang_isCursorDefinition(CXCursor C) {
6346 if (!clang_isDeclaration(C.kind))
6347 return 0;
6348
6349 return clang_getCursorDefinition(C) == C;
6350}
6351
6352CXCursor clang_getCanonicalCursor(CXCursor C) {
6353 if (!clang_isDeclaration(C.kind))
6354 return C;
6355
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006356 if (const Decl *D = getCursorDecl(C)) {
6357 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006358 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6359 return MakeCXCursor(CatD, getCursorTU(C));
6360
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006361 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6362 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006363 return MakeCXCursor(IFD, getCursorTU(C));
6364
6365 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6366 }
6367
6368 return C;
6369}
6370
6371int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6372 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6373}
6374
6375unsigned clang_getNumOverloadedDecls(CXCursor C) {
6376 if (C.kind != CXCursor_OverloadedDeclRef)
6377 return 0;
6378
6379 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006380 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 return E->getNumDecls();
6382
6383 if (OverloadedTemplateStorage *S
6384 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6385 return S->size();
6386
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006387 const Decl *D = Storage.get<const Decl *>();
6388 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006389 return Using->shadow_size();
6390
6391 return 0;
6392}
6393
6394CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6395 if (cursor.kind != CXCursor_OverloadedDeclRef)
6396 return clang_getNullCursor();
6397
6398 if (index >= clang_getNumOverloadedDecls(cursor))
6399 return clang_getNullCursor();
6400
6401 CXTranslationUnit TU = getCursorTU(cursor);
6402 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006403 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 return MakeCXCursor(E->decls_begin()[index], TU);
6405
6406 if (OverloadedTemplateStorage *S
6407 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6408 return MakeCXCursor(S->begin()[index], TU);
6409
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006410 const Decl *D = Storage.get<const Decl *>();
6411 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 // FIXME: This is, unfortunately, linear time.
6413 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6414 std::advance(Pos, index);
6415 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6416 }
6417
6418 return clang_getNullCursor();
6419}
6420
6421void clang_getDefinitionSpellingAndExtent(CXCursor C,
6422 const char **startBuf,
6423 const char **endBuf,
6424 unsigned *startLine,
6425 unsigned *startColumn,
6426 unsigned *endLine,
6427 unsigned *endColumn) {
6428 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006429 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6431
6432 SourceManager &SM = FD->getASTContext().getSourceManager();
6433 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6434 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6435 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6436 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6437 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6438 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6439}
6440
6441
6442CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6443 unsigned PieceIndex) {
6444 RefNamePieces Pieces;
6445
6446 switch (C.kind) {
6447 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006448 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6450 E->getQualifierLoc().getSourceRange());
6451 break;
6452
6453 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006454 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6455 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6456 Pieces =
6457 buildPieces(NameFlags, false, E->getNameInfo(),
6458 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6459 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006460 break;
6461
6462 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006463 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006464 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006465 const Expr *Callee = OCE->getCallee();
6466 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006467 Callee = ICE->getSubExpr();
6468
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006469 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006470 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6471 DRE->getQualifierLoc().getSourceRange());
6472 }
6473 break;
6474
6475 default:
6476 break;
6477 }
6478
6479 if (Pieces.empty()) {
6480 if (PieceIndex == 0)
6481 return clang_getCursorExtent(C);
6482 } else if (PieceIndex < Pieces.size()) {
6483 SourceRange R = Pieces[PieceIndex];
6484 if (R.isValid())
6485 return cxloc::translateSourceRange(getCursorContext(C), R);
6486 }
6487
6488 return clang_getNullRange();
6489}
6490
6491void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006492 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6493 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006494}
6495
6496void clang_executeOnThread(void (*fn)(void*), void *user_data,
6497 unsigned stack_size) {
6498 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6499}
6500
Guy Benyei11169dd2012-12-18 14:30:41 +00006501//===----------------------------------------------------------------------===//
6502// Token-based Operations.
6503//===----------------------------------------------------------------------===//
6504
6505/* CXToken layout:
6506 * int_data[0]: a CXTokenKind
6507 * int_data[1]: starting token location
6508 * int_data[2]: token length
6509 * int_data[3]: reserved
6510 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6511 * otherwise unused.
6512 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006513CXTokenKind clang_getTokenKind(CXToken CXTok) {
6514 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6515}
6516
6517CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6518 switch (clang_getTokenKind(CXTok)) {
6519 case CXToken_Identifier:
6520 case CXToken_Keyword:
6521 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006522 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 ->getNameStart());
6524
6525 case CXToken_Literal: {
6526 // We have stashed the starting pointer in the ptr_data field. Use it.
6527 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006528 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006529 }
6530
6531 case CXToken_Punctuation:
6532 case CXToken_Comment:
6533 break;
6534 }
6535
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006536 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006537 LOG_BAD_TU(TU);
6538 return cxstring::createEmpty();
6539 }
6540
Guy Benyei11169dd2012-12-18 14:30:41 +00006541 // We have to find the starting buffer pointer the hard way, by
6542 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006543 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006544 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006545 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006546
6547 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6548 std::pair<FileID, unsigned> LocInfo
6549 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6550 bool Invalid = false;
6551 StringRef Buffer
6552 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6553 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006554 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006555
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006556 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006557}
6558
6559CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006560 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006561 LOG_BAD_TU(TU);
6562 return clang_getNullLocation();
6563 }
6564
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006565 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006566 if (!CXXUnit)
6567 return clang_getNullLocation();
6568
6569 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6570 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6571}
6572
6573CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006574 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006575 LOG_BAD_TU(TU);
6576 return clang_getNullRange();
6577 }
6578
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006579 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006580 if (!CXXUnit)
6581 return clang_getNullRange();
6582
6583 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6584 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6585}
6586
6587static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6588 SmallVectorImpl<CXToken> &CXTokens) {
6589 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6590 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006591 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006593 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006594
6595 // Cannot tokenize across files.
6596 if (BeginLocInfo.first != EndLocInfo.first)
6597 return;
6598
6599 // Create a lexer
6600 bool Invalid = false;
6601 StringRef Buffer
6602 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6603 if (Invalid)
6604 return;
6605
6606 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6607 CXXUnit->getASTContext().getLangOpts(),
6608 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6609 Lex.SetCommentRetentionState(true);
6610
6611 // Lex tokens until we hit the end of the range.
6612 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6613 Token Tok;
6614 bool previousWasAt = false;
6615 do {
6616 // Lex the next token
6617 Lex.LexFromRawLexer(Tok);
6618 if (Tok.is(tok::eof))
6619 break;
6620
6621 // Initialize the CXToken.
6622 CXToken CXTok;
6623
6624 // - Common fields
6625 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6626 CXTok.int_data[2] = Tok.getLength();
6627 CXTok.int_data[3] = 0;
6628
6629 // - Kind-specific fields
6630 if (Tok.isLiteral()) {
6631 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006632 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006633 } else if (Tok.is(tok::raw_identifier)) {
6634 // Lookup the identifier to determine whether we have a keyword.
6635 IdentifierInfo *II
6636 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6637
6638 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6639 CXTok.int_data[0] = CXToken_Keyword;
6640 }
6641 else {
6642 CXTok.int_data[0] = Tok.is(tok::identifier)
6643 ? CXToken_Identifier
6644 : CXToken_Keyword;
6645 }
6646 CXTok.ptr_data = II;
6647 } else if (Tok.is(tok::comment)) {
6648 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006649 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006650 } else {
6651 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006652 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006653 }
6654 CXTokens.push_back(CXTok);
6655 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006656 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006657}
6658
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006659CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6660 LOG_FUNC_SECTION {
6661 *Log << TU << ' ' << Location;
6662 }
6663
6664 if (isNotUsableTU(TU)) {
6665 LOG_BAD_TU(TU);
6666 return NULL;
6667 }
6668
6669 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6670 if (!CXXUnit)
6671 return NULL;
6672
6673 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6674 if (Begin.isInvalid())
6675 return NULL;
6676 SourceManager &SM = CXXUnit->getSourceManager();
6677 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6678 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6679
6680 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6681
6682 SmallVector<CXToken, 32> CXTokens;
6683 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6684
6685 if (CXTokens.empty())
6686 return NULL;
6687
6688 CXTokens.resize(1);
6689 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6690
6691 memmove(Token, CXTokens.data(), sizeof(CXToken));
6692 return Token;
6693}
6694
Guy Benyei11169dd2012-12-18 14:30:41 +00006695void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6696 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006697 LOG_FUNC_SECTION {
6698 *Log << TU << ' ' << Range;
6699 }
6700
Guy Benyei11169dd2012-12-18 14:30:41 +00006701 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006702 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 if (NumTokens)
6704 *NumTokens = 0;
6705
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006706 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006707 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006708 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006709 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006710
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006711 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006712 if (!CXXUnit || !Tokens || !NumTokens)
6713 return;
6714
6715 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6716
6717 SourceRange R = cxloc::translateCXSourceRange(Range);
6718 if (R.isInvalid())
6719 return;
6720
6721 SmallVector<CXToken, 32> CXTokens;
6722 getTokens(CXXUnit, R, CXTokens);
6723
6724 if (CXTokens.empty())
6725 return;
6726
Serge Pavlov52525732018-02-21 02:02:39 +00006727 *Tokens = static_cast<CXToken *>(
6728 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006729 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6730 *NumTokens = CXTokens.size();
6731}
6732
6733void clang_disposeTokens(CXTranslationUnit TU,
6734 CXToken *Tokens, unsigned NumTokens) {
6735 free(Tokens);
6736}
6737
Guy Benyei11169dd2012-12-18 14:30:41 +00006738//===----------------------------------------------------------------------===//
6739// Token annotation APIs.
6740//===----------------------------------------------------------------------===//
6741
Guy Benyei11169dd2012-12-18 14:30:41 +00006742static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6743 CXCursor parent,
6744 CXClientData client_data);
6745static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6746 CXClientData client_data);
6747
6748namespace {
6749class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 CXToken *Tokens;
6751 CXCursor *Cursors;
6752 unsigned NumTokens;
6753 unsigned TokIdx;
6754 unsigned PreprocessingTokIdx;
6755 CursorVisitor AnnotateVis;
6756 SourceManager &SrcMgr;
6757 bool HasContextSensitiveKeywords;
6758
6759 struct PostChildrenInfo {
6760 CXCursor Cursor;
6761 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006762 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006763 unsigned BeforeChildrenTokenIdx;
6764 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006765 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006766
6767 CXToken &getTok(unsigned Idx) {
6768 assert(Idx < NumTokens);
6769 return Tokens[Idx];
6770 }
6771 const CXToken &getTok(unsigned Idx) const {
6772 assert(Idx < NumTokens);
6773 return Tokens[Idx];
6774 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006775 bool MoreTokens() const { return TokIdx < NumTokens; }
6776 unsigned NextToken() const { return TokIdx; }
6777 void AdvanceToken() { ++TokIdx; }
6778 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006779 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 }
6781 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006782 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006783 }
6784 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006785 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006786 }
6787
6788 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006789 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006790 SourceRange);
6791
6792public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006793 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006794 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006795 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006796 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006797 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006798 AnnotateTokensVisitor, this,
6799 /*VisitPreprocessorLast=*/true,
6800 /*VisitIncludedEntities=*/false,
6801 RegionOfInterest,
6802 /*VisitDeclsOnly=*/false,
6803 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006804 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006805 HasContextSensitiveKeywords(false) { }
6806
6807 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6808 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6809 bool postVisitChildren(CXCursor cursor);
6810 void AnnotateTokens();
6811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006812 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006813 /// context-sensitive keywords.
6814 bool hasContextSensitiveKeywords() const {
6815 return HasContextSensitiveKeywords;
6816 }
6817
6818 ~AnnotateTokensWorker() {
6819 assert(PostChildrenInfos.empty());
6820 }
6821};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006822}
Guy Benyei11169dd2012-12-18 14:30:41 +00006823
6824void AnnotateTokensWorker::AnnotateTokens() {
6825 // Walk the AST within the region of interest, annotating tokens
6826 // along the way.
6827 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006828}
Guy Benyei11169dd2012-12-18 14:30:41 +00006829
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006830static inline void updateCursorAnnotation(CXCursor &Cursor,
6831 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006832 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006833 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006834 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006835}
6836
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006837/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006838//// between the cursor location and the source range is the same as
6839/// \arg compResult.
6840///
6841/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6842/// Pass RangeOverlap to annotate tokens inside a range.
6843void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6844 RangeComparisonResult compResult,
6845 SourceRange range) {
6846 while (MoreTokens()) {
6847 const unsigned I = NextToken();
6848 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006849 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6850 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006851
6852 SourceLocation TokLoc = GetTokenLoc(I);
6853 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006854 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 AdvanceToken();
6856 continue;
6857 }
6858 break;
6859 }
6860}
6861
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006862/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006863/// \returns true if it advanced beyond all macro tokens, false otherwise.
6864bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006865 CXCursor updateC,
6866 RangeComparisonResult compResult,
6867 SourceRange range) {
6868 assert(MoreTokens());
6869 assert(isFunctionMacroToken(NextToken()) &&
6870 "Should be called only for macro arg tokens");
6871
6872 // This works differently than annotateAndAdvanceTokens; because expanded
6873 // macro arguments can have arbitrary translation-unit source order, we do not
6874 // advance the token index one by one until a token fails the range test.
6875 // We only advance once past all of the macro arg tokens if all of them
6876 // pass the range test. If one of them fails we keep the token index pointing
6877 // at the start of the macro arg tokens so that the failing token will be
6878 // annotated by a subsequent annotation try.
6879
6880 bool atLeastOneCompFail = false;
6881
6882 unsigned I = NextToken();
6883 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6884 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6885 if (TokLoc.isFileID())
6886 continue; // not macro arg token, it's parens or comma.
6887 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6888 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6889 Cursors[I] = updateC;
6890 } else
6891 atLeastOneCompFail = true;
6892 }
6893
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006894 if (atLeastOneCompFail)
6895 return false;
6896
6897 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6898 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006899}
6900
6901enum CXChildVisitResult
6902AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006903 SourceRange cursorRange = getRawCursorExtent(cursor);
6904 if (cursorRange.isInvalid())
6905 return CXChildVisit_Recurse;
6906
6907 if (!HasContextSensitiveKeywords) {
6908 // Objective-C properties can have context-sensitive keywords.
6909 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006910 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006911 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6912 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6913 }
6914 // Objective-C methods can have context-sensitive keywords.
6915 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6916 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006917 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006918 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6919 if (Method->getObjCDeclQualifier())
6920 HasContextSensitiveKeywords = true;
6921 else {
David Majnemer59f77922016-06-24 04:05:48 +00006922 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006923 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006924 HasContextSensitiveKeywords = true;
6925 break;
6926 }
6927 }
6928 }
6929 }
6930 }
6931 // C++ methods can have context-sensitive keywords.
6932 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006933 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006934 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6935 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6936 HasContextSensitiveKeywords = true;
6937 }
6938 }
6939 // C++ classes can have context-sensitive keywords.
6940 else if (cursor.kind == CXCursor_StructDecl ||
6941 cursor.kind == CXCursor_ClassDecl ||
6942 cursor.kind == CXCursor_ClassTemplate ||
6943 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006944 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006945 if (D->hasAttr<FinalAttr>())
6946 HasContextSensitiveKeywords = true;
6947 }
6948 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006949
6950 // Don't override a property annotation with its getter/setter method.
6951 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6952 parent.kind == CXCursor_ObjCPropertyDecl)
6953 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006954
6955 if (clang_isPreprocessing(cursor.kind)) {
6956 // Items in the preprocessing record are kept separate from items in
6957 // declarations, so we keep a separate token index.
6958 unsigned SavedTokIdx = TokIdx;
6959 TokIdx = PreprocessingTokIdx;
6960
6961 // Skip tokens up until we catch up to the beginning of the preprocessing
6962 // entry.
6963 while (MoreTokens()) {
6964 const unsigned I = NextToken();
6965 SourceLocation TokLoc = GetTokenLoc(I);
6966 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6967 case RangeBefore:
6968 AdvanceToken();
6969 continue;
6970 case RangeAfter:
6971 case RangeOverlap:
6972 break;
6973 }
6974 break;
6975 }
6976
6977 // Look at all of the tokens within this range.
6978 while (MoreTokens()) {
6979 const unsigned I = NextToken();
6980 SourceLocation TokLoc = GetTokenLoc(I);
6981 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6982 case RangeBefore:
6983 llvm_unreachable("Infeasible");
6984 case RangeAfter:
6985 break;
6986 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006987 // For macro expansions, just note where the beginning of the macro
6988 // expansion occurs.
6989 if (cursor.kind == CXCursor_MacroExpansion) {
6990 if (TokLoc == cursorRange.getBegin())
6991 Cursors[I] = cursor;
6992 AdvanceToken();
6993 break;
6994 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006995 // We may have already annotated macro names inside macro definitions.
6996 if (Cursors[I].kind != CXCursor_MacroExpansion)
6997 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006998 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006999 continue;
7000 }
7001 break;
7002 }
7003
7004 // Save the preprocessing token index; restore the non-preprocessing
7005 // token index.
7006 PreprocessingTokIdx = TokIdx;
7007 TokIdx = SavedTokIdx;
7008 return CXChildVisit_Recurse;
7009 }
7010
7011 if (cursorRange.isInvalid())
7012 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007013
7014 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007015 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007016 const enum CXCursorKind K = clang_getCursorKind(parent);
7017 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007018 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7019 // Attributes are annotated out-of-order, skip tokens until we reach it.
7020 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007021 ? clang_getNullCursor() : parent;
7022
7023 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7024
7025 // Avoid having the cursor of an expression "overwrite" the annotation of the
7026 // variable declaration that it belongs to.
7027 // This can happen for C++ constructor expressions whose range generally
7028 // include the variable declaration, e.g.:
7029 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007030 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007031 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00007032 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007033 const unsigned I = NextToken();
7034 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
7035 E->getLocStart() == D->getLocation() &&
7036 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007037 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007038 AdvanceToken();
7039 }
7040 }
7041 }
7042
7043 // Before recursing into the children keep some state that we are going
7044 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7045 // extra work after the child nodes are visited.
7046 // Note that we don't call VisitChildren here to avoid traversing statements
7047 // code-recursively which can blow the stack.
7048
7049 PostChildrenInfo Info;
7050 Info.Cursor = cursor;
7051 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007052 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007053 Info.BeforeChildrenTokenIdx = NextToken();
7054 PostChildrenInfos.push_back(Info);
7055
7056 return CXChildVisit_Recurse;
7057}
7058
7059bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7060 if (PostChildrenInfos.empty())
7061 return false;
7062 const PostChildrenInfo &Info = PostChildrenInfos.back();
7063 if (!clang_equalCursors(Info.Cursor, cursor))
7064 return false;
7065
7066 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7067 const unsigned AfterChildren = NextToken();
7068 SourceRange cursorRange = Info.CursorRange;
7069
7070 // Scan the tokens that are at the end of the cursor, but are not captured
7071 // but the child cursors.
7072 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7073
7074 // Scan the tokens that are at the beginning of the cursor, but are not
7075 // capture by the child cursors.
7076 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7077 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7078 break;
7079
7080 Cursors[I] = cursor;
7081 }
7082
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007083 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7084 // encountered the attribute cursor.
7085 if (clang_isAttribute(cursor.kind))
7086 TokIdx = Info.BeforeReachingCursorIdx;
7087
Guy Benyei11169dd2012-12-18 14:30:41 +00007088 PostChildrenInfos.pop_back();
7089 return false;
7090}
7091
7092static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7093 CXCursor parent,
7094 CXClientData client_data) {
7095 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7096}
7097
7098static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7099 CXClientData client_data) {
7100 return static_cast<AnnotateTokensWorker*>(client_data)->
7101 postVisitChildren(cursor);
7102}
7103
7104namespace {
7105
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007106/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007107/// and mark tokens that are macro arguments. This info is used by the
7108/// AnnotateTokensWorker.
7109class MarkMacroArgTokensVisitor {
7110 SourceManager &SM;
7111 CXToken *Tokens;
7112 unsigned NumTokens;
7113 unsigned CurIdx;
7114
7115public:
7116 MarkMacroArgTokensVisitor(SourceManager &SM,
7117 CXToken *tokens, unsigned numTokens)
7118 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7119
7120 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7121 if (cursor.kind != CXCursor_MacroExpansion)
7122 return CXChildVisit_Continue;
7123
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007124 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007125 if (macroRange.getBegin() == macroRange.getEnd())
7126 return CXChildVisit_Continue; // it's not a function macro.
7127
7128 for (; CurIdx < NumTokens; ++CurIdx) {
7129 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7130 macroRange.getBegin()))
7131 break;
7132 }
7133
7134 if (CurIdx == NumTokens)
7135 return CXChildVisit_Break;
7136
7137 for (; CurIdx < NumTokens; ++CurIdx) {
7138 SourceLocation tokLoc = getTokenLoc(CurIdx);
7139 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7140 break;
7141
7142 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7143 }
7144
7145 if (CurIdx == NumTokens)
7146 return CXChildVisit_Break;
7147
7148 return CXChildVisit_Continue;
7149 }
7150
7151private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007152 CXToken &getTok(unsigned Idx) {
7153 assert(Idx < NumTokens);
7154 return Tokens[Idx];
7155 }
7156 const CXToken &getTok(unsigned Idx) const {
7157 assert(Idx < NumTokens);
7158 return Tokens[Idx];
7159 }
7160
Guy Benyei11169dd2012-12-18 14:30:41 +00007161 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007162 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 }
7164
7165 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7166 // The third field is reserved and currently not used. Use it here
7167 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007168 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007169 }
7170};
7171
7172} // end anonymous namespace
7173
7174static CXChildVisitResult
7175MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7176 CXClientData client_data) {
7177 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7178 parent);
7179}
7180
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007181/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007182/// \returns true if lexing was finished, false otherwise.
7183static bool lexNext(Lexer &Lex, Token &Tok,
7184 unsigned &NextIdx, unsigned NumTokens) {
7185 if (NextIdx >= NumTokens)
7186 return true;
7187
7188 ++NextIdx;
7189 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007190 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007191}
7192
Guy Benyei11169dd2012-12-18 14:30:41 +00007193static void annotatePreprocessorTokens(CXTranslationUnit TU,
7194 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007195 CXCursor *Cursors,
7196 CXToken *Tokens,
7197 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007198 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007199
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007200 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007201 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7202 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007203 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007204 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007205 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007206
7207 if (BeginLocInfo.first != EndLocInfo.first)
7208 return;
7209
7210 StringRef Buffer;
7211 bool Invalid = false;
7212 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7213 if (Buffer.empty() || Invalid)
7214 return;
7215
7216 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7217 CXXUnit->getASTContext().getLangOpts(),
7218 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7219 Buffer.end());
7220 Lex.SetCommentRetentionState(true);
7221
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007222 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007223 // Lex tokens in raw mode until we hit the end of the range, to avoid
7224 // entering #includes or expanding macros.
7225 while (true) {
7226 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007227 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7228 break;
7229 unsigned TokIdx = NextIdx-1;
7230 assert(Tok.getLocation() ==
7231 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007232
7233 reprocess:
7234 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007235 // We have found a preprocessing directive. Annotate the tokens
7236 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007237 //
7238 // FIXME: Some simple tests here could identify macro definitions and
7239 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007240
7241 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007242 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7243 break;
7244
Craig Topper69186e72014-06-08 08:38:04 +00007245 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007246 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007247 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7248 break;
7249
7250 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007251 IdentifierInfo &II =
7252 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007253 SourceLocation MappedTokLoc =
7254 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7255 MI = getMacroInfo(II, MappedTokLoc, TU);
7256 }
7257 }
7258
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007259 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007261 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7262 finished = true;
7263 break;
7264 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007265 // If we are in a macro definition, check if the token was ever a
7266 // macro name and annotate it if that's the case.
7267 if (MI) {
7268 SourceLocation SaveLoc = Tok.getLocation();
7269 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007270 MacroDefinitionRecord *MacroDef =
7271 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007272 Tok.setLocation(SaveLoc);
7273 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007274 Cursors[NextIdx - 1] =
7275 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007276 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007277 } while (!Tok.isAtStartOfLine());
7278
7279 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7280 assert(TokIdx <= LastIdx);
7281 SourceLocation EndLoc =
7282 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7283 CXCursor Cursor =
7284 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7285
7286 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007287 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007288
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007289 if (finished)
7290 break;
7291 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007292 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007293 }
7294}
7295
7296// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007297static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7298 CXToken *Tokens, unsigned NumTokens,
7299 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007300 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007301 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7302 setThreadBackgroundPriority();
7303
7304 // Determine the region of interest, which contains all of the tokens.
7305 SourceRange RegionOfInterest;
7306 RegionOfInterest.setBegin(
7307 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7308 RegionOfInterest.setEnd(
7309 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7310 Tokens[NumTokens-1])));
7311
Guy Benyei11169dd2012-12-18 14:30:41 +00007312 // Relex the tokens within the source range to look for preprocessing
7313 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007314 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007315
7316 // If begin location points inside a macro argument, set it to the expansion
7317 // location so we can have the full context when annotating semantically.
7318 {
7319 SourceManager &SM = CXXUnit->getSourceManager();
7320 SourceLocation Loc =
7321 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7322 if (Loc.isMacroID())
7323 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7324 }
7325
Guy Benyei11169dd2012-12-18 14:30:41 +00007326 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7327 // Search and mark tokens that are macro argument expansions.
7328 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7329 Tokens, NumTokens);
7330 CursorVisitor MacroArgMarker(TU,
7331 MarkMacroArgTokensVisitorDelegate, &Visitor,
7332 /*VisitPreprocessorLast=*/true,
7333 /*VisitIncludedEntities=*/false,
7334 RegionOfInterest);
7335 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7336 }
7337
7338 // Annotate all of the source locations in the region of interest that map to
7339 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007340 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007341
7342 // FIXME: We use a ridiculous stack size here because the data-recursion
7343 // algorithm uses a large stack frame than the non-data recursive version,
7344 // and AnnotationTokensWorker currently transforms the data-recursion
7345 // algorithm back into a traditional recursion by explicitly calling
7346 // VisitChildren(). We will need to remove this explicit recursive call.
7347 W.AnnotateTokens();
7348
7349 // If we ran into any entities that involve context-sensitive keywords,
7350 // take another pass through the tokens to mark them as such.
7351 if (W.hasContextSensitiveKeywords()) {
7352 for (unsigned I = 0; I != NumTokens; ++I) {
7353 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7354 continue;
7355
7356 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7357 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007358 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007359 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7360 if (Property->getPropertyAttributesAsWritten() != 0 &&
7361 llvm::StringSwitch<bool>(II->getName())
7362 .Case("readonly", true)
7363 .Case("assign", true)
7364 .Case("unsafe_unretained", true)
7365 .Case("readwrite", true)
7366 .Case("retain", true)
7367 .Case("copy", true)
7368 .Case("nonatomic", true)
7369 .Case("atomic", true)
7370 .Case("getter", true)
7371 .Case("setter", true)
7372 .Case("strong", true)
7373 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007374 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007375 .Default(false))
7376 Tokens[I].int_data[0] = CXToken_Keyword;
7377 }
7378 continue;
7379 }
7380
7381 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7382 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7383 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7384 if (llvm::StringSwitch<bool>(II->getName())
7385 .Case("in", true)
7386 .Case("out", true)
7387 .Case("inout", true)
7388 .Case("oneway", true)
7389 .Case("bycopy", true)
7390 .Case("byref", true)
7391 .Default(false))
7392 Tokens[I].int_data[0] = CXToken_Keyword;
7393 continue;
7394 }
7395
7396 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7397 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7398 Tokens[I].int_data[0] = CXToken_Keyword;
7399 continue;
7400 }
7401 }
7402 }
7403}
7404
Guy Benyei11169dd2012-12-18 14:30:41 +00007405void clang_annotateTokens(CXTranslationUnit TU,
7406 CXToken *Tokens, unsigned NumTokens,
7407 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007408 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007409 LOG_BAD_TU(TU);
7410 return;
7411 }
7412 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007413 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007415 }
7416
7417 LOG_FUNC_SECTION {
7418 *Log << TU << ' ';
7419 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7420 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7421 *Log << clang_getRange(bloc, eloc);
7422 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007423
7424 // Any token we don't specifically annotate will have a NULL cursor.
7425 CXCursor C = clang_getNullCursor();
7426 for (unsigned I = 0; I != NumTokens; ++I)
7427 Cursors[I] = C;
7428
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007429 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007430 if (!CXXUnit)
7431 return;
7432
7433 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007434
7435 auto AnnotateTokensImpl = [=]() {
7436 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7437 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007438 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007439 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007440 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7441 }
7442}
7443
Guy Benyei11169dd2012-12-18 14:30:41 +00007444//===----------------------------------------------------------------------===//
7445// Operations for querying linkage of a cursor.
7446//===----------------------------------------------------------------------===//
7447
Guy Benyei11169dd2012-12-18 14:30:41 +00007448CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7449 if (!clang_isDeclaration(cursor.kind))
7450 return CXLinkage_Invalid;
7451
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007452 const Decl *D = cxcursor::getCursorDecl(cursor);
7453 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007454 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007455 case NoLinkage:
7456 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007457 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007458 case InternalLinkage: return CXLinkage_Internal;
7459 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007460 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007461 case ExternalLinkage: return CXLinkage_External;
7462 };
7463
7464 return CXLinkage_Invalid;
7465}
Guy Benyei11169dd2012-12-18 14:30:41 +00007466
7467//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007468// Operations for querying visibility of a cursor.
7469//===----------------------------------------------------------------------===//
7470
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007471CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7472 if (!clang_isDeclaration(cursor.kind))
7473 return CXVisibility_Invalid;
7474
7475 const Decl *D = cxcursor::getCursorDecl(cursor);
7476 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7477 switch (ND->getVisibility()) {
7478 case HiddenVisibility: return CXVisibility_Hidden;
7479 case ProtectedVisibility: return CXVisibility_Protected;
7480 case DefaultVisibility: return CXVisibility_Default;
7481 };
7482
7483 return CXVisibility_Invalid;
7484}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007485
7486//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007487// Operations for querying language of a cursor.
7488//===----------------------------------------------------------------------===//
7489
7490static CXLanguageKind getDeclLanguage(const Decl *D) {
7491 if (!D)
7492 return CXLanguage_C;
7493
7494 switch (D->getKind()) {
7495 default:
7496 break;
7497 case Decl::ImplicitParam:
7498 case Decl::ObjCAtDefsField:
7499 case Decl::ObjCCategory:
7500 case Decl::ObjCCategoryImpl:
7501 case Decl::ObjCCompatibleAlias:
7502 case Decl::ObjCImplementation:
7503 case Decl::ObjCInterface:
7504 case Decl::ObjCIvar:
7505 case Decl::ObjCMethod:
7506 case Decl::ObjCProperty:
7507 case Decl::ObjCPropertyImpl:
7508 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007509 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007510 return CXLanguage_ObjC;
7511 case Decl::CXXConstructor:
7512 case Decl::CXXConversion:
7513 case Decl::CXXDestructor:
7514 case Decl::CXXMethod:
7515 case Decl::CXXRecord:
7516 case Decl::ClassTemplate:
7517 case Decl::ClassTemplatePartialSpecialization:
7518 case Decl::ClassTemplateSpecialization:
7519 case Decl::Friend:
7520 case Decl::FriendTemplate:
7521 case Decl::FunctionTemplate:
7522 case Decl::LinkageSpec:
7523 case Decl::Namespace:
7524 case Decl::NamespaceAlias:
7525 case Decl::NonTypeTemplateParm:
7526 case Decl::StaticAssert:
7527 case Decl::TemplateTemplateParm:
7528 case Decl::TemplateTypeParm:
7529 case Decl::UnresolvedUsingTypename:
7530 case Decl::UnresolvedUsingValue:
7531 case Decl::Using:
7532 case Decl::UsingDirective:
7533 case Decl::UsingShadow:
7534 return CXLanguage_CPlusPlus;
7535 }
7536
7537 return CXLanguage_C;
7538}
7539
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007540static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7541 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007542 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007543
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007544 switch (D->getAvailability()) {
7545 case AR_Available:
7546 case AR_NotYetIntroduced:
7547 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007548 return getCursorAvailabilityForDecl(
7549 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007550 return CXAvailability_Available;
7551
7552 case AR_Deprecated:
7553 return CXAvailability_Deprecated;
7554
7555 case AR_Unavailable:
7556 return CXAvailability_NotAvailable;
7557 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007558
7559 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007560}
7561
Guy Benyei11169dd2012-12-18 14:30:41 +00007562enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7563 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007564 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7565 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007566
7567 return CXAvailability_Available;
7568}
7569
7570static CXVersion convertVersion(VersionTuple In) {
7571 CXVersion Out = { -1, -1, -1 };
7572 if (In.empty())
7573 return Out;
7574
7575 Out.Major = In.getMajor();
7576
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007577 Optional<unsigned> Minor = In.getMinor();
7578 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007579 Out.Minor = *Minor;
7580 else
7581 return Out;
7582
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007583 Optional<unsigned> Subminor = In.getSubminor();
7584 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007585 Out.Subminor = *Subminor;
7586
7587 return Out;
7588}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007589
Alex Lorenz1345ea22017-06-12 19:06:30 +00007590static void getCursorPlatformAvailabilityForDecl(
7591 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7592 int *always_unavailable, CXString *unavailable_message,
7593 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007594 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007595 for (auto A : D->attrs()) {
7596 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007597 HadAvailAttr = true;
7598 if (always_deprecated)
7599 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007600 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007601 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007602 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007603 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007604 continue;
7605 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007606
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007607 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007608 HadAvailAttr = true;
7609 if (always_unavailable)
7610 *always_unavailable = 1;
7611 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007612 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007613 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7614 }
7615 continue;
7616 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007617
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007618 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007619 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007620 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007621 }
7622 }
7623
7624 if (!HadAvailAttr)
7625 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7626 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007627 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7628 deprecated_message, always_unavailable, unavailable_message,
7629 AvailabilityAttrs);
7630
7631 if (AvailabilityAttrs.empty())
7632 return;
7633
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007634 llvm::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7635 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7636 return LHS->getPlatform()->getName() <
7637 RHS->getPlatform()->getName();
Alex Lorenz1345ea22017-06-12 19:06:30 +00007638 });
7639 ASTContext &Ctx = D->getASTContext();
7640 auto It = std::unique(
7641 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7642 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7643 if (LHS->getPlatform() != RHS->getPlatform())
7644 return false;
7645
7646 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7647 LHS->getDeprecated() == RHS->getDeprecated() &&
7648 LHS->getObsoleted() == RHS->getObsoleted() &&
7649 LHS->getMessage() == RHS->getMessage() &&
7650 LHS->getReplacement() == RHS->getReplacement())
7651 return true;
7652
7653 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7654 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7655 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7656 return false;
7657
7658 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7659 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7660
7661 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7662 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7663 if (LHS->getMessage().empty())
7664 LHS->setMessage(Ctx, RHS->getMessage());
7665 if (LHS->getReplacement().empty())
7666 LHS->setReplacement(Ctx, RHS->getReplacement());
7667 }
7668
7669 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7670 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7671 if (LHS->getMessage().empty())
7672 LHS->setMessage(Ctx, RHS->getMessage());
7673 if (LHS->getReplacement().empty())
7674 LHS->setReplacement(Ctx, RHS->getReplacement());
7675 }
7676
7677 return true;
7678 });
7679 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007680}
7681
Alex Lorenz1345ea22017-06-12 19:06:30 +00007682int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007683 CXString *deprecated_message,
7684 int *always_unavailable,
7685 CXString *unavailable_message,
7686 CXPlatformAvailability *availability,
7687 int availability_size) {
7688 if (always_deprecated)
7689 *always_deprecated = 0;
7690 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007691 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007692 if (always_unavailable)
7693 *always_unavailable = 0;
7694 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007695 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007696
Guy Benyei11169dd2012-12-18 14:30:41 +00007697 if (!clang_isDeclaration(cursor.kind))
7698 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007699
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007700 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007701 if (!D)
7702 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007703
Alex Lorenz1345ea22017-06-12 19:06:30 +00007704 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7705 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7706 always_unavailable, unavailable_message,
7707 AvailabilityAttrs);
7708 for (const auto &Avail :
7709 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7710 .take_front(availability_size))) {
7711 availability[Avail.index()].Platform =
7712 cxstring::createDup(Avail.value()->getPlatform()->getName());
7713 availability[Avail.index()].Introduced =
7714 convertVersion(Avail.value()->getIntroduced());
7715 availability[Avail.index()].Deprecated =
7716 convertVersion(Avail.value()->getDeprecated());
7717 availability[Avail.index()].Obsoleted =
7718 convertVersion(Avail.value()->getObsoleted());
7719 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7720 availability[Avail.index()].Message =
7721 cxstring::createDup(Avail.value()->getMessage());
7722 }
7723
7724 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007725}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007726
Guy Benyei11169dd2012-12-18 14:30:41 +00007727void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7728 clang_disposeString(availability->Platform);
7729 clang_disposeString(availability->Message);
7730}
7731
7732CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7733 if (clang_isDeclaration(cursor.kind))
7734 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7735
7736 return CXLanguage_Invalid;
7737}
7738
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007739CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7740 const Decl *D = cxcursor::getCursorDecl(cursor);
7741 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7742 switch (VD->getTLSKind()) {
7743 case VarDecl::TLS_None:
7744 return CXTLS_None;
7745 case VarDecl::TLS_Dynamic:
7746 return CXTLS_Dynamic;
7747 case VarDecl::TLS_Static:
7748 return CXTLS_Static;
7749 }
7750 }
7751
7752 return CXTLS_None;
7753}
7754
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007755 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007756 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007758static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007759 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007760 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007761
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007762 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007763 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7764 return FunTmpl;
7765
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007766 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007767 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7768 return ClassTmpl;
7769
7770 return D;
7771}
7772
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007773
7774enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7775 StorageClass sc = SC_None;
7776 const Decl *D = getCursorDecl(C);
7777 if (D) {
7778 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7779 sc = FD->getStorageClass();
7780 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7781 sc = VD->getStorageClass();
7782 } else {
7783 return CX_SC_Invalid;
7784 }
7785 } else {
7786 return CX_SC_Invalid;
7787 }
7788 switch (sc) {
7789 case SC_None:
7790 return CX_SC_None;
7791 case SC_Extern:
7792 return CX_SC_Extern;
7793 case SC_Static:
7794 return CX_SC_Static;
7795 case SC_PrivateExtern:
7796 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007797 case SC_Auto:
7798 return CX_SC_Auto;
7799 case SC_Register:
7800 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007801 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007802 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007803}
7804
Guy Benyei11169dd2012-12-18 14:30:41 +00007805CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7806 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007807 if (const Decl *D = getCursorDecl(cursor)) {
7808 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007809 if (!DC)
7810 return clang_getNullCursor();
7811
7812 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7813 getCursorTU(cursor));
7814 }
7815 }
7816
7817 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007818 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007819 return MakeCXCursor(D, getCursorTU(cursor));
7820 }
7821
7822 return clang_getNullCursor();
7823}
7824
7825CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7826 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007827 if (const Decl *D = getCursorDecl(cursor)) {
7828 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007829 if (!DC)
7830 return clang_getNullCursor();
7831
7832 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7833 getCursorTU(cursor));
7834 }
7835 }
7836
7837 // FIXME: Note that we can't easily compute the lexical context of a
7838 // statement or expression, so we return nothing.
7839 return clang_getNullCursor();
7840}
7841
7842CXFile clang_getIncludedFile(CXCursor cursor) {
7843 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007844 return nullptr;
7845
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007846 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007847 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007848}
7849
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007850unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7851 if (C.kind != CXCursor_ObjCPropertyDecl)
7852 return CXObjCPropertyAttr_noattr;
7853
7854 unsigned Result = CXObjCPropertyAttr_noattr;
7855 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7856 ObjCPropertyDecl::PropertyAttributeKind Attr =
7857 PD->getPropertyAttributesAsWritten();
7858
7859#define SET_CXOBJCPROP_ATTR(A) \
7860 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7861 Result |= CXObjCPropertyAttr_##A
7862 SET_CXOBJCPROP_ATTR(readonly);
7863 SET_CXOBJCPROP_ATTR(getter);
7864 SET_CXOBJCPROP_ATTR(assign);
7865 SET_CXOBJCPROP_ATTR(readwrite);
7866 SET_CXOBJCPROP_ATTR(retain);
7867 SET_CXOBJCPROP_ATTR(copy);
7868 SET_CXOBJCPROP_ATTR(nonatomic);
7869 SET_CXOBJCPROP_ATTR(setter);
7870 SET_CXOBJCPROP_ATTR(atomic);
7871 SET_CXOBJCPROP_ATTR(weak);
7872 SET_CXOBJCPROP_ATTR(strong);
7873 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007874 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007875#undef SET_CXOBJCPROP_ATTR
7876
7877 return Result;
7878}
7879
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007880unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7881 if (!clang_isDeclaration(C.kind))
7882 return CXObjCDeclQualifier_None;
7883
7884 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7885 const Decl *D = getCursorDecl(C);
7886 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7887 QT = MD->getObjCDeclQualifier();
7888 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7889 QT = PD->getObjCDeclQualifier();
7890 if (QT == Decl::OBJC_TQ_None)
7891 return CXObjCDeclQualifier_None;
7892
7893 unsigned Result = CXObjCDeclQualifier_None;
7894 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7895 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7896 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7897 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7898 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7899 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7900
7901 return Result;
7902}
7903
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007904unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7905 if (!clang_isDeclaration(C.kind))
7906 return 0;
7907
7908 const Decl *D = getCursorDecl(C);
7909 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7910 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7911 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7912 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7913
7914 return 0;
7915}
7916
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007917unsigned clang_Cursor_isVariadic(CXCursor C) {
7918 if (!clang_isDeclaration(C.kind))
7919 return 0;
7920
7921 const Decl *D = getCursorDecl(C);
7922 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7923 return FD->isVariadic();
7924 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7925 return MD->isVariadic();
7926
7927 return 0;
7928}
7929
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007930unsigned clang_Cursor_isExternalSymbol(CXCursor C,
7931 CXString *language, CXString *definedIn,
7932 unsigned *isGenerated) {
7933 if (!clang_isDeclaration(C.kind))
7934 return 0;
7935
7936 const Decl *D = getCursorDecl(C);
7937
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00007938 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007939 if (language)
7940 *language = cxstring::createDup(attr->getLanguage());
7941 if (definedIn)
7942 *definedIn = cxstring::createDup(attr->getDefinedIn());
7943 if (isGenerated)
7944 *isGenerated = attr->getGeneratedDeclaration();
7945 return 1;
7946 }
7947 return 0;
7948}
7949
Guy Benyei11169dd2012-12-18 14:30:41 +00007950CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7951 if (!clang_isDeclaration(C.kind))
7952 return clang_getNullRange();
7953
7954 const Decl *D = getCursorDecl(C);
7955 ASTContext &Context = getCursorContext(C);
7956 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7957 if (!RC)
7958 return clang_getNullRange();
7959
7960 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7961}
7962
7963CXString clang_Cursor_getRawCommentText(CXCursor C) {
7964 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007965 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007966
7967 const Decl *D = getCursorDecl(C);
7968 ASTContext &Context = getCursorContext(C);
7969 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7970 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7971 StringRef();
7972
7973 // Don't duplicate the string because RawText points directly into source
7974 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007975 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007976}
7977
7978CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7979 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007980 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007981
7982 const Decl *D = getCursorDecl(C);
7983 const ASTContext &Context = getCursorContext(C);
7984 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7985
7986 if (RC) {
7987 StringRef BriefText = RC->getBriefText(Context);
7988
7989 // Don't duplicate the string because RawComment ensures that this memory
7990 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007991 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007992 }
7993
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007994 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007995}
7996
Guy Benyei11169dd2012-12-18 14:30:41 +00007997CXModule clang_Cursor_getModule(CXCursor C) {
7998 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007999 if (const ImportDecl *ImportD =
8000 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 return ImportD->getImportedModule();
8002 }
8003
Craig Topper69186e72014-06-08 08:38:04 +00008004 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008005}
8006
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008007CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8008 if (isNotUsableTU(TU)) {
8009 LOG_BAD_TU(TU);
8010 return nullptr;
8011 }
8012 if (!File)
8013 return nullptr;
8014 FileEntry *FE = static_cast<FileEntry *>(File);
8015
8016 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8017 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8018 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8019
Richard Smithfeb54b62014-10-23 02:01:19 +00008020 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008021}
8022
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008023CXFile clang_Module_getASTFile(CXModule CXMod) {
8024 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008025 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008026 Module *Mod = static_cast<Module*>(CXMod);
8027 return const_cast<FileEntry *>(Mod->getASTFile());
8028}
8029
Guy Benyei11169dd2012-12-18 14:30:41 +00008030CXModule clang_Module_getParent(CXModule CXMod) {
8031 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008032 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008033 Module *Mod = static_cast<Module*>(CXMod);
8034 return Mod->Parent;
8035}
8036
8037CXString clang_Module_getName(CXModule CXMod) {
8038 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008039 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008040 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008041 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008042}
8043
8044CXString clang_Module_getFullName(CXModule CXMod) {
8045 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008046 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008047 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008048 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008049}
8050
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008051int clang_Module_isSystem(CXModule CXMod) {
8052 if (!CXMod)
8053 return 0;
8054 Module *Mod = static_cast<Module*>(CXMod);
8055 return Mod->IsSystem;
8056}
8057
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008058unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8059 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008060 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008061 LOG_BAD_TU(TU);
8062 return 0;
8063 }
8064 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008065 return 0;
8066 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008067 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8068 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8069 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008070}
8071
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008072CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8073 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008074 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008075 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008076 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008077 }
8078 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008079 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008080 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008081 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008082
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008083 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8084 if (Index < TopHeaders.size())
8085 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008086
Craig Topper69186e72014-06-08 08:38:04 +00008087 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008088}
8089
Guy Benyei11169dd2012-12-18 14:30:41 +00008090//===----------------------------------------------------------------------===//
8091// C++ AST instrospection.
8092//===----------------------------------------------------------------------===//
8093
Jonathan Coe29565352016-04-27 12:48:25 +00008094unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8095 if (!clang_isDeclaration(C.kind))
8096 return 0;
8097
8098 const Decl *D = cxcursor::getCursorDecl(C);
8099 const CXXConstructorDecl *Constructor =
8100 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8101 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8102}
8103
8104unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8105 if (!clang_isDeclaration(C.kind))
8106 return 0;
8107
8108 const Decl *D = cxcursor::getCursorDecl(C);
8109 const CXXConstructorDecl *Constructor =
8110 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8111 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8112}
8113
8114unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8115 if (!clang_isDeclaration(C.kind))
8116 return 0;
8117
8118 const Decl *D = cxcursor::getCursorDecl(C);
8119 const CXXConstructorDecl *Constructor =
8120 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8121 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8122}
8123
8124unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8125 if (!clang_isDeclaration(C.kind))
8126 return 0;
8127
8128 const Decl *D = cxcursor::getCursorDecl(C);
8129 const CXXConstructorDecl *Constructor =
8130 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8131 // Passing 'false' excludes constructors marked 'explicit'.
8132 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8133}
8134
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008135unsigned clang_CXXField_isMutable(CXCursor C) {
8136 if (!clang_isDeclaration(C.kind))
8137 return 0;
8138
8139 if (const auto D = cxcursor::getCursorDecl(C))
8140 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8141 return FD->isMutable() ? 1 : 0;
8142 return 0;
8143}
8144
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008145unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8146 if (!clang_isDeclaration(C.kind))
8147 return 0;
8148
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008149 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008150 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008151 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008152 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8153}
8154
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008155unsigned clang_CXXMethod_isConst(CXCursor C) {
8156 if (!clang_isDeclaration(C.kind))
8157 return 0;
8158
8159 const Decl *D = cxcursor::getCursorDecl(C);
8160 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008161 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008162 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
8163}
8164
Jonathan Coe29565352016-04-27 12:48:25 +00008165unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8166 if (!clang_isDeclaration(C.kind))
8167 return 0;
8168
8169 const Decl *D = cxcursor::getCursorDecl(C);
8170 const CXXMethodDecl *Method =
8171 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8172 return (Method && Method->isDefaulted()) ? 1 : 0;
8173}
8174
Guy Benyei11169dd2012-12-18 14:30:41 +00008175unsigned clang_CXXMethod_isStatic(CXCursor C) {
8176 if (!clang_isDeclaration(C.kind))
8177 return 0;
8178
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008179 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008180 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008181 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 return (Method && Method->isStatic()) ? 1 : 0;
8183}
8184
8185unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8186 if (!clang_isDeclaration(C.kind))
8187 return 0;
8188
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008189 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008190 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008191 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008192 return (Method && Method->isVirtual()) ? 1 : 0;
8193}
Guy Benyei11169dd2012-12-18 14:30:41 +00008194
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008195unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8196 if (!clang_isDeclaration(C.kind))
8197 return 0;
8198
8199 const auto *D = cxcursor::getCursorDecl(C);
8200 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8201 if (RD)
8202 RD = RD->getDefinition();
8203 return (RD && RD->isAbstract()) ? 1 : 0;
8204}
8205
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008206unsigned clang_EnumDecl_isScoped(CXCursor C) {
8207 if (!clang_isDeclaration(C.kind))
8208 return 0;
8209
8210 const Decl *D = cxcursor::getCursorDecl(C);
8211 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8212 return (Enum && Enum->isScoped()) ? 1 : 0;
8213}
8214
Guy Benyei11169dd2012-12-18 14:30:41 +00008215//===----------------------------------------------------------------------===//
8216// Attribute introspection.
8217//===----------------------------------------------------------------------===//
8218
Guy Benyei11169dd2012-12-18 14:30:41 +00008219CXType clang_getIBOutletCollectionType(CXCursor C) {
8220 if (C.kind != CXCursor_IBOutletCollectionAttr)
8221 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8222
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008223 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008224 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8225
8226 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8227}
Guy Benyei11169dd2012-12-18 14:30:41 +00008228
8229//===----------------------------------------------------------------------===//
8230// Inspecting memory usage.
8231//===----------------------------------------------------------------------===//
8232
8233typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8234
8235static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8236 enum CXTUResourceUsageKind k,
8237 unsigned long amount) {
8238 CXTUResourceUsageEntry entry = { k, amount };
8239 entries.push_back(entry);
8240}
8241
Guy Benyei11169dd2012-12-18 14:30:41 +00008242const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8243 const char *str = "";
8244 switch (kind) {
8245 case CXTUResourceUsage_AST:
8246 str = "ASTContext: expressions, declarations, and types";
8247 break;
8248 case CXTUResourceUsage_Identifiers:
8249 str = "ASTContext: identifiers";
8250 break;
8251 case CXTUResourceUsage_Selectors:
8252 str = "ASTContext: selectors";
8253 break;
8254 case CXTUResourceUsage_GlobalCompletionResults:
8255 str = "Code completion: cached global results";
8256 break;
8257 case CXTUResourceUsage_SourceManagerContentCache:
8258 str = "SourceManager: content cache allocator";
8259 break;
8260 case CXTUResourceUsage_AST_SideTables:
8261 str = "ASTContext: side tables";
8262 break;
8263 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8264 str = "SourceManager: malloc'ed memory buffers";
8265 break;
8266 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8267 str = "SourceManager: mmap'ed memory buffers";
8268 break;
8269 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8270 str = "ExternalASTSource: malloc'ed memory buffers";
8271 break;
8272 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8273 str = "ExternalASTSource: mmap'ed memory buffers";
8274 break;
8275 case CXTUResourceUsage_Preprocessor:
8276 str = "Preprocessor: malloc'ed memory";
8277 break;
8278 case CXTUResourceUsage_PreprocessingRecord:
8279 str = "Preprocessor: PreprocessingRecord";
8280 break;
8281 case CXTUResourceUsage_SourceManager_DataStructures:
8282 str = "SourceManager: data structures and tables";
8283 break;
8284 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8285 str = "Preprocessor: header search tables";
8286 break;
8287 }
8288 return str;
8289}
8290
8291CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008292 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008293 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008294 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008295 return usage;
8296 }
8297
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008298 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008299 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 ASTContext &astContext = astUnit->getASTContext();
8301
8302 // How much memory is used by AST nodes and types?
8303 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8304 (unsigned long) astContext.getASTAllocatedMemory());
8305
8306 // How much memory is used by identifiers?
8307 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8308 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8309
8310 // How much memory is used for selectors?
8311 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8312 (unsigned long) astContext.Selectors.getTotalMemory());
8313
8314 // How much memory is used by ASTContext's side tables?
8315 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8316 (unsigned long) astContext.getSideTableAllocatedMemory());
8317
8318 // How much memory is used for caching global code completion results?
8319 unsigned long completionBytes = 0;
8320 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008321 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008322 completionBytes = completionAllocator->getTotalMemory();
8323 }
8324 createCXTUResourceUsageEntry(*entries,
8325 CXTUResourceUsage_GlobalCompletionResults,
8326 completionBytes);
8327
8328 // How much memory is being used by SourceManager's content cache?
8329 createCXTUResourceUsageEntry(*entries,
8330 CXTUResourceUsage_SourceManagerContentCache,
8331 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8332
8333 // How much memory is being used by the MemoryBuffer's in SourceManager?
8334 const SourceManager::MemoryBufferSizes &srcBufs =
8335 astUnit->getSourceManager().getMemoryBufferSizes();
8336
8337 createCXTUResourceUsageEntry(*entries,
8338 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8339 (unsigned long) srcBufs.malloc_bytes);
8340 createCXTUResourceUsageEntry(*entries,
8341 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8342 (unsigned long) srcBufs.mmap_bytes);
8343 createCXTUResourceUsageEntry(*entries,
8344 CXTUResourceUsage_SourceManager_DataStructures,
8345 (unsigned long) astContext.getSourceManager()
8346 .getDataStructureSizes());
8347
8348 // How much memory is being used by the ExternalASTSource?
8349 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8350 const ExternalASTSource::MemoryBufferSizes &sizes =
8351 esrc->getMemoryBufferSizes();
8352
8353 createCXTUResourceUsageEntry(*entries,
8354 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8355 (unsigned long) sizes.malloc_bytes);
8356 createCXTUResourceUsageEntry(*entries,
8357 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8358 (unsigned long) sizes.mmap_bytes);
8359 }
8360
8361 // How much memory is being used by the Preprocessor?
8362 Preprocessor &pp = astUnit->getPreprocessor();
8363 createCXTUResourceUsageEntry(*entries,
8364 CXTUResourceUsage_Preprocessor,
8365 pp.getTotalMemory());
8366
8367 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8368 createCXTUResourceUsageEntry(*entries,
8369 CXTUResourceUsage_PreprocessingRecord,
8370 pRec->getTotalMemory());
8371 }
8372
8373 createCXTUResourceUsageEntry(*entries,
8374 CXTUResourceUsage_Preprocessor_HeaderSearch,
8375 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008376
Guy Benyei11169dd2012-12-18 14:30:41 +00008377 CXTUResourceUsage usage = { (void*) entries.get(),
8378 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008379 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008380 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008381 return usage;
8382}
8383
8384void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8385 if (usage.data)
8386 delete (MemUsageEntries*) usage.data;
8387}
8388
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008389CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8390 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008391 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008392 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008393
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008394 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008395 LOG_BAD_TU(TU);
8396 return skipped;
8397 }
8398
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008399 if (!file)
8400 return skipped;
8401
8402 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8403 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8404 if (!ppRec)
8405 return skipped;
8406
8407 ASTContext &Ctx = astUnit->getASTContext();
8408 SourceManager &sm = Ctx.getSourceManager();
8409 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8410 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008411 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008412
8413 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8414 std::vector<SourceRange> wantedRanges;
8415 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8416 i != ei; ++i) {
8417 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8418 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008419 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8420 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008421 }
8422
8423 skipped->count = wantedRanges.size();
8424 skipped->ranges = new CXSourceRange[skipped->count];
8425 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8426 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8427
8428 return skipped;
8429}
8430
Cameron Desrochersd8091282016-08-18 15:43:55 +00008431CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8432 CXSourceRangeList *skipped = new CXSourceRangeList;
8433 skipped->count = 0;
8434 skipped->ranges = nullptr;
8435
8436 if (isNotUsableTU(TU)) {
8437 LOG_BAD_TU(TU);
8438 return skipped;
8439 }
8440
8441 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8442 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8443 if (!ppRec)
8444 return skipped;
8445
8446 ASTContext &Ctx = astUnit->getASTContext();
8447
8448 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8449
8450 skipped->count = SkippedRanges.size();
8451 skipped->ranges = new CXSourceRange[skipped->count];
8452 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8453 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8454
8455 return skipped;
8456}
8457
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008458void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8459 if (ranges) {
8460 delete[] ranges->ranges;
8461 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008462 }
8463}
8464
Guy Benyei11169dd2012-12-18 14:30:41 +00008465void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8466 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8467 for (unsigned I = 0; I != Usage.numEntries; ++I)
8468 fprintf(stderr, " %s: %lu\n",
8469 clang_getTUResourceUsageName(Usage.entries[I].kind),
8470 Usage.entries[I].amount);
8471
8472 clang_disposeCXTUResourceUsage(Usage);
8473}
8474
8475//===----------------------------------------------------------------------===//
8476// Misc. utility functions.
8477//===----------------------------------------------------------------------===//
8478
Richard Smith0a7b2972018-07-03 21:34:13 +00008479/// Default to using our desired 8 MB stack size on "safety" threads.
8480static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008481
8482namespace clang {
8483
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008484bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008485 unsigned Size) {
8486 if (!Size)
8487 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008488 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008489 return CRC.RunSafelyOnThread(Fn, Size);
8490 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008491}
8492
8493unsigned GetSafetyThreadStackSize() {
8494 return SafetyStackThreadSize;
8495}
8496
8497void SetSafetyThreadStackSize(unsigned Value) {
8498 SafetyStackThreadSize = Value;
8499}
8500
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008501}
Guy Benyei11169dd2012-12-18 14:30:41 +00008502
8503void clang::setThreadBackgroundPriority() {
8504 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8505 return;
8506
Alp Toker1a86ad22014-07-06 06:24:00 +00008507#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008508 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8509#endif
8510}
8511
8512void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8513 if (!Unit)
8514 return;
8515
8516 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8517 DEnd = Unit->stored_diag_end();
8518 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008519 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008520 CXString Msg = clang_formatDiagnostic(&Diag,
8521 clang_defaultDiagnosticDisplayOptions());
8522 fprintf(stderr, "%s\n", clang_getCString(Msg));
8523 clang_disposeString(Msg);
8524 }
Nico Weber1865df42018-04-27 19:11:14 +00008525#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008526 // On Windows, force a flush, since there may be multiple copies of
8527 // stderr and stdout in the file system, all with different buffers
8528 // but writing to the same device.
8529 fflush(stderr);
8530#endif
8531}
8532
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008533MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8534 SourceLocation MacroDefLoc,
8535 CXTranslationUnit TU){
8536 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008537 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008538 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008539 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008540
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008541 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008542 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008543 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008544 if (MD) {
8545 for (MacroDirective::DefInfo
8546 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8547 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8548 return Def.getMacroInfo();
8549 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008550 }
8551
Craig Topper69186e72014-06-08 08:38:04 +00008552 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008553}
8554
Richard Smith66a81862015-05-04 02:25:31 +00008555const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008556 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008557 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008558 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008559 const IdentifierInfo *II = MacroDef->getName();
8560 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008561 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008562
8563 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8564}
8565
Richard Smith66a81862015-05-04 02:25:31 +00008566MacroDefinitionRecord *
8567cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8568 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008569 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008570 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008571 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008572 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008573
8574 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008575 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008576 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8577 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008578 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008579
8580 // Check that the token is inside the definition and not its argument list.
8581 SourceManager &SM = Unit->getSourceManager();
8582 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008583 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008584 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008585 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008586
8587 Preprocessor &PP = Unit->getPreprocessor();
8588 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8589 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008590 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008591
Alp Toker2d57cea2014-05-17 04:53:25 +00008592 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008593 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008594 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008595
8596 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008597 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008598 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008599
Richard Smith20e883e2015-04-29 23:20:19 +00008600 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008601 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008602 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008603
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008604 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008605}
8606
Richard Smith66a81862015-05-04 02:25:31 +00008607MacroDefinitionRecord *
8608cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8609 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008610 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008611 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008612
8613 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008614 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008615 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008616 Preprocessor &PP = Unit->getPreprocessor();
8617 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008618 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008619 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8620 Token Tok;
8621 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008622 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008623
8624 return checkForMacroInMacroDefinition(MI, Tok, TU);
8625}
8626
Guy Benyei11169dd2012-12-18 14:30:41 +00008627CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008628 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008629}
8630
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008631Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8632 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008633 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008634 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008635 if (Unit->isMainFileAST())
8636 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008637 return *this;
8638 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008639 } else {
8640 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008641 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008642 return *this;
8643}
8644
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008645Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8646 *this << FE->getName();
8647 return *this;
8648}
8649
8650Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8651 CXString cursorName = clang_getCursorDisplayName(cursor);
8652 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8653 clang_disposeString(cursorName);
8654 return *this;
8655}
8656
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008657Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8658 CXFile File;
8659 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008660 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008661 CXString FileName = clang_getFileName(File);
8662 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8663 clang_disposeString(FileName);
8664 return *this;
8665}
8666
8667Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8668 CXSourceLocation BLoc = clang_getRangeStart(range);
8669 CXSourceLocation ELoc = clang_getRangeEnd(range);
8670
8671 CXFile BFile;
8672 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008673 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008674
8675 CXFile EFile;
8676 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008677 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008678
8679 CXString BFileName = clang_getFileName(BFile);
8680 if (BFile == EFile) {
8681 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8682 BLine, BColumn, ELine, EColumn);
8683 } else {
8684 CXString EFileName = clang_getFileName(EFile);
8685 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8686 BLine, BColumn)
8687 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8688 ELine, EColumn);
8689 clang_disposeString(EFileName);
8690 }
8691 clang_disposeString(BFileName);
8692 return *this;
8693}
8694
8695Logger &cxindex::Logger::operator<<(CXString Str) {
8696 *this << clang_getCString(Str);
8697 return *this;
8698}
8699
8700Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8701 LogOS << Fmt;
8702 return *this;
8703}
8704
Chandler Carruth37ad2582014-06-27 15:14:39 +00008705static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8706
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008707cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008708 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008709
8710 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8711
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008712 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008713 OS << "[libclang:" << Name << ':';
8714
Alp Toker1a86ad22014-07-06 06:24:00 +00008715#ifdef USE_DARWIN_THREADS
8716 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008717 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8718 OS << tid << ':';
8719#endif
8720
8721 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8722 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008723 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008724
8725 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008726 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008727 OS << "--------------------------------------------------\n";
8728 }
8729}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008730
8731#ifdef CLANG_TOOL_EXTRA_BUILD
8732// This anchor is used to force the linker to link the clang-tidy plugin.
8733extern volatile int ClangTidyPluginAnchorSource;
8734static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8735 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008736
8737// This anchor is used to force the linker to link the clang-include-fixer
8738// plugin.
8739extern volatile int ClangIncludeFixerPluginAnchorSource;
8740static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8741 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008742#endif