blob: b61dff3238096edde8e9db26376237ce6bde9298 [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)
Guy Benyei11169dd2012-12-18 14:30:41 +00001775DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1776DEFAULT_TYPELOC_IMPL(Vector, Type)
1777DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1778DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1779DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1780DEFAULT_TYPELOC_IMPL(Record, TagType)
1781DEFAULT_TYPELOC_IMPL(Enum, TagType)
1782DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1783DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1784DEFAULT_TYPELOC_IMPL(Auto, Type)
1785
1786bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1787 // Visit the nested-name-specifier, if present.
1788 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1789 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1790 return true;
1791
1792 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001793 for (const auto &I : D->bases()) {
1794 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001795 return true;
1796 }
1797 }
1798
1799 return VisitTagDecl(D);
1800}
1801
1802bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001803 for (const auto *I : D->attrs())
Erik Verbruggenc068e902018-04-24 08:39:46 +00001804 if (!I->isImplicit() && Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001805 return true;
1806
1807 return false;
1808}
1809
1810//===----------------------------------------------------------------------===//
1811// Data-recursive visitor methods.
1812//===----------------------------------------------------------------------===//
1813
1814namespace {
1815#define DEF_JOB(NAME, DATA, KIND)\
1816class NAME : public VisitorJob {\
1817public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001818 NAME(const DATA *d, CXCursor parent) : \
1819 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001820 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001821 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001822};
1823
1824DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1825DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1826DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1827DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001828DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1829DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1830DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1831#undef DEF_JOB
1832
James Y Knight04ec5bf2015-12-24 02:59:37 +00001833class ExplicitTemplateArgsVisit : public VisitorJob {
1834public:
1835 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1836 const TemplateArgumentLoc *End, CXCursor parent)
1837 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1838 End) {}
1839 static bool classof(const VisitorJob *VJ) {
1840 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1841 }
1842 const TemplateArgumentLoc *begin() const {
1843 return static_cast<const TemplateArgumentLoc *>(data[0]);
1844 }
1845 const TemplateArgumentLoc *end() {
1846 return static_cast<const TemplateArgumentLoc *>(data[1]);
1847 }
1848};
Guy Benyei11169dd2012-12-18 14:30:41 +00001849class DeclVisit : public VisitorJob {
1850public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001851 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001852 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001853 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001854 static bool classof(const VisitorJob *VJ) {
1855 return VJ->getKind() == DeclVisitKind;
1856 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001857 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001858 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001859};
1860class TypeLocVisit : public VisitorJob {
1861public:
1862 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1863 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1864 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1865
1866 static bool classof(const VisitorJob *VJ) {
1867 return VJ->getKind() == TypeLocVisitKind;
1868 }
1869
1870 TypeLoc get() const {
1871 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001872 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001873 }
1874};
1875
1876class LabelRefVisit : public VisitorJob {
1877public:
1878 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1879 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1880 labelLoc.getPtrEncoding()) {}
1881
1882 static bool classof(const VisitorJob *VJ) {
1883 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1884 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001885 const LabelDecl *get() const {
1886 return static_cast<const LabelDecl *>(data[0]);
1887 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001888 SourceLocation getLoc() const {
1889 return SourceLocation::getFromPtrEncoding(data[1]); }
1890};
1891
1892class NestedNameSpecifierLocVisit : public VisitorJob {
1893public:
1894 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1895 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1896 Qualifier.getNestedNameSpecifier(),
1897 Qualifier.getOpaqueData()) { }
1898
1899 static bool classof(const VisitorJob *VJ) {
1900 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1901 }
1902
1903 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001904 return NestedNameSpecifierLoc(
1905 const_cast<NestedNameSpecifier *>(
1906 static_cast<const NestedNameSpecifier *>(data[0])),
1907 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 }
1909};
1910
1911class DeclarationNameInfoVisit : public VisitorJob {
1912public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001913 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001914 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 static bool classof(const VisitorJob *VJ) {
1916 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1917 }
1918 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001919 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001920 switch (S->getStmtClass()) {
1921 default:
1922 llvm_unreachable("Unhandled Stmt");
1923 case clang::Stmt::MSDependentExistsStmtClass:
1924 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1925 case Stmt::CXXDependentScopeMemberExprClass:
1926 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1927 case Stmt::DependentScopeDeclRefExprClass:
1928 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001929 case Stmt::OMPCriticalDirectiveClass:
1930 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001931 }
1932 }
1933};
1934class MemberRefVisit : public VisitorJob {
1935public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001936 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001937 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1938 L.getPtrEncoding()) {}
1939 static bool classof(const VisitorJob *VJ) {
1940 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1941 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001942 const FieldDecl *get() const {
1943 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001944 }
1945 SourceLocation getLoc() const {
1946 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1947 }
1948};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001949class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001950 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 VisitorWorkList &WL;
1952 CXCursor Parent;
1953public:
1954 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1955 : WL(wl), Parent(parent) {}
1956
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001957 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1958 void VisitBlockExpr(const BlockExpr *B);
1959 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1960 void VisitCompoundStmt(const CompoundStmt *S);
1961 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1962 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1963 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1964 void VisitCXXNewExpr(const CXXNewExpr *E);
1965 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1966 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1967 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1968 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1969 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1970 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1971 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1972 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001973 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001974 void VisitDeclRefExpr(const DeclRefExpr *D);
1975 void VisitDeclStmt(const DeclStmt *S);
1976 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1977 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1978 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1979 void VisitForStmt(const ForStmt *FS);
1980 void VisitGotoStmt(const GotoStmt *GS);
1981 void VisitIfStmt(const IfStmt *If);
1982 void VisitInitListExpr(const InitListExpr *IE);
1983 void VisitMemberExpr(const MemberExpr *M);
1984 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1985 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1986 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1987 void VisitOverloadExpr(const OverloadExpr *E);
1988 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1989 void VisitStmt(const Stmt *S);
1990 void VisitSwitchStmt(const SwitchStmt *S);
1991 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001992 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1993 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1994 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1995 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1996 void VisitVAArgExpr(const VAArgExpr *E);
1997 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1998 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1999 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2000 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002001 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002002 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002003 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002004 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002005 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002006 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002007 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002008 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002009 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002010 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002011 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002012 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002013 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002014 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002015 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002016 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002017 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002018 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002019 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002020 void
2021 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002022 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002023 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002024 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002025 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002026 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002027 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002028 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002029 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002030 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002031 void
2032 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002033 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002034 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002035 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002036 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002037 void VisitOMPDistributeParallelForDirective(
2038 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002039 void VisitOMPDistributeParallelForSimdDirective(
2040 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002041 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002042 void VisitOMPTargetParallelForSimdDirective(
2043 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002044 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002045 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002046 void VisitOMPTeamsDistributeSimdDirective(
2047 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002048 void VisitOMPTeamsDistributeParallelForSimdDirective(
2049 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002050 void VisitOMPTeamsDistributeParallelForDirective(
2051 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002052 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002053 void VisitOMPTargetTeamsDistributeDirective(
2054 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002055 void VisitOMPTargetTeamsDistributeParallelForDirective(
2056 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002057 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2058 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002059 void VisitOMPTargetTeamsDistributeSimdDirective(
2060 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002061
Guy Benyei11169dd2012-12-18 14:30:41 +00002062private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002063 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002064 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002065 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2066 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002067 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2068 void AddStmt(const Stmt *S);
2069 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002070 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002071 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002072 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002073};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002074} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002075
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002076void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002077 // 'S' should always be non-null, since it comes from the
2078 // statement we are visiting.
2079 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2080}
2081
2082void
2083EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2084 if (Qualifier)
2085 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2086}
2087
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002088void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002089 if (S)
2090 WL.push_back(StmtVisit(S, Parent));
2091}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002092void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002093 if (D)
2094 WL.push_back(DeclVisit(D, Parent, isFirst));
2095}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002096void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2097 unsigned NumTemplateArgs) {
2098 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002099}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002100void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002101 if (D)
2102 WL.push_back(MemberRefVisit(D, L, Parent));
2103}
2104void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2105 if (TI)
2106 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2107 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002108void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002109 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002110 for (const Stmt *SubStmt : S->children()) {
2111 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002112 }
2113 if (size == WL.size())
2114 return;
2115 // Now reverse the entries we just added. This will match the DFS
2116 // ordering performed by the worklist.
2117 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2118 std::reverse(I, E);
2119}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002120namespace {
2121class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2122 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002123 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002124 template <typename T>
2125 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002126public:
2127 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2128#define OPENMP_CLAUSE(Name, Class) \
2129 void Visit##Class(const Class *C);
2130#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002131 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002132 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002133};
2134
Alexey Bataev3392d762016-02-16 11:18:12 +00002135void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2136 const OMPClauseWithPreInit *C) {
2137 Visitor->AddStmt(C->getPreInitStmt());
2138}
2139
Alexey Bataev005248a2016-02-25 05:25:57 +00002140void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2141 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002142 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002143 Visitor->AddStmt(C->getPostUpdateExpr());
2144}
2145
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002146void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002147 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002148 Visitor->AddStmt(C->getCondition());
2149}
2150
Alexey Bataev3778b602014-07-17 07:32:53 +00002151void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2152 Visitor->AddStmt(C->getCondition());
2153}
2154
Alexey Bataev568a8332014-03-06 06:15:19 +00002155void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002156 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002157 Visitor->AddStmt(C->getNumThreads());
2158}
2159
Alexey Bataev62c87d22014-03-21 04:51:18 +00002160void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2161 Visitor->AddStmt(C->getSafelen());
2162}
2163
Alexey Bataev66b15b52015-08-21 11:14:16 +00002164void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2165 Visitor->AddStmt(C->getSimdlen());
2166}
2167
Alexander Musman8bd31e62014-05-27 15:12:19 +00002168void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2169 Visitor->AddStmt(C->getNumForLoops());
2170}
2171
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002172void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002173
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002174void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2175
Alexey Bataev56dafe82014-06-20 07:16:17 +00002176void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002177 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002178 Visitor->AddStmt(C->getChunkSize());
2179}
2180
Alexey Bataev10e775f2015-07-30 11:36:16 +00002181void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2182 Visitor->AddStmt(C->getNumForLoops());
2183}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002184
Alexey Bataev236070f2014-06-20 11:19:47 +00002185void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2186
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002187void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2188
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002189void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2190
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002191void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2192
Alexey Bataevdea47612014-07-23 07:46:59 +00002193void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2194
Alexey Bataev67a4f222014-07-23 10:25:33 +00002195void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2196
Alexey Bataev459dec02014-07-24 06:46:57 +00002197void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2198
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002199void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2200
Alexey Bataev346265e2015-09-25 10:37:12 +00002201void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2202
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002203void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2204
Alexey Bataevb825de12015-12-07 10:51:44 +00002205void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2206
Michael Wonge710d542015-08-07 16:16:36 +00002207void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2208 Visitor->AddStmt(C->getDevice());
2209}
2210
Kelvin Li099bb8c2015-11-24 20:50:12 +00002211void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002212 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002213 Visitor->AddStmt(C->getNumTeams());
2214}
2215
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002216void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002217 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002218 Visitor->AddStmt(C->getThreadLimit());
2219}
2220
Alexey Bataeva0569352015-12-01 10:17:31 +00002221void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2222 Visitor->AddStmt(C->getPriority());
2223}
2224
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002225void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2226 Visitor->AddStmt(C->getGrainsize());
2227}
2228
Alexey Bataev382967a2015-12-08 12:06:20 +00002229void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2230 Visitor->AddStmt(C->getNumTasks());
2231}
2232
Alexey Bataev28c75412015-12-15 08:19:24 +00002233void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2234 Visitor->AddStmt(C->getHint());
2235}
2236
Alexey Bataev756c1962013-09-24 03:17:45 +00002237template<typename T>
2238void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002239 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002240 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002241 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002242}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002243
2244void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002245 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002246 for (const auto *E : C->private_copies()) {
2247 Visitor->AddStmt(E);
2248 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002249}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002250void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2251 const OMPFirstprivateClause *C) {
2252 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002253 VisitOMPClauseWithPreInit(C);
2254 for (const auto *E : C->private_copies()) {
2255 Visitor->AddStmt(E);
2256 }
2257 for (const auto *E : C->inits()) {
2258 Visitor->AddStmt(E);
2259 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002260}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002261void OMPClauseEnqueue::VisitOMPLastprivateClause(
2262 const OMPLastprivateClause *C) {
2263 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002264 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002265 for (auto *E : C->private_copies()) {
2266 Visitor->AddStmt(E);
2267 }
2268 for (auto *E : C->source_exprs()) {
2269 Visitor->AddStmt(E);
2270 }
2271 for (auto *E : C->destination_exprs()) {
2272 Visitor->AddStmt(E);
2273 }
2274 for (auto *E : C->assignment_ops()) {
2275 Visitor->AddStmt(E);
2276 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002277}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002278void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002279 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002280}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002281void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2282 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002283 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002284 for (auto *E : C->privates()) {
2285 Visitor->AddStmt(E);
2286 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002287 for (auto *E : C->lhs_exprs()) {
2288 Visitor->AddStmt(E);
2289 }
2290 for (auto *E : C->rhs_exprs()) {
2291 Visitor->AddStmt(E);
2292 }
2293 for (auto *E : C->reduction_ops()) {
2294 Visitor->AddStmt(E);
2295 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002296}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002297void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2298 const OMPTaskReductionClause *C) {
2299 VisitOMPClauseList(C);
2300 VisitOMPClauseWithPostUpdate(C);
2301 for (auto *E : C->privates()) {
2302 Visitor->AddStmt(E);
2303 }
2304 for (auto *E : C->lhs_exprs()) {
2305 Visitor->AddStmt(E);
2306 }
2307 for (auto *E : C->rhs_exprs()) {
2308 Visitor->AddStmt(E);
2309 }
2310 for (auto *E : C->reduction_ops()) {
2311 Visitor->AddStmt(E);
2312 }
2313}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002314void OMPClauseEnqueue::VisitOMPInReductionClause(
2315 const OMPInReductionClause *C) {
2316 VisitOMPClauseList(C);
2317 VisitOMPClauseWithPostUpdate(C);
2318 for (auto *E : C->privates()) {
2319 Visitor->AddStmt(E);
2320 }
2321 for (auto *E : C->lhs_exprs()) {
2322 Visitor->AddStmt(E);
2323 }
2324 for (auto *E : C->rhs_exprs()) {
2325 Visitor->AddStmt(E);
2326 }
2327 for (auto *E : C->reduction_ops()) {
2328 Visitor->AddStmt(E);
2329 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002330 for (auto *E : C->taskgroup_descriptors())
2331 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002332}
Alexander Musman8dba6642014-04-22 13:09:42 +00002333void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2334 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002335 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002336 for (const auto *E : C->privates()) {
2337 Visitor->AddStmt(E);
2338 }
Alexander Musman3276a272015-03-21 10:12:56 +00002339 for (const auto *E : C->inits()) {
2340 Visitor->AddStmt(E);
2341 }
2342 for (const auto *E : C->updates()) {
2343 Visitor->AddStmt(E);
2344 }
2345 for (const auto *E : C->finals()) {
2346 Visitor->AddStmt(E);
2347 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002348 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002349 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002350}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002351void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2352 VisitOMPClauseList(C);
2353 Visitor->AddStmt(C->getAlignment());
2354}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002355void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2356 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002357 for (auto *E : C->source_exprs()) {
2358 Visitor->AddStmt(E);
2359 }
2360 for (auto *E : C->destination_exprs()) {
2361 Visitor->AddStmt(E);
2362 }
2363 for (auto *E : C->assignment_ops()) {
2364 Visitor->AddStmt(E);
2365 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002366}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002367void
2368OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2369 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002370 for (auto *E : C->source_exprs()) {
2371 Visitor->AddStmt(E);
2372 }
2373 for (auto *E : C->destination_exprs()) {
2374 Visitor->AddStmt(E);
2375 }
2376 for (auto *E : C->assignment_ops()) {
2377 Visitor->AddStmt(E);
2378 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002379}
Alexey Bataev6125da92014-07-21 11:26:11 +00002380void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2381 VisitOMPClauseList(C);
2382}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002383void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2384 VisitOMPClauseList(C);
2385}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002386void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2387 VisitOMPClauseList(C);
2388}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002389void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2390 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002391 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002392 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002393}
Alexey Bataev3392d762016-02-16 11:18:12 +00002394void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2395 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002396void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2397 VisitOMPClauseList(C);
2398}
Samuel Antaoec172c62016-05-26 17:49:04 +00002399void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2400 VisitOMPClauseList(C);
2401}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002402void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2403 VisitOMPClauseList(C);
2404}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002405void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2406 VisitOMPClauseList(C);
2407}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002408}
Alexey Bataev756c1962013-09-24 03:17:45 +00002409
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002410void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2411 unsigned size = WL.size();
2412 OMPClauseEnqueue Visitor(this);
2413 Visitor.Visit(S);
2414 if (size == WL.size())
2415 return;
2416 // Now reverse the entries we just added. This will match the DFS
2417 // ordering performed by the worklist.
2418 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2419 std::reverse(I, E);
2420}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002421void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2423}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002424void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 AddDecl(B->getBlockDecl());
2426}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002427void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 EnqueueChildren(E);
2429 AddTypeLoc(E->getTypeSourceInfo());
2430}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002431void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002432 for (auto &I : llvm::reverse(S->body()))
2433 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002434}
2435void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002436VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 AddStmt(S->getSubStmt());
2438 AddDeclarationNameInfo(S);
2439 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2440 AddNestedNameSpecifierLoc(QualifierLoc);
2441}
2442
2443void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002444VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002445 if (E->hasExplicitTemplateArgs())
2446 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 AddDeclarationNameInfo(E);
2448 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2449 AddNestedNameSpecifierLoc(QualifierLoc);
2450 if (!E->isImplicitAccess())
2451 AddStmt(E->getBase());
2452}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002453void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 // Enqueue the initializer , if any.
2455 AddStmt(E->getInitializer());
2456 // Enqueue the array size, if any.
2457 AddStmt(E->getArraySize());
2458 // Enqueue the allocated type.
2459 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2460 // Enqueue the placement arguments.
2461 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2462 AddStmt(E->getPlacementArg(I-1));
2463}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002464void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2466 AddStmt(CE->getArg(I-1));
2467 AddStmt(CE->getCallee());
2468 AddStmt(CE->getArg(0));
2469}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002470void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2471 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 // Visit the name of the type being destroyed.
2473 AddTypeLoc(E->getDestroyedTypeInfo());
2474 // Visit the scope type that looks disturbingly like the nested-name-specifier
2475 // but isn't.
2476 AddTypeLoc(E->getScopeTypeInfo());
2477 // Visit the nested-name-specifier.
2478 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2479 AddNestedNameSpecifierLoc(QualifierLoc);
2480 // Visit base expression.
2481 AddStmt(E->getBase());
2482}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002483void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2484 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 AddTypeLoc(E->getTypeSourceInfo());
2486}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002487void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2488 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 EnqueueChildren(E);
2490 AddTypeLoc(E->getTypeSourceInfo());
2491}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002492void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 EnqueueChildren(E);
2494 if (E->isTypeOperand())
2495 AddTypeLoc(E->getTypeOperandSourceInfo());
2496}
2497
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002498void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2499 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 EnqueueChildren(E);
2501 AddTypeLoc(E->getTypeSourceInfo());
2502}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002503void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 EnqueueChildren(E);
2505 if (E->isTypeOperand())
2506 AddTypeLoc(E->getTypeOperandSourceInfo());
2507}
2508
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002509void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 EnqueueChildren(S);
2511 AddDecl(S->getExceptionDecl());
2512}
2513
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002514void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002515 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002516 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002517 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002518}
2519
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002520void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002521 if (DR->hasExplicitTemplateArgs())
2522 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 WL.push_back(DeclRefExprParts(DR, Parent));
2524}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002525void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2526 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002527 if (E->hasExplicitTemplateArgs())
2528 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 AddDeclarationNameInfo(E);
2530 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2531}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002532void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 unsigned size = WL.size();
2534 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002535 for (const auto *D : S->decls()) {
2536 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 isFirst = false;
2538 }
2539 if (size == WL.size())
2540 return;
2541 // Now reverse the entries we just added. This will match the DFS
2542 // ordering performed by the worklist.
2543 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2544 std::reverse(I, E);
2545}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002546void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002548 for (const DesignatedInitExpr::Designator &D :
2549 llvm::reverse(E->designators())) {
2550 if (D.isFieldDesignator()) {
2551 if (FieldDecl *Field = D.getField())
2552 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 continue;
2554 }
David Majnemerf7e36092016-06-23 00:15:04 +00002555 if (D.isArrayDesignator()) {
2556 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 continue;
2558 }
David Majnemerf7e36092016-06-23 00:15:04 +00002559 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2560 AddStmt(E->getArrayRangeEnd(D));
2561 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 }
2563}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002564void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 EnqueueChildren(E);
2566 AddTypeLoc(E->getTypeInfoAsWritten());
2567}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002568void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 AddStmt(FS->getBody());
2570 AddStmt(FS->getInc());
2571 AddStmt(FS->getCond());
2572 AddDecl(FS->getConditionVariable());
2573 AddStmt(FS->getInit());
2574}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002575void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2577}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002578void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 AddStmt(If->getElse());
2580 AddStmt(If->getThen());
2581 AddStmt(If->getCond());
2582 AddDecl(If->getConditionVariable());
2583}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002584void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 // We care about the syntactic form of the initializer list, only.
2586 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2587 IE = Syntactic;
2588 EnqueueChildren(IE);
2589}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002590void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 WL.push_back(MemberExprParts(M, Parent));
2592
2593 // If the base of the member access expression is an implicit 'this', don't
2594 // visit it.
2595 // FIXME: If we ever want to show these implicit accesses, this will be
2596 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002597 if (M->isImplicitAccess())
2598 return;
2599
2600 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002601 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002602 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2603 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2604 if (FD->isAnonymousStructOrUnion()) {
2605 AddStmt(SubME->getBase());
2606 return;
2607 }
2608 }
2609 }
2610
2611 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002612}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002613void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 AddTypeLoc(E->getEncodedTypeSourceInfo());
2615}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002616void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 EnqueueChildren(M);
2618 AddTypeLoc(M->getClassReceiverTypeInfo());
2619}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002620void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 // Visit the components of the offsetof expression.
2622 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 const OffsetOfNode &Node = E->getComponent(I-1);
2624 switch (Node.getKind()) {
2625 case OffsetOfNode::Array:
2626 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2627 break;
2628 case OffsetOfNode::Field:
2629 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2630 break;
2631 case OffsetOfNode::Identifier:
2632 case OffsetOfNode::Base:
2633 continue;
2634 }
2635 }
2636 // Visit the type into which we're computing the offset.
2637 AddTypeLoc(E->getTypeSourceInfo());
2638}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002639void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002640 if (E->hasExplicitTemplateArgs())
2641 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 WL.push_back(OverloadExprParts(E, Parent));
2643}
2644void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002645 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 EnqueueChildren(E);
2647 if (E->isArgumentType())
2648 AddTypeLoc(E->getArgumentTypeInfo());
2649}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002650void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 EnqueueChildren(S);
2652}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002653void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 AddStmt(S->getBody());
2655 AddStmt(S->getCond());
2656 AddDecl(S->getConditionVariable());
2657}
2658
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002659void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 AddStmt(W->getBody());
2661 AddStmt(W->getCond());
2662 AddDecl(W->getConditionVariable());
2663}
2664
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002665void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 for (unsigned I = E->getNumArgs(); I > 0; --I)
2667 AddTypeLoc(E->getArg(I-1));
2668}
2669
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002670void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 AddTypeLoc(E->getQueriedTypeSourceInfo());
2672}
2673
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002674void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 EnqueueChildren(E);
2676}
2677
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002678void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 VisitOverloadExpr(U);
2680 if (!U->isImplicitAccess())
2681 AddStmt(U->getBase());
2682}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002683void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 AddStmt(E->getSubExpr());
2685 AddTypeLoc(E->getWrittenTypeInfo());
2686}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002687void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 WL.push_back(SizeOfPackExprParts(E, Parent));
2689}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002690void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 // If the opaque value has a source expression, just transparently
2692 // visit that. This is useful for (e.g.) pseudo-object expressions.
2693 if (Expr *SourceExpr = E->getSourceExpr())
2694 return Visit(SourceExpr);
2695}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002696void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 AddStmt(E->getBody());
2698 WL.push_back(LambdaExprParts(E, Parent));
2699}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002700void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 // Treat the expression like its syntactic form.
2702 Visit(E->getSyntacticForm());
2703}
2704
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002705void EnqueueVisitor::VisitOMPExecutableDirective(
2706 const OMPExecutableDirective *D) {
2707 EnqueueChildren(D);
2708 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2709 E = D->clauses().end();
2710 I != E; ++I)
2711 EnqueueChildren(*I);
2712}
2713
Alexander Musman3aaab662014-08-19 11:27:13 +00002714void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2715 VisitOMPExecutableDirective(D);
2716}
2717
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002718void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2719 VisitOMPExecutableDirective(D);
2720}
2721
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002722void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002723 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002724}
2725
Alexey Bataevf29276e2014-06-18 04:14:57 +00002726void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002727 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002728}
2729
Alexander Musmanf82886e2014-09-18 05:12:34 +00002730void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2731 VisitOMPLoopDirective(D);
2732}
2733
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002734void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2735 VisitOMPExecutableDirective(D);
2736}
2737
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002738void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2739 VisitOMPExecutableDirective(D);
2740}
2741
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002742void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2743 VisitOMPExecutableDirective(D);
2744}
2745
Alexander Musman80c22892014-07-17 08:54:58 +00002746void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2747 VisitOMPExecutableDirective(D);
2748}
2749
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002750void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2751 VisitOMPExecutableDirective(D);
2752 AddDeclarationNameInfo(D);
2753}
2754
Alexey Bataev4acb8592014-07-07 13:01:15 +00002755void
2756EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002757 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002758}
2759
Alexander Musmane4e893b2014-09-23 09:33:00 +00002760void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2761 const OMPParallelForSimdDirective *D) {
2762 VisitOMPLoopDirective(D);
2763}
2764
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002765void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2766 const OMPParallelSectionsDirective *D) {
2767 VisitOMPExecutableDirective(D);
2768}
2769
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002770void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2771 VisitOMPExecutableDirective(D);
2772}
2773
Alexey Bataev68446b72014-07-18 07:47:19 +00002774void
2775EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2776 VisitOMPExecutableDirective(D);
2777}
2778
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002779void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2780 VisitOMPExecutableDirective(D);
2781}
2782
Alexey Bataev2df347a2014-07-18 10:17:07 +00002783void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2784 VisitOMPExecutableDirective(D);
2785}
2786
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002787void EnqueueVisitor::VisitOMPTaskgroupDirective(
2788 const OMPTaskgroupDirective *D) {
2789 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002790 if (const Expr *E = D->getReductionRef())
2791 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002792}
2793
Alexey Bataev6125da92014-07-21 11:26:11 +00002794void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2795 VisitOMPExecutableDirective(D);
2796}
2797
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002798void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2799 VisitOMPExecutableDirective(D);
2800}
2801
Alexey Bataev0162e452014-07-22 10:10:35 +00002802void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2803 VisitOMPExecutableDirective(D);
2804}
2805
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002806void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2807 VisitOMPExecutableDirective(D);
2808}
2809
Michael Wong65f367f2015-07-21 13:44:28 +00002810void EnqueueVisitor::VisitOMPTargetDataDirective(const
2811 OMPTargetDataDirective *D) {
2812 VisitOMPExecutableDirective(D);
2813}
2814
Samuel Antaodf67fc42016-01-19 19:15:56 +00002815void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2816 const OMPTargetEnterDataDirective *D) {
2817 VisitOMPExecutableDirective(D);
2818}
2819
Samuel Antao72590762016-01-19 20:04:50 +00002820void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2821 const OMPTargetExitDataDirective *D) {
2822 VisitOMPExecutableDirective(D);
2823}
2824
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002825void EnqueueVisitor::VisitOMPTargetParallelDirective(
2826 const OMPTargetParallelDirective *D) {
2827 VisitOMPExecutableDirective(D);
2828}
2829
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002830void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2831 const OMPTargetParallelForDirective *D) {
2832 VisitOMPLoopDirective(D);
2833}
2834
Alexey Bataev13314bf2014-10-09 04:18:56 +00002835void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2836 VisitOMPExecutableDirective(D);
2837}
2838
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002839void EnqueueVisitor::VisitOMPCancellationPointDirective(
2840 const OMPCancellationPointDirective *D) {
2841 VisitOMPExecutableDirective(D);
2842}
2843
Alexey Bataev80909872015-07-02 11:25:17 +00002844void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2845 VisitOMPExecutableDirective(D);
2846}
2847
Alexey Bataev49f6e782015-12-01 04:18:41 +00002848void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2849 VisitOMPLoopDirective(D);
2850}
2851
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002852void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2853 const OMPTaskLoopSimdDirective *D) {
2854 VisitOMPLoopDirective(D);
2855}
2856
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002857void EnqueueVisitor::VisitOMPDistributeDirective(
2858 const OMPDistributeDirective *D) {
2859 VisitOMPLoopDirective(D);
2860}
2861
Carlo Bertolli9925f152016-06-27 14:55:37 +00002862void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2863 const OMPDistributeParallelForDirective *D) {
2864 VisitOMPLoopDirective(D);
2865}
2866
Kelvin Li4a39add2016-07-05 05:00:15 +00002867void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2868 const OMPDistributeParallelForSimdDirective *D) {
2869 VisitOMPLoopDirective(D);
2870}
2871
Kelvin Li787f3fc2016-07-06 04:45:38 +00002872void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2873 const OMPDistributeSimdDirective *D) {
2874 VisitOMPLoopDirective(D);
2875}
2876
Kelvin Lia579b912016-07-14 02:54:56 +00002877void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2878 const OMPTargetParallelForSimdDirective *D) {
2879 VisitOMPLoopDirective(D);
2880}
2881
Kelvin Li986330c2016-07-20 22:57:10 +00002882void EnqueueVisitor::VisitOMPTargetSimdDirective(
2883 const OMPTargetSimdDirective *D) {
2884 VisitOMPLoopDirective(D);
2885}
2886
Kelvin Li02532872016-08-05 14:37:37 +00002887void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2888 const OMPTeamsDistributeDirective *D) {
2889 VisitOMPLoopDirective(D);
2890}
2891
Kelvin Li4e325f72016-10-25 12:50:55 +00002892void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2893 const OMPTeamsDistributeSimdDirective *D) {
2894 VisitOMPLoopDirective(D);
2895}
2896
Kelvin Li579e41c2016-11-30 23:51:03 +00002897void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2898 const OMPTeamsDistributeParallelForSimdDirective *D) {
2899 VisitOMPLoopDirective(D);
2900}
2901
Kelvin Li7ade93f2016-12-09 03:24:30 +00002902void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2903 const OMPTeamsDistributeParallelForDirective *D) {
2904 VisitOMPLoopDirective(D);
2905}
2906
Kelvin Libf594a52016-12-17 05:48:59 +00002907void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2908 const OMPTargetTeamsDirective *D) {
2909 VisitOMPExecutableDirective(D);
2910}
2911
Kelvin Li83c451e2016-12-25 04:52:54 +00002912void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2913 const OMPTargetTeamsDistributeDirective *D) {
2914 VisitOMPLoopDirective(D);
2915}
2916
Kelvin Li80e8f562016-12-29 22:16:30 +00002917void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2918 const OMPTargetTeamsDistributeParallelForDirective *D) {
2919 VisitOMPLoopDirective(D);
2920}
2921
Kelvin Li1851df52017-01-03 05:23:48 +00002922void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2923 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2924 VisitOMPLoopDirective(D);
2925}
2926
Kelvin Lida681182017-01-10 18:08:18 +00002927void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2928 const OMPTargetTeamsDistributeSimdDirective *D) {
2929 VisitOMPLoopDirective(D);
2930}
2931
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002932void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2934}
2935
2936bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2937 if (RegionOfInterest.isValid()) {
2938 SourceRange Range = getRawCursorExtent(C);
2939 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2940 return false;
2941 }
2942 return true;
2943}
2944
2945bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2946 while (!WL.empty()) {
2947 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002948 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002949
2950 // Set the Parent field, then back to its old value once we're done.
2951 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2952
2953 switch (LI.getKind()) {
2954 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002955 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002956 if (!D)
2957 continue;
2958
2959 // For now, perform default visitation for Decls.
2960 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2961 cast<DeclVisit>(&LI)->isFirst())))
2962 return true;
2963
2964 continue;
2965 }
2966 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002967 for (const TemplateArgumentLoc &Arg :
2968 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2969 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 return true;
2971 }
2972 continue;
2973 }
2974 case VisitorJob::TypeLocVisitKind: {
2975 // Perform default visitation for TypeLocs.
2976 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2977 return true;
2978 continue;
2979 }
2980 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002981 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 if (LabelStmt *stmt = LS->getStmt()) {
2983 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2984 TU))) {
2985 return true;
2986 }
2987 }
2988 continue;
2989 }
2990
2991 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2992 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2993 if (VisitNestedNameSpecifierLoc(V->get()))
2994 return true;
2995 continue;
2996 }
2997
2998 case VisitorJob::DeclarationNameInfoVisitKind: {
2999 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3000 ->get()))
3001 return true;
3002 continue;
3003 }
3004 case VisitorJob::MemberRefVisitKind: {
3005 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3006 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3007 return true;
3008 continue;
3009 }
3010 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003011 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003012 if (!S)
3013 continue;
3014
3015 // Update the current cursor.
3016 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3017 if (!IsInRegionOfInterest(Cursor))
3018 continue;
3019 switch (Visitor(Cursor, Parent, ClientData)) {
3020 case CXChildVisit_Break: return true;
3021 case CXChildVisit_Continue: break;
3022 case CXChildVisit_Recurse:
3023 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003024 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 EnqueueWorkList(WL, S);
3026 break;
3027 }
3028 continue;
3029 }
3030 case VisitorJob::MemberExprPartsKind: {
3031 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003032 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003033
3034 // Visit the nested-name-specifier
3035 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3036 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3037 return true;
3038
3039 // Visit the declaration name.
3040 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3041 return true;
3042
3043 // Visit the explicitly-specified template arguments, if any.
3044 if (M->hasExplicitTemplateArgs()) {
3045 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3046 *ArgEnd = Arg + M->getNumTemplateArgs();
3047 Arg != ArgEnd; ++Arg) {
3048 if (VisitTemplateArgumentLoc(*Arg))
3049 return true;
3050 }
3051 }
3052 continue;
3053 }
3054 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003055 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 // Visit nested-name-specifier, if present.
3057 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3058 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3059 return true;
3060 // Visit declaration name.
3061 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3062 return true;
3063 continue;
3064 }
3065 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003066 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 // Visit the nested-name-specifier.
3068 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3069 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3070 return true;
3071 // Visit the declaration name.
3072 if (VisitDeclarationNameInfo(O->getNameInfo()))
3073 return true;
3074 // Visit the overloaded declaration reference.
3075 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3076 return true;
3077 continue;
3078 }
3079 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003080 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 NamedDecl *Pack = E->getPack();
3082 if (isa<TemplateTypeParmDecl>(Pack)) {
3083 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3084 E->getPackLoc(), TU)))
3085 return true;
3086
3087 continue;
3088 }
3089
3090 if (isa<TemplateTemplateParmDecl>(Pack)) {
3091 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3092 E->getPackLoc(), TU)))
3093 return true;
3094
3095 continue;
3096 }
3097
3098 // Non-type template parameter packs and function parameter packs are
3099 // treated like DeclRefExpr cursors.
3100 continue;
3101 }
3102
3103 case VisitorJob::LambdaExprPartsKind: {
3104 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003105 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3107 CEnd = E->explicit_capture_end();
3108 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003109 // FIXME: Lambda init-captures.
3110 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003112
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3114 C->getLocation(),
3115 TU)))
3116 return true;
3117 }
3118
3119 // Visit parameters and return type, if present.
3120 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3121 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3122 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3123 // Visit the whole type.
3124 if (Visit(TL))
3125 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003126 } else if (FunctionProtoTypeLoc Proto =
3127 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 if (E->hasExplicitParameters()) {
3129 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003130 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3131 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 return true;
3133 } else {
3134 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003135 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 return true;
3137 }
3138 }
3139 }
3140 break;
3141 }
3142
3143 case VisitorJob::PostChildrenVisitKind:
3144 if (PostChildrenVisitor(Parent, ClientData))
3145 return true;
3146 break;
3147 }
3148 }
3149 return false;
3150}
3151
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003152bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003153 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 if (!WorkListFreeList.empty()) {
3155 WL = WorkListFreeList.back();
3156 WL->clear();
3157 WorkListFreeList.pop_back();
3158 }
3159 else {
3160 WL = new VisitorWorkList();
3161 WorkListCache.push_back(WL);
3162 }
3163 EnqueueWorkList(*WL, S);
3164 bool result = RunVisitorWorkList(*WL);
3165 WorkListFreeList.push_back(WL);
3166 return result;
3167}
3168
3169namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003170typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003171RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3172 const DeclarationNameInfo &NI, SourceRange QLoc,
3173 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003174 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3175 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3176 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3177
3178 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3179
3180 RefNamePieces Pieces;
3181
3182 if (WantQualifier && QLoc.isValid())
3183 Pieces.push_back(QLoc);
3184
3185 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3186 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003187
3188 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3189 Pieces.push_back(*TemplateArgsLoc);
3190
Guy Benyei11169dd2012-12-18 14:30:41 +00003191 if (Kind == DeclarationName::CXXOperatorName) {
3192 Pieces.push_back(SourceLocation::getFromRawEncoding(
3193 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3194 Pieces.push_back(SourceLocation::getFromRawEncoding(
3195 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3196 }
3197
3198 if (WantSinglePiece) {
3199 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3200 Pieces.clear();
3201 Pieces.push_back(R);
3202 }
3203
3204 return Pieces;
3205}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003206}
Guy Benyei11169dd2012-12-18 14:30:41 +00003207
3208//===----------------------------------------------------------------------===//
3209// Misc. API hooks.
3210//===----------------------------------------------------------------------===//
3211
Chad Rosier05c71aa2013-03-27 18:28:23 +00003212static void fatal_error_handler(void *user_data, const std::string& reason,
3213 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003214 // Write the result out to stderr avoiding errs() because raw_ostreams can
3215 // call report_fatal_error.
3216 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3217 ::abort();
3218}
3219
Chandler Carruth66660742014-06-27 16:37:27 +00003220namespace {
3221struct RegisterFatalErrorHandler {
3222 RegisterFatalErrorHandler() {
3223 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3224 }
3225};
3226}
3227
3228static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3229
Guy Benyei11169dd2012-12-18 14:30:41 +00003230CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3231 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003232 // We use crash recovery to make some of our APIs more reliable, implicitly
3233 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003234 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3235 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003236
Chandler Carruth66660742014-06-27 16:37:27 +00003237 // Look through the managed static to trigger construction of the managed
3238 // static which registers our fatal error handler. This ensures it is only
3239 // registered once.
3240 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003241
Adrian Prantlbc068582015-07-08 01:00:30 +00003242 // Initialize targets for clang module support.
3243 llvm::InitializeAllTargets();
3244 llvm::InitializeAllTargetMCs();
3245 llvm::InitializeAllAsmPrinters();
3246 llvm::InitializeAllAsmParsers();
3247
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003248 CIndexer *CIdxr = new CIndexer();
3249
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 if (excludeDeclarationsFromPCH)
3251 CIdxr->setOnlyLocalDecls();
3252 if (displayDiagnostics)
3253 CIdxr->setDisplayDiagnostics();
3254
3255 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3256 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3257 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3258 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3259 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3260 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3261
3262 return CIdxr;
3263}
3264
3265void clang_disposeIndex(CXIndex CIdx) {
3266 if (CIdx)
3267 delete static_cast<CIndexer *>(CIdx);
3268}
3269
3270void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3271 if (CIdx)
3272 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3273}
3274
3275unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3276 if (CIdx)
3277 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3278 return 0;
3279}
3280
Alex Lorenz08615792017-12-04 21:56:36 +00003281void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3282 const char *Path) {
3283 if (CIdx)
3284 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3285}
3286
Guy Benyei11169dd2012-12-18 14:30:41 +00003287void clang_toggleCrashRecovery(unsigned isEnabled) {
3288 if (isEnabled)
3289 llvm::CrashRecoveryContext::Enable();
3290 else
3291 llvm::CrashRecoveryContext::Disable();
3292}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003293
Guy Benyei11169dd2012-12-18 14:30:41 +00003294CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3295 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003296 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003297 enum CXErrorCode Result =
3298 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003299 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003300 assert((TU && Result == CXError_Success) ||
3301 (!TU && Result != CXError_Success));
3302 return TU;
3303}
3304
3305enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3306 const char *ast_filename,
3307 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003308 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003309 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003310
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003311 if (!CIdx || !ast_filename || !out_TU)
3312 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003313
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003314 LOG_FUNC_SECTION {
3315 *Log << ast_filename;
3316 }
3317
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3319 FileSystemOptions FileSystemOpts;
3320
Justin Bognerd512c1e2014-10-15 00:33:06 +00003321 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3322 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003323 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003324 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3325 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003326 FileSystemOpts, /*UseDebugInfo=*/false,
3327 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003328 /*CaptureDiagnostics=*/true,
3329 /*AllowPCHWithCompilerErrors=*/true,
3330 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003331 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003332 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003333}
3334
3335unsigned clang_defaultEditingTranslationUnitOptions() {
3336 return CXTranslationUnit_PrecompiledPreamble |
3337 CXTranslationUnit_CacheCompletionResults;
3338}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003339
Guy Benyei11169dd2012-12-18 14:30:41 +00003340CXTranslationUnit
3341clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3342 const char *source_filename,
3343 int num_command_line_args,
3344 const char * const *command_line_args,
3345 unsigned num_unsaved_files,
3346 struct CXUnsavedFile *unsaved_files) {
3347 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3348 return clang_parseTranslationUnit(CIdx, source_filename,
3349 command_line_args, num_command_line_args,
3350 unsaved_files, num_unsaved_files,
3351 Options);
3352}
3353
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003354static CXErrorCode
3355clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3356 const char *const *command_line_args,
3357 int num_command_line_args,
3358 ArrayRef<CXUnsavedFile> unsaved_files,
3359 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003360 // Set up the initial return values.
3361 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003362 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003363
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003364 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003365 if (!CIdx || !out_TU)
3366 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003367
Guy Benyei11169dd2012-12-18 14:30:41 +00003368 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3369
3370 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3371 setThreadBackgroundPriority();
3372
3373 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003374 bool CreatePreambleOnFirstParse =
3375 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 // FIXME: Add a flag for modules.
3377 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003378 = (options & (CXTranslationUnit_Incomplete |
3379 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003380 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003381 = options & CXTranslationUnit_CacheCompletionResults;
3382 bool IncludeBriefCommentsInCodeCompletion
3383 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003384 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3385 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003386 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3387 if (options & CXTranslationUnit_SkipFunctionBodies) {
3388 SkipFunctionBodies =
3389 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3390 ? SkipFunctionBodiesScope::Preamble
3391 : SkipFunctionBodiesScope::PreambleAndMainFile;
3392 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003393
3394 // Configure the diagnostics.
3395 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003396 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003397
Manuel Klimek016c0242016-03-01 10:56:19 +00003398 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003399 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003400
Guy Benyei11169dd2012-12-18 14:30:41 +00003401 // Recover resources if we crash before exiting this function.
3402 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3403 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003404 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003405
Ahmed Charlesb8984322014-03-07 20:03:18 +00003406 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3407 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003408
3409 // Recover resources if we crash before exiting this function.
3410 llvm::CrashRecoveryContextCleanupRegistrar<
3411 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3412
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003413 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003414 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003415 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003416 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003417 }
3418
Ahmed Charlesb8984322014-03-07 20:03:18 +00003419 std::unique_ptr<std::vector<const char *>> Args(
3420 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003421
3422 // Recover resources if we crash before exiting this method.
3423 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3424 ArgsCleanup(Args.get());
3425
3426 // Since the Clang C library is primarily used by batch tools dealing with
3427 // (often very broken) source code, where spell-checking can have a
3428 // significant negative impact on performance (particularly when
3429 // precompiled headers are involved), we disable it by default.
3430 // Only do this if we haven't found a spell-checking-related argument.
3431 bool FoundSpellCheckingArgument = false;
3432 for (int I = 0; I != num_command_line_args; ++I) {
3433 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3434 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3435 FoundSpellCheckingArgument = true;
3436 break;
3437 }
3438 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 Args->insert(Args->end(), command_line_args,
3440 command_line_args + num_command_line_args);
3441
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003442 if (!FoundSpellCheckingArgument)
3443 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3444
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 // The 'source_filename' argument is optional. If the caller does not
3446 // specify it then it is assumed that the source file is specified
3447 // in the actual argument list.
3448 // Put the source file after command_line_args otherwise if '-x' flag is
3449 // present it will be unused.
3450 if (source_filename)
3451 Args->push_back(source_filename);
3452
3453 // Do we need the detailed preprocessing record?
3454 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3455 Args->push_back("-Xclang");
3456 Args->push_back("-detailed-preprocessing-record");
3457 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003458
3459 // Suppress any editor placeholder diagnostics.
3460 Args->push_back("-fallow-editor-placeholders");
3461
Guy Benyei11169dd2012-12-18 14:30:41 +00003462 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003463 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003464 // Unless the user specified that they want the preamble on the first parse
3465 // set it up to be created on the first reparse. This makes the first parse
3466 // faster, trading for a slower (first) reparse.
3467 unsigned PrecompilePreambleAfterNParses =
3468 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003469
Alex Lorenz08615792017-12-04 21:56:36 +00003470 LibclangInvocationReporter InvocationReporter(
3471 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003472 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3473 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003474 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003475 Args->data(), Args->data() + Args->size(),
3476 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003477 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3478 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003479 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3480 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003481 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003482 /*UserFilesAreVolatile=*/true, ForSerialization,
3483 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3484 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003485
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003486 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003487 if (!Unit && !ErrUnit)
3488 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003489
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 if (NumErrors != Diags->getClient()->getNumErrors()) {
3491 // Make sure to check that 'Unit' is non-NULL.
3492 if (CXXIdx->getDisplayDiagnostics())
3493 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3494 }
3495
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003496 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3497 return CXError_ASTReadError;
3498
David Blaikieea4395e2017-01-06 19:49:01 +00003499 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003500 if (CXTranslationUnitImpl *TU = *out_TU) {
3501 TU->ParsingOptions = options;
3502 TU->Arguments.reserve(Args->size());
3503 for (const char *Arg : *Args)
3504 TU->Arguments.push_back(Arg);
3505 return CXError_Success;
3506 }
3507 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003508}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003509
3510CXTranslationUnit
3511clang_parseTranslationUnit(CXIndex CIdx,
3512 const char *source_filename,
3513 const char *const *command_line_args,
3514 int num_command_line_args,
3515 struct CXUnsavedFile *unsaved_files,
3516 unsigned num_unsaved_files,
3517 unsigned options) {
3518 CXTranslationUnit TU;
3519 enum CXErrorCode Result = clang_parseTranslationUnit2(
3520 CIdx, source_filename, command_line_args, num_command_line_args,
3521 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003522 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003523 assert((TU && Result == CXError_Success) ||
3524 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003525 return TU;
3526}
3527
3528enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003529 CXIndex CIdx, const char *source_filename,
3530 const char *const *command_line_args, int num_command_line_args,
3531 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3532 unsigned options, CXTranslationUnit *out_TU) {
3533 SmallVector<const char *, 4> Args;
3534 Args.push_back("clang");
3535 Args.append(command_line_args, command_line_args + num_command_line_args);
3536 return clang_parseTranslationUnit2FullArgv(
3537 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3538 num_unsaved_files, options, out_TU);
3539}
3540
3541enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3542 CXIndex CIdx, const char *source_filename,
3543 const char *const *command_line_args, int num_command_line_args,
3544 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3545 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003546 LOG_FUNC_SECTION {
3547 *Log << source_filename << ": ";
3548 for (int i = 0; i != num_command_line_args; ++i)
3549 *Log << command_line_args[i] << " ";
3550 }
3551
Alp Toker9d85b182014-07-07 01:23:14 +00003552 if (num_unsaved_files && !unsaved_files)
3553 return CXError_InvalidArguments;
3554
Alp Toker5c532982014-07-07 22:42:03 +00003555 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003556 auto ParseTranslationUnitImpl = [=, &result] {
3557 result = clang_parseTranslationUnit_Impl(
3558 CIdx, source_filename, command_line_args, num_command_line_args,
3559 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3560 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003561
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 llvm::CrashRecoveryContext CRC;
3563
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003564 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3566 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3567 fprintf(stderr, " 'command_line_args' : [");
3568 for (int i = 0; i != num_command_line_args; ++i) {
3569 if (i)
3570 fprintf(stderr, ", ");
3571 fprintf(stderr, "'%s'", command_line_args[i]);
3572 }
3573 fprintf(stderr, "],\n");
3574 fprintf(stderr, " 'unsaved_files' : [");
3575 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3576 if (i)
3577 fprintf(stderr, ", ");
3578 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3579 unsaved_files[i].Length);
3580 }
3581 fprintf(stderr, "],\n");
3582 fprintf(stderr, " 'options' : %d,\n", options);
3583 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003584
3585 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003586 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003587 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003588 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003589 }
Alp Toker5c532982014-07-07 22:42:03 +00003590
3591 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003592}
3593
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003594CXString clang_Type_getObjCEncoding(CXType CT) {
3595 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3596 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3597 std::string encoding;
3598 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3599 encoding);
3600
3601 return cxstring::createDup(encoding);
3602}
3603
3604static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3605 if (C.kind == CXCursor_MacroDefinition) {
3606 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3607 return MDR->getName();
3608 } else if (C.kind == CXCursor_MacroExpansion) {
3609 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3610 return ME.getName();
3611 }
3612 return nullptr;
3613}
3614
3615unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3616 const IdentifierInfo *II = getMacroIdentifier(C);
3617 if (!II) {
3618 return false;
3619 }
3620 ASTUnit *ASTU = getCursorASTUnit(C);
3621 Preprocessor &PP = ASTU->getPreprocessor();
3622 if (const MacroInfo *MI = PP.getMacroInfo(II))
3623 return MI->isFunctionLike();
3624 return false;
3625}
3626
3627unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3628 const IdentifierInfo *II = getMacroIdentifier(C);
3629 if (!II) {
3630 return false;
3631 }
3632 ASTUnit *ASTU = getCursorASTUnit(C);
3633 Preprocessor &PP = ASTU->getPreprocessor();
3634 if (const MacroInfo *MI = PP.getMacroInfo(II))
3635 return MI->isBuiltinMacro();
3636 return false;
3637}
3638
3639unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3640 const Decl *D = getCursorDecl(C);
3641 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3642 if (!FD) {
3643 return false;
3644 }
3645 return FD->isInlined();
3646}
3647
3648static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3649 if (callExpr->getNumArgs() != 1) {
3650 return nullptr;
3651 }
3652
3653 StringLiteral *S = nullptr;
3654 auto *arg = callExpr->getArg(0);
3655 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3656 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3657 auto *subExpr = I->getSubExprAsWritten();
3658
3659 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3660 return nullptr;
3661 }
3662
3663 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3664 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3665 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3666 } else {
3667 return nullptr;
3668 }
3669 return S;
3670}
3671
David Blaikie59272572016-04-13 18:23:33 +00003672struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003673 CXEvalResultKind EvalType;
3674 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003675 unsigned long long unsignedVal;
3676 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003677 double floatVal;
3678 char *stringVal;
3679 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003680 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003681 ~ExprEvalResult() {
3682 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3683 EvalType != CXEval_Int) {
3684 delete EvalData.stringVal;
3685 }
3686 }
3687};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003688
3689void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003690 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003691}
3692
3693CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3694 if (!E) {
3695 return CXEval_UnExposed;
3696 }
3697 return ((ExprEvalResult *)E)->EvalType;
3698}
3699
3700int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003701 return clang_EvalResult_getAsLongLong(E);
3702}
3703
3704long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003705 if (!E) {
3706 return 0;
3707 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003708 ExprEvalResult *Result = (ExprEvalResult*)E;
3709 if (Result->IsUnsignedInt)
3710 return Result->EvalData.unsignedVal;
3711 return Result->EvalData.intVal;
3712}
3713
3714unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3715 return ((ExprEvalResult *)E)->IsUnsignedInt;
3716}
3717
3718unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3719 if (!E) {
3720 return 0;
3721 }
3722
3723 ExprEvalResult *Result = (ExprEvalResult*)E;
3724 if (Result->IsUnsignedInt)
3725 return Result->EvalData.unsignedVal;
3726 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003727}
3728
3729double clang_EvalResult_getAsDouble(CXEvalResult E) {
3730 if (!E) {
3731 return 0;
3732 }
3733 return ((ExprEvalResult *)E)->EvalData.floatVal;
3734}
3735
3736const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3737 if (!E) {
3738 return nullptr;
3739 }
3740 return ((ExprEvalResult *)E)->EvalData.stringVal;
3741}
3742
3743static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3744 Expr::EvalResult ER;
3745 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003746 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003747 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003748
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003749 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003750 if (!expr->EvaluateAsRValue(ER, ctx))
3751 return nullptr;
3752
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003753 QualType rettype;
3754 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003755 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003756 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003757 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003758
David Blaikiebbc00882016-04-13 18:36:19 +00003759 if (ER.Val.isInt()) {
3760 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003761
3762 auto& val = ER.Val.getInt();
3763 if (val.isUnsigned()) {
3764 result->IsUnsignedInt = true;
3765 result->EvalData.unsignedVal = val.getZExtValue();
3766 } else {
3767 result->EvalData.intVal = val.getExtValue();
3768 }
3769
David Blaikiebbc00882016-04-13 18:36:19 +00003770 return result.release();
3771 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003772
David Blaikiebbc00882016-04-13 18:36:19 +00003773 if (ER.Val.isFloat()) {
3774 llvm::SmallVector<char, 100> Buffer;
3775 ER.Val.getFloat().toString(Buffer);
3776 std::string floatStr(Buffer.data(), Buffer.size());
3777 result->EvalType = CXEval_Float;
3778 bool ignored;
3779 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003780 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003781 llvm::APFloat::rmNearestTiesToEven, &ignored);
3782 result->EvalData.floatVal = apFloat.convertToDouble();
3783 return result.release();
3784 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003785
David Blaikiebbc00882016-04-13 18:36:19 +00003786 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3787 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3788 auto *subExpr = I->getSubExprAsWritten();
3789 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3790 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003791 const StringLiteral *StrE = nullptr;
3792 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003793 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003794
3795 if (ObjCExpr) {
3796 StrE = ObjCExpr->getString();
3797 result->EvalType = CXEval_ObjCStrLiteral;
3798 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003799 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003800 result->EvalType = CXEval_StrLiteral;
3801 }
3802
3803 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003804 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003805 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3806 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003807 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003808 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003809 }
3810 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3811 expr->getStmtClass() == Stmt::StringLiteralClass) {
3812 const StringLiteral *StrE = nullptr;
3813 const ObjCStringLiteral *ObjCExpr;
3814 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003815
David Blaikiebbc00882016-04-13 18:36:19 +00003816 if (ObjCExpr) {
3817 StrE = ObjCExpr->getString();
3818 result->EvalType = CXEval_ObjCStrLiteral;
3819 } else {
3820 StrE = cast<StringLiteral>(expr);
3821 result->EvalType = CXEval_StrLiteral;
3822 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003823
David Blaikiebbc00882016-04-13 18:36:19 +00003824 std::string strRef(StrE->getString().str());
3825 result->EvalData.stringVal = new char[strRef.size() + 1];
3826 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3827 result->EvalData.stringVal[strRef.size()] = '\0';
3828 return result.release();
3829 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003830
David Blaikiebbc00882016-04-13 18:36:19 +00003831 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3832 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003833
David Blaikiebbc00882016-04-13 18:36:19 +00003834 rettype = CC->getType();
3835 if (rettype.getAsString() == "CFStringRef" &&
3836 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003837
David Blaikiebbc00882016-04-13 18:36:19 +00003838 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3839 StringLiteral *S = getCFSTR_value(callExpr);
3840 if (S) {
3841 std::string strLiteral(S->getString().str());
3842 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003843
David Blaikiebbc00882016-04-13 18:36:19 +00003844 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3845 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3846 strLiteral.size());
3847 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003848 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003849 }
3850 }
3851
David Blaikiebbc00882016-04-13 18:36:19 +00003852 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3853 callExpr = static_cast<CallExpr *>(expr);
3854 rettype = callExpr->getCallReturnType(ctx);
3855
3856 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3857 return nullptr;
3858
3859 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3860 if (callExpr->getNumArgs() == 1 &&
3861 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3862 return nullptr;
3863 } else if (rettype.getAsString() == "CFStringRef") {
3864
3865 StringLiteral *S = getCFSTR_value(callExpr);
3866 if (S) {
3867 std::string strLiteral(S->getString().str());
3868 result->EvalType = CXEval_CFStr;
3869 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3870 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3871 strLiteral.size());
3872 result->EvalData.stringVal[strLiteral.size()] = '\0';
3873 return result.release();
3874 }
3875 }
3876 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3877 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3878 ValueDecl *V = D->getDecl();
3879 if (V->getKind() == Decl::Function) {
3880 std::string strName = V->getNameAsString();
3881 result->EvalType = CXEval_Other;
3882 result->EvalData.stringVal = new char[strName.size() + 1];
3883 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3884 result->EvalData.stringVal[strName.size()] = '\0';
3885 return result.release();
3886 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003887 }
3888
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003889 return nullptr;
3890}
3891
3892CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3893 const Decl *D = getCursorDecl(C);
3894 if (D) {
3895 const Expr *expr = nullptr;
3896 if (auto *Var = dyn_cast<VarDecl>(D)) {
3897 expr = Var->getInit();
3898 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3899 expr = Field->getInClassInitializer();
3900 }
3901 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003902 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3903 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003904 return nullptr;
3905 }
3906
3907 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3908 if (compoundStmt) {
3909 Expr *expr = nullptr;
3910 for (auto *bodyIterator : compoundStmt->body()) {
3911 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3912 break;
3913 }
3914 }
3915 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003916 return const_cast<CXEvalResult>(
3917 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003918 }
3919 return nullptr;
3920}
3921
3922unsigned clang_Cursor_hasAttrs(CXCursor C) {
3923 const Decl *D = getCursorDecl(C);
3924 if (!D) {
3925 return 0;
3926 }
3927
3928 if (D->hasAttrs()) {
3929 return 1;
3930 }
3931
3932 return 0;
3933}
Guy Benyei11169dd2012-12-18 14:30:41 +00003934unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3935 return CXSaveTranslationUnit_None;
3936}
3937
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003938static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3939 const char *FileName,
3940 unsigned options) {
3941 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003942 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3943 setThreadBackgroundPriority();
3944
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003945 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3946 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003947}
3948
3949int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3950 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003951 LOG_FUNC_SECTION {
3952 *Log << TU << ' ' << FileName;
3953 }
3954
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003955 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003956 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003957 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003958 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003959
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003960 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3962 if (!CXXUnit->hasSema())
3963 return CXSaveError_InvalidTU;
3964
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003965 CXSaveError result;
3966 auto SaveTranslationUnitImpl = [=, &result]() {
3967 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3968 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003969
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003970 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003971 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003972
3973 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3974 PrintLibclangResourceUsage(TU);
3975
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003976 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003977 }
3978
3979 // We have an AST that has invalid nodes due to compiler errors.
3980 // Use a crash recovery thread for protection.
3981
3982 llvm::CrashRecoveryContext CRC;
3983
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003984 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003985 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3986 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3987 fprintf(stderr, " 'options' : %d,\n", options);
3988 fprintf(stderr, "}\n");
3989
3990 return CXSaveError_Unknown;
3991
3992 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3993 PrintLibclangResourceUsage(TU);
3994 }
3995
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003996 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003997}
3998
3999void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4000 if (CTUnit) {
4001 // If the translation unit has been marked as unsafe to free, just discard
4002 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004003 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4004 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 return;
4006
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004007 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004008 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4010 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004011 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004012 delete CTUnit;
4013 }
4014}
4015
Erik Verbruggen346066b2017-05-30 14:25:54 +00004016unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4017 if (CTUnit) {
4018 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4019
4020 if (Unit && Unit->isUnsafeToFree())
4021 return false;
4022
4023 Unit->ResetForParse();
4024 return true;
4025 }
4026
4027 return false;
4028}
4029
Guy Benyei11169dd2012-12-18 14:30:41 +00004030unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4031 return CXReparse_None;
4032}
4033
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004034static CXErrorCode
4035clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4036 ArrayRef<CXUnsavedFile> unsaved_files,
4037 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004038 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004039 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004040 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004041 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004042 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004043
4044 // Reset the associated diagnostics.
4045 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004046 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004047
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004048 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4050 setThreadBackgroundPriority();
4051
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004052 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004053 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004054
4055 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4056 new std::vector<ASTUnit::RemappedFile>());
4057
Guy Benyei11169dd2012-12-18 14:30:41 +00004058 // Recover resources if we crash before exiting this function.
4059 llvm::CrashRecoveryContextCleanupRegistrar<
4060 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004061
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004062 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004063 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004064 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004065 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004067
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004068 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4069 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004070 return CXError_Success;
4071 if (isASTReadError(CXXUnit))
4072 return CXError_ASTReadError;
4073 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004074}
4075
4076int clang_reparseTranslationUnit(CXTranslationUnit TU,
4077 unsigned num_unsaved_files,
4078 struct CXUnsavedFile *unsaved_files,
4079 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004080 LOG_FUNC_SECTION {
4081 *Log << TU;
4082 }
4083
Alp Toker9d85b182014-07-07 01:23:14 +00004084 if (num_unsaved_files && !unsaved_files)
4085 return CXError_InvalidArguments;
4086
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004087 CXErrorCode result;
4088 auto ReparseTranslationUnitImpl = [=, &result]() {
4089 result = clang_reparseTranslationUnit_Impl(
4090 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4091 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004092
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 llvm::CrashRecoveryContext CRC;
4094
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004095 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004097 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004098 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4100 PrintLibclangResourceUsage(TU);
4101
Alp Toker5c532982014-07-07 22:42:03 +00004102 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004103}
4104
4105
4106CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004107 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004108 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004109 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004110 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004111
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004112 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004113 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004114}
4115
4116CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004117 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004118 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004119 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004120 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004121
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004122 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4124}
4125
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004126CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4127 if (isNotUsableTU(CTUnit)) {
4128 LOG_BAD_TU(CTUnit);
4129 return nullptr;
4130 }
4131
4132 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4133 impl->TranslationUnit = CTUnit;
4134 return impl;
4135}
4136
4137CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4138 if (!TargetInfo)
4139 return cxstring::createEmpty();
4140
4141 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4142 assert(!isNotUsableTU(CTUnit) &&
4143 "Unexpected unusable translation unit in TargetInfo");
4144
4145 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4146 std::string Triple =
4147 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4148 return cxstring::createDup(Triple);
4149}
4150
4151int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4152 if (!TargetInfo)
4153 return -1;
4154
4155 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4156 assert(!isNotUsableTU(CTUnit) &&
4157 "Unexpected unusable translation unit in TargetInfo");
4158
4159 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4160 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4161}
4162
4163void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4164 if (!TargetInfo)
4165 return;
4166
4167 delete TargetInfo;
4168}
4169
Guy Benyei11169dd2012-12-18 14:30:41 +00004170//===----------------------------------------------------------------------===//
4171// CXFile Operations.
4172//===----------------------------------------------------------------------===//
4173
Guy Benyei11169dd2012-12-18 14:30:41 +00004174CXString clang_getFileName(CXFile SFile) {
4175 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004176 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004177
4178 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004179 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004180}
4181
4182time_t clang_getFileTime(CXFile SFile) {
4183 if (!SFile)
4184 return 0;
4185
4186 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4187 return FEnt->getModificationTime();
4188}
4189
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004190CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004191 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004192 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004193 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004194 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004195
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004196 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004197
4198 FileManager &FMgr = CXXUnit->getFileManager();
4199 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4200}
4201
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004202const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4203 size_t *size) {
4204 if (isNotUsableTU(TU)) {
4205 LOG_BAD_TU(TU);
4206 return nullptr;
4207 }
4208
4209 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4210 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4211 bool Invalid = true;
4212 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4213 if (Invalid) {
4214 if (size)
4215 *size = 0;
4216 return nullptr;
4217 }
4218 if (size)
4219 *size = buf->getBufferSize();
4220 return buf->getBufferStart();
4221}
4222
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004223unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4224 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004225 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004226 LOG_BAD_TU(TU);
4227 return 0;
4228 }
4229
4230 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 return 0;
4232
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004233 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 FileEntry *FEnt = static_cast<FileEntry *>(file);
4235 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4236 .isFileMultipleIncludeGuarded(FEnt);
4237}
4238
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004239int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4240 if (!file || !outID)
4241 return 1;
4242
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004243 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004244 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4245 outID->data[0] = ID.getDevice();
4246 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004247 outID->data[2] = FEnt->getModificationTime();
4248 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004249}
4250
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004251int clang_File_isEqual(CXFile file1, CXFile file2) {
4252 if (file1 == file2)
4253 return true;
4254
4255 if (!file1 || !file2)
4256 return false;
4257
4258 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4259 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4260 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4261}
4262
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004263CXString clang_File_tryGetRealPathName(CXFile SFile) {
4264 if (!SFile)
4265 return cxstring::createNull();
4266
4267 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4268 return cxstring::createRef(FEnt->tryGetRealPathName());
4269}
4270
Guy Benyei11169dd2012-12-18 14:30:41 +00004271//===----------------------------------------------------------------------===//
4272// CXCursor Operations.
4273//===----------------------------------------------------------------------===//
4274
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004275static const Decl *getDeclFromExpr(const Stmt *E) {
4276 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 return getDeclFromExpr(CE->getSubExpr());
4278
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004279 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004280 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004281 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004282 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004283 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004285 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 if (PRE->isExplicitProperty())
4287 return PRE->getExplicitProperty();
4288 // It could be messaging both getter and setter as in:
4289 // ++myobj.myprop;
4290 // in which case prefer to associate the setter since it is less obvious
4291 // from inspecting the source that the setter is going to get called.
4292 if (PRE->isMessagingSetter())
4293 return PRE->getImplicitPropertySetter();
4294 return PRE->getImplicitPropertyGetter();
4295 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004296 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004298 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 if (Expr *Src = OVE->getSourceExpr())
4300 return getDeclFromExpr(Src);
4301
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004302 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004304 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 if (!CE->isElidable())
4306 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004307 if (const CXXInheritedCtorInitExpr *CE =
4308 dyn_cast<CXXInheritedCtorInitExpr>(E))
4309 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004310 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 return OME->getMethodDecl();
4312
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004313 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004315 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4317 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004318 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4320 isa<ParmVarDecl>(SizeOfPack->getPack()))
4321 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004322
4323 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004324}
4325
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004326static SourceLocation getLocationFromExpr(const Expr *E) {
4327 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 return getLocationFromExpr(CE->getSubExpr());
4329
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004330 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004332 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004334 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004336 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004338 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004340 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 return PropRef->getLocation();
4342
4343 return E->getLocStart();
4344}
4345
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004346extern "C" {
4347
Guy Benyei11169dd2012-12-18 14:30:41 +00004348unsigned clang_visitChildren(CXCursor parent,
4349 CXCursorVisitor visitor,
4350 CXClientData client_data) {
4351 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4352 /*VisitPreprocessorLast=*/false);
4353 return CursorVis.VisitChildren(parent);
4354}
4355
4356#ifndef __has_feature
4357#define __has_feature(x) 0
4358#endif
4359#if __has_feature(blocks)
4360typedef enum CXChildVisitResult
4361 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4362
4363static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4364 CXClientData client_data) {
4365 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4366 return block(cursor, parent);
4367}
4368#else
4369// If we are compiled with a compiler that doesn't have native blocks support,
4370// define and call the block manually, so the
4371typedef struct _CXChildVisitResult
4372{
4373 void *isa;
4374 int flags;
4375 int reserved;
4376 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4377 CXCursor);
4378} *CXCursorVisitorBlock;
4379
4380static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4381 CXClientData client_data) {
4382 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4383 return block->invoke(block, cursor, parent);
4384}
4385#endif
4386
4387
4388unsigned clang_visitChildrenWithBlock(CXCursor parent,
4389 CXCursorVisitorBlock block) {
4390 return clang_visitChildren(parent, visitWithBlock, block);
4391}
4392
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004393static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004395 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004396
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004397 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004399 if (const ObjCPropertyImplDecl *PropImpl =
4400 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004402 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004403
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004404 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004406 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004407
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004408 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 }
4410
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004411 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004412 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004413
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004414 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4416 // and returns different names. NamedDecl returns the class name and
4417 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004418 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004419
4420 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004421 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004422
4423 SmallString<1024> S;
4424 llvm::raw_svector_ostream os(S);
4425 ND->printName(os);
4426
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004427 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004428}
4429
4430CXString clang_getCursorSpelling(CXCursor C) {
4431 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004432 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004433
4434 if (clang_isReference(C.kind)) {
4435 switch (C.kind) {
4436 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004437 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004438 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 }
4440 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004441 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004442 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 }
4444 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004445 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004447 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 }
4449 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004450 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004451 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 }
4453 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004454 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 assert(Type && "Missing type decl");
4456
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004457 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 getAsString());
4459 }
4460 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004461 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 assert(Template && "Missing template decl");
4463
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004464 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 }
4466
4467 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004468 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 assert(NS && "Missing namespace decl");
4470
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004471 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 }
4473
4474 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004475 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 assert(Field && "Missing member decl");
4477
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004478 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 }
4480
4481 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004482 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 assert(Label && "Missing label");
4484
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004485 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004486 }
4487
4488 case CXCursor_OverloadedDeclRef: {
4489 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004490 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4491 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004492 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004493 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004495 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004496 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 OverloadedTemplateStorage *Ovl
4498 = Storage.get<OverloadedTemplateStorage*>();
4499 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004500 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004501 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 }
4503
4504 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004505 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 assert(Var && "Missing variable decl");
4507
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004508 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 }
4510
4511 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004512 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 }
4514 }
4515
4516 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004517 const Expr *E = getCursorExpr(C);
4518
4519 if (C.kind == CXCursor_ObjCStringLiteral ||
4520 C.kind == CXCursor_StringLiteral) {
4521 const StringLiteral *SLit;
4522 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4523 SLit = OSL->getString();
4524 } else {
4525 SLit = cast<StringLiteral>(E);
4526 }
4527 SmallString<256> Buf;
4528 llvm::raw_svector_ostream OS(Buf);
4529 SLit->outputString(OS);
4530 return cxstring::createDup(OS.str());
4531 }
4532
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004533 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 if (D)
4535 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004536 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 }
4538
4539 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004540 const Stmt *S = getCursorStmt(C);
4541 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004542 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004543
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004544 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 }
4546
4547 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004548 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 ->getNameStart());
4550
4551 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004552 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 ->getNameStart());
4554
4555 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004556 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004557
4558 if (clang_isDeclaration(C.kind))
4559 return getDeclSpelling(getCursorDecl(C));
4560
4561 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004562 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004563 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 }
4565
4566 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004567 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004568 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 }
4570
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004571 if (C.kind == CXCursor_PackedAttr) {
4572 return cxstring::createRef("packed");
4573 }
4574
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004575 if (C.kind == CXCursor_VisibilityAttr) {
4576 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4577 switch (AA->getVisibility()) {
4578 case VisibilityAttr::VisibilityType::Default:
4579 return cxstring::createRef("default");
4580 case VisibilityAttr::VisibilityType::Hidden:
4581 return cxstring::createRef("hidden");
4582 case VisibilityAttr::VisibilityType::Protected:
4583 return cxstring::createRef("protected");
4584 }
4585 llvm_unreachable("unknown visibility type");
4586 }
4587
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004588 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004589}
4590
4591CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4592 unsigned pieceIndex,
4593 unsigned options) {
4594 if (clang_Cursor_isNull(C))
4595 return clang_getNullRange();
4596
4597 ASTContext &Ctx = getCursorContext(C);
4598
4599 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004600 const Stmt *S = getCursorStmt(C);
4601 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 if (pieceIndex > 0)
4603 return clang_getNullRange();
4604 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4605 }
4606
4607 return clang_getNullRange();
4608 }
4609
4610 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004611 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4613 if (pieceIndex >= ME->getNumSelectorLocs())
4614 return clang_getNullRange();
4615 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4616 }
4617 }
4618
4619 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4620 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004621 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4623 if (pieceIndex >= MD->getNumSelectorLocs())
4624 return clang_getNullRange();
4625 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4626 }
4627 }
4628
4629 if (C.kind == CXCursor_ObjCCategoryDecl ||
4630 C.kind == CXCursor_ObjCCategoryImplDecl) {
4631 if (pieceIndex > 0)
4632 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004633 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4635 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004636 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4638 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4639 }
4640
4641 if (C.kind == CXCursor_ModuleImportDecl) {
4642 if (pieceIndex > 0)
4643 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004644 if (const ImportDecl *ImportD =
4645 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4647 if (!Locs.empty())
4648 return cxloc::translateSourceRange(Ctx,
4649 SourceRange(Locs.front(), Locs.back()));
4650 }
4651 return clang_getNullRange();
4652 }
4653
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004654 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004655 C.kind == CXCursor_ConversionFunction ||
4656 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004657 if (pieceIndex > 0)
4658 return clang_getNullRange();
4659 if (const FunctionDecl *FD =
4660 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4661 DeclarationNameInfo FunctionName = FD->getNameInfo();
4662 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4663 }
4664 return clang_getNullRange();
4665 }
4666
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 // FIXME: A CXCursor_InclusionDirective should give the location of the
4668 // filename, but we don't keep track of this.
4669
4670 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4671 // but we don't keep track of this.
4672
4673 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4674 // but we don't keep track of this.
4675
4676 // Default handling, give the location of the cursor.
4677
4678 if (pieceIndex > 0)
4679 return clang_getNullRange();
4680
4681 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4682 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4683 return cxloc::translateSourceRange(Ctx, Loc);
4684}
4685
Eli Bendersky44a206f2014-07-31 18:04:56 +00004686CXString clang_Cursor_getMangling(CXCursor C) {
4687 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4688 return cxstring::createEmpty();
4689
Eli Bendersky44a206f2014-07-31 18:04:56 +00004690 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004691 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004692 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4693 return cxstring::createEmpty();
4694
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004695 ASTContext &Ctx = D->getASTContext();
4696 index::CodegenNameGenerator CGNameGen(Ctx);
4697 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004698}
4699
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004700CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4701 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4702 return nullptr;
4703
4704 const Decl *D = getCursorDecl(C);
4705 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4706 return nullptr;
4707
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004708 ASTContext &Ctx = D->getASTContext();
4709 index::CodegenNameGenerator CGNameGen(Ctx);
4710 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004711 return cxstring::createSet(Manglings);
4712}
4713
Dave Lee1a532c92017-09-22 16:58:57 +00004714CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4715 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4716 return nullptr;
4717
4718 const Decl *D = getCursorDecl(C);
4719 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4720 return nullptr;
4721
4722 ASTContext &Ctx = D->getASTContext();
4723 index::CodegenNameGenerator CGNameGen(Ctx);
4724 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4725 return cxstring::createSet(Manglings);
4726}
4727
Jonathan Coe45ef5032018-01-16 10:19:56 +00004728CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4729 if (clang_Cursor_isNull(C))
4730 return 0;
4731 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4732}
4733
4734void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4735 if (Policy)
4736 delete static_cast<PrintingPolicy *>(Policy);
4737}
4738
4739unsigned
4740clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4741 enum CXPrintingPolicyProperty Property) {
4742 if (!Policy)
4743 return 0;
4744
4745 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4746 switch (Property) {
4747 case CXPrintingPolicy_Indentation:
4748 return P->Indentation;
4749 case CXPrintingPolicy_SuppressSpecifiers:
4750 return P->SuppressSpecifiers;
4751 case CXPrintingPolicy_SuppressTagKeyword:
4752 return P->SuppressTagKeyword;
4753 case CXPrintingPolicy_IncludeTagDefinition:
4754 return P->IncludeTagDefinition;
4755 case CXPrintingPolicy_SuppressScope:
4756 return P->SuppressScope;
4757 case CXPrintingPolicy_SuppressUnwrittenScope:
4758 return P->SuppressUnwrittenScope;
4759 case CXPrintingPolicy_SuppressInitializers:
4760 return P->SuppressInitializers;
4761 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4762 return P->ConstantArraySizeAsWritten;
4763 case CXPrintingPolicy_AnonymousTagLocations:
4764 return P->AnonymousTagLocations;
4765 case CXPrintingPolicy_SuppressStrongLifetime:
4766 return P->SuppressStrongLifetime;
4767 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4768 return P->SuppressLifetimeQualifiers;
4769 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4770 return P->SuppressTemplateArgsInCXXConstructors;
4771 case CXPrintingPolicy_Bool:
4772 return P->Bool;
4773 case CXPrintingPolicy_Restrict:
4774 return P->Restrict;
4775 case CXPrintingPolicy_Alignof:
4776 return P->Alignof;
4777 case CXPrintingPolicy_UnderscoreAlignof:
4778 return P->UnderscoreAlignof;
4779 case CXPrintingPolicy_UseVoidForZeroParams:
4780 return P->UseVoidForZeroParams;
4781 case CXPrintingPolicy_TerseOutput:
4782 return P->TerseOutput;
4783 case CXPrintingPolicy_PolishForDeclaration:
4784 return P->PolishForDeclaration;
4785 case CXPrintingPolicy_Half:
4786 return P->Half;
4787 case CXPrintingPolicy_MSWChar:
4788 return P->MSWChar;
4789 case CXPrintingPolicy_IncludeNewlines:
4790 return P->IncludeNewlines;
4791 case CXPrintingPolicy_MSVCFormatting:
4792 return P->MSVCFormatting;
4793 case CXPrintingPolicy_ConstantsAsWritten:
4794 return P->ConstantsAsWritten;
4795 case CXPrintingPolicy_SuppressImplicitBase:
4796 return P->SuppressImplicitBase;
4797 case CXPrintingPolicy_FullyQualifiedName:
4798 return P->FullyQualifiedName;
4799 }
4800
4801 assert(false && "Invalid CXPrintingPolicyProperty");
4802 return 0;
4803}
4804
4805void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4806 enum CXPrintingPolicyProperty Property,
4807 unsigned Value) {
4808 if (!Policy)
4809 return;
4810
4811 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4812 switch (Property) {
4813 case CXPrintingPolicy_Indentation:
4814 P->Indentation = Value;
4815 return;
4816 case CXPrintingPolicy_SuppressSpecifiers:
4817 P->SuppressSpecifiers = Value;
4818 return;
4819 case CXPrintingPolicy_SuppressTagKeyword:
4820 P->SuppressTagKeyword = Value;
4821 return;
4822 case CXPrintingPolicy_IncludeTagDefinition:
4823 P->IncludeTagDefinition = Value;
4824 return;
4825 case CXPrintingPolicy_SuppressScope:
4826 P->SuppressScope = Value;
4827 return;
4828 case CXPrintingPolicy_SuppressUnwrittenScope:
4829 P->SuppressUnwrittenScope = Value;
4830 return;
4831 case CXPrintingPolicy_SuppressInitializers:
4832 P->SuppressInitializers = Value;
4833 return;
4834 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4835 P->ConstantArraySizeAsWritten = Value;
4836 return;
4837 case CXPrintingPolicy_AnonymousTagLocations:
4838 P->AnonymousTagLocations = Value;
4839 return;
4840 case CXPrintingPolicy_SuppressStrongLifetime:
4841 P->SuppressStrongLifetime = Value;
4842 return;
4843 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4844 P->SuppressLifetimeQualifiers = Value;
4845 return;
4846 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4847 P->SuppressTemplateArgsInCXXConstructors = Value;
4848 return;
4849 case CXPrintingPolicy_Bool:
4850 P->Bool = Value;
4851 return;
4852 case CXPrintingPolicy_Restrict:
4853 P->Restrict = Value;
4854 return;
4855 case CXPrintingPolicy_Alignof:
4856 P->Alignof = Value;
4857 return;
4858 case CXPrintingPolicy_UnderscoreAlignof:
4859 P->UnderscoreAlignof = Value;
4860 return;
4861 case CXPrintingPolicy_UseVoidForZeroParams:
4862 P->UseVoidForZeroParams = Value;
4863 return;
4864 case CXPrintingPolicy_TerseOutput:
4865 P->TerseOutput = Value;
4866 return;
4867 case CXPrintingPolicy_PolishForDeclaration:
4868 P->PolishForDeclaration = Value;
4869 return;
4870 case CXPrintingPolicy_Half:
4871 P->Half = Value;
4872 return;
4873 case CXPrintingPolicy_MSWChar:
4874 P->MSWChar = Value;
4875 return;
4876 case CXPrintingPolicy_IncludeNewlines:
4877 P->IncludeNewlines = Value;
4878 return;
4879 case CXPrintingPolicy_MSVCFormatting:
4880 P->MSVCFormatting = Value;
4881 return;
4882 case CXPrintingPolicy_ConstantsAsWritten:
4883 P->ConstantsAsWritten = Value;
4884 return;
4885 case CXPrintingPolicy_SuppressImplicitBase:
4886 P->SuppressImplicitBase = Value;
4887 return;
4888 case CXPrintingPolicy_FullyQualifiedName:
4889 P->FullyQualifiedName = Value;
4890 return;
4891 }
4892
4893 assert(false && "Invalid CXPrintingPolicyProperty");
4894}
4895
4896CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4897 if (clang_Cursor_isNull(C))
4898 return cxstring::createEmpty();
4899
4900 if (clang_isDeclaration(C.kind)) {
4901 const Decl *D = getCursorDecl(C);
4902 if (!D)
4903 return cxstring::createEmpty();
4904
4905 SmallString<128> Str;
4906 llvm::raw_svector_ostream OS(Str);
4907 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4908 D->print(OS, UserPolicy ? *UserPolicy
4909 : getCursorContext(C).getPrintingPolicy());
4910
4911 return cxstring::createDup(OS.str());
4912 }
4913
4914 return cxstring::createEmpty();
4915}
4916
Guy Benyei11169dd2012-12-18 14:30:41 +00004917CXString clang_getCursorDisplayName(CXCursor C) {
4918 if (!clang_isDeclaration(C.kind))
4919 return clang_getCursorSpelling(C);
4920
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004921 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004922 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004923 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004924
4925 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004926 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 D = FunTmpl->getTemplatedDecl();
4928
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004929 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 SmallString<64> Str;
4931 llvm::raw_svector_ostream OS(Str);
4932 OS << *Function;
4933 if (Function->getPrimaryTemplate())
4934 OS << "<>";
4935 OS << "(";
4936 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4937 if (I)
4938 OS << ", ";
4939 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4940 }
4941
4942 if (Function->isVariadic()) {
4943 if (Function->getNumParams())
4944 OS << ", ";
4945 OS << "...";
4946 }
4947 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004948 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 }
4950
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004951 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004952 SmallString<64> Str;
4953 llvm::raw_svector_ostream OS(Str);
4954 OS << *ClassTemplate;
4955 OS << "<";
4956 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4957 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4958 if (I)
4959 OS << ", ";
4960
4961 NamedDecl *Param = Params->getParam(I);
4962 if (Param->getIdentifier()) {
4963 OS << Param->getIdentifier()->getName();
4964 continue;
4965 }
4966
4967 // There is no parameter name, which makes this tricky. Try to come up
4968 // with something useful that isn't too long.
4969 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4970 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4971 else if (NonTypeTemplateParmDecl *NTTP
4972 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4973 OS << NTTP->getType().getAsString(Policy);
4974 else
4975 OS << "template<...> class";
4976 }
4977
4978 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004979 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004980 }
4981
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004982 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4984 // If the type was explicitly written, use that.
4985 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004986 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004987
Benjamin Kramer9170e912013-02-22 15:46:01 +00004988 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004989 llvm::raw_svector_ostream OS(Str);
4990 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00004991 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
4992 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004993 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004994 }
4995
4996 return clang_getCursorSpelling(C);
4997}
4998
4999CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5000 switch (Kind) {
5001 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005002 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005004 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005006 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005008 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005010 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005012 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005014 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005016 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005018 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005020 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005022 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005024 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005026 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005028 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005030 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005032 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005034 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005036 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005038 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005040 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005042 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005065 case CXCursor_FixedPointLiteral:
5066 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005081 case CXCursor_OMPArraySectionExpr:
5082 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005094 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005133 case CXCursor_ObjCAvailabilityCheckExpr:
5134 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005135 case CXCursor_ObjCSelfExpr:
5136 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005225 case CXCursor_SEHLeaveStmt:
5226 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005255 case CXCursor_PackedAttr:
5256 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005257 case CXCursor_PureAttr:
5258 return cxstring::createRef("attribute(pure)");
5259 case CXCursor_ConstAttr:
5260 return cxstring::createRef("attribute(const)");
5261 case CXCursor_NoDuplicateAttr:
5262 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005263 case CXCursor_CUDAConstantAttr:
5264 return cxstring::createRef("attribute(constant)");
5265 case CXCursor_CUDADeviceAttr:
5266 return cxstring::createRef("attribute(device)");
5267 case CXCursor_CUDAGlobalAttr:
5268 return cxstring::createRef("attribute(global)");
5269 case CXCursor_CUDAHostAttr:
5270 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005271 case CXCursor_CUDASharedAttr:
5272 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005273 case CXCursor_VisibilityAttr:
5274 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005275 case CXCursor_DLLExport:
5276 return cxstring::createRef("attribute(dllexport)");
5277 case CXCursor_DLLImport:
5278 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005280 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005282 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005284 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005286 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005288 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005290 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005292 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005294 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005295 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005296 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005298 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005300 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005301 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005302 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005303 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005304 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005305 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005306 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005307 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005308 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005309 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005310 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005312 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005313 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005314 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005316 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005317 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005318 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005319 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005320 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005321 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005322 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005323 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005324 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005325 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005326 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005327 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005328 return cxstring::createRef("OMPParallelDirective");
5329 case CXCursor_OMPSimdDirective:
5330 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005331 case CXCursor_OMPForDirective:
5332 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005333 case CXCursor_OMPForSimdDirective:
5334 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005335 case CXCursor_OMPSectionsDirective:
5336 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005337 case CXCursor_OMPSectionDirective:
5338 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005339 case CXCursor_OMPSingleDirective:
5340 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005341 case CXCursor_OMPMasterDirective:
5342 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005343 case CXCursor_OMPCriticalDirective:
5344 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005345 case CXCursor_OMPParallelForDirective:
5346 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005347 case CXCursor_OMPParallelForSimdDirective:
5348 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005349 case CXCursor_OMPParallelSectionsDirective:
5350 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005351 case CXCursor_OMPTaskDirective:
5352 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005353 case CXCursor_OMPTaskyieldDirective:
5354 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005355 case CXCursor_OMPBarrierDirective:
5356 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005357 case CXCursor_OMPTaskwaitDirective:
5358 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005359 case CXCursor_OMPTaskgroupDirective:
5360 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005361 case CXCursor_OMPFlushDirective:
5362 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005363 case CXCursor_OMPOrderedDirective:
5364 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005365 case CXCursor_OMPAtomicDirective:
5366 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005367 case CXCursor_OMPTargetDirective:
5368 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005369 case CXCursor_OMPTargetDataDirective:
5370 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005371 case CXCursor_OMPTargetEnterDataDirective:
5372 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005373 case CXCursor_OMPTargetExitDataDirective:
5374 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005375 case CXCursor_OMPTargetParallelDirective:
5376 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005377 case CXCursor_OMPTargetParallelForDirective:
5378 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005379 case CXCursor_OMPTargetUpdateDirective:
5380 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005381 case CXCursor_OMPTeamsDirective:
5382 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005383 case CXCursor_OMPCancellationPointDirective:
5384 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005385 case CXCursor_OMPCancelDirective:
5386 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005387 case CXCursor_OMPTaskLoopDirective:
5388 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005389 case CXCursor_OMPTaskLoopSimdDirective:
5390 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005391 case CXCursor_OMPDistributeDirective:
5392 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005393 case CXCursor_OMPDistributeParallelForDirective:
5394 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005395 case CXCursor_OMPDistributeParallelForSimdDirective:
5396 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005397 case CXCursor_OMPDistributeSimdDirective:
5398 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005399 case CXCursor_OMPTargetParallelForSimdDirective:
5400 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005401 case CXCursor_OMPTargetSimdDirective:
5402 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005403 case CXCursor_OMPTeamsDistributeDirective:
5404 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005405 case CXCursor_OMPTeamsDistributeSimdDirective:
5406 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005407 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5408 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005409 case CXCursor_OMPTeamsDistributeParallelForDirective:
5410 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005411 case CXCursor_OMPTargetTeamsDirective:
5412 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005413 case CXCursor_OMPTargetTeamsDistributeDirective:
5414 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005415 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5416 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005417 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5418 return cxstring::createRef(
5419 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005420 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5421 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005422 case CXCursor_OverloadCandidate:
5423 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005424 case CXCursor_TypeAliasTemplateDecl:
5425 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005426 case CXCursor_StaticAssert:
5427 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005428 case CXCursor_FriendDecl:
5429 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 }
5431
5432 llvm_unreachable("Unhandled CXCursorKind");
5433}
5434
5435struct GetCursorData {
5436 SourceLocation TokenBeginLoc;
5437 bool PointsAtMacroArgExpansion;
5438 bool VisitedObjCPropertyImplDecl;
5439 SourceLocation VisitedDeclaratorDeclStartLoc;
5440 CXCursor &BestCursor;
5441
5442 GetCursorData(SourceManager &SM,
5443 SourceLocation tokenBegin, CXCursor &outputCursor)
5444 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5445 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5446 VisitedObjCPropertyImplDecl = false;
5447 }
5448};
5449
5450static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5451 CXCursor parent,
5452 CXClientData client_data) {
5453 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5454 CXCursor *BestCursor = &Data->BestCursor;
5455
5456 // If we point inside a macro argument we should provide info of what the
5457 // token is so use the actual cursor, don't replace it with a macro expansion
5458 // cursor.
5459 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5460 return CXChildVisit_Recurse;
5461
5462 if (clang_isDeclaration(cursor.kind)) {
5463 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005464 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005465 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5466 if (MD->isImplicit())
5467 return CXChildVisit_Break;
5468
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005469 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005470 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5471 // Check that when we have multiple @class references in the same line,
5472 // that later ones do not override the previous ones.
5473 // If we have:
5474 // @class Foo, Bar;
5475 // source ranges for both start at '@', so 'Bar' will end up overriding
5476 // 'Foo' even though the cursor location was at 'Foo'.
5477 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5478 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005479 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005480 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5481 if (PrevID != ID &&
5482 !PrevID->isThisDeclarationADefinition() &&
5483 !ID->isThisDeclarationADefinition())
5484 return CXChildVisit_Break;
5485 }
5486
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005487 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005488 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5489 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5490 // Check that when we have multiple declarators in the same line,
5491 // that later ones do not override the previous ones.
5492 // If we have:
5493 // int Foo, Bar;
5494 // source ranges for both start at 'int', so 'Bar' will end up overriding
5495 // 'Foo' even though the cursor location was at 'Foo'.
5496 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5497 return CXChildVisit_Break;
5498 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5499
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005500 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005501 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5502 (void)PropImp;
5503 // Check that when we have multiple @synthesize in the same line,
5504 // that later ones do not override the previous ones.
5505 // If we have:
5506 // @synthesize Foo, Bar;
5507 // source ranges for both start at '@', so 'Bar' will end up overriding
5508 // 'Foo' even though the cursor location was at 'Foo'.
5509 if (Data->VisitedObjCPropertyImplDecl)
5510 return CXChildVisit_Break;
5511 Data->VisitedObjCPropertyImplDecl = true;
5512 }
5513 }
5514
5515 if (clang_isExpression(cursor.kind) &&
5516 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005517 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 // Avoid having the cursor of an expression replace the declaration cursor
5519 // when the expression source range overlaps the declaration range.
5520 // This can happen for C++ constructor expressions whose range generally
5521 // include the variable declaration, e.g.:
5522 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5523 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5524 D->getLocation() == Data->TokenBeginLoc)
5525 return CXChildVisit_Break;
5526 }
5527 }
5528
5529 // If our current best cursor is the construction of a temporary object,
5530 // don't replace that cursor with a type reference, because we want
5531 // clang_getCursor() to point at the constructor.
5532 if (clang_isExpression(BestCursor->kind) &&
5533 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5534 cursor.kind == CXCursor_TypeRef) {
5535 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5536 // as having the actual point on the type reference.
5537 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5538 return CXChildVisit_Recurse;
5539 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005540
5541 // If we already have an Objective-C superclass reference, don't
5542 // update it further.
5543 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5544 return CXChildVisit_Break;
5545
Guy Benyei11169dd2012-12-18 14:30:41 +00005546 *BestCursor = cursor;
5547 return CXChildVisit_Recurse;
5548}
5549
5550CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005551 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005552 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005553 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005554 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005555
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005556 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005557 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5558
5559 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5560 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5561
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005562 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005563 CXFile SearchFile;
5564 unsigned SearchLine, SearchColumn;
5565 CXFile ResultFile;
5566 unsigned ResultLine, ResultColumn;
5567 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5568 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5569 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005570
5571 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5572 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005573 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005574 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005575 SearchFileName = clang_getFileName(SearchFile);
5576 ResultFileName = clang_getFileName(ResultFile);
5577 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5578 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005579 *Log << llvm::format("(%s:%d:%d) = %s",
5580 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5581 clang_getCString(KindSpelling))
5582 << llvm::format("(%s:%d:%d):%s%s",
5583 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5584 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005585 clang_disposeString(SearchFileName);
5586 clang_disposeString(ResultFileName);
5587 clang_disposeString(KindSpelling);
5588 clang_disposeString(USR);
5589
5590 CXCursor Definition = clang_getCursorDefinition(Result);
5591 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5592 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5593 CXString DefinitionKindSpelling
5594 = clang_getCursorKindSpelling(Definition.kind);
5595 CXFile DefinitionFile;
5596 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005597 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005598 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005599 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005600 *Log << llvm::format(" -> %s(%s:%d:%d)",
5601 clang_getCString(DefinitionKindSpelling),
5602 clang_getCString(DefinitionFileName),
5603 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005604 clang_disposeString(DefinitionFileName);
5605 clang_disposeString(DefinitionKindSpelling);
5606 }
5607 }
5608
5609 return Result;
5610}
5611
5612CXCursor clang_getNullCursor(void) {
5613 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5614}
5615
5616unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005617 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5618 // can't set consistently. For example, when visiting a DeclStmt we will set
5619 // it but we don't set it on the result of clang_getCursorDefinition for
5620 // a reference of the same declaration.
5621 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5622 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5623 // to provide that kind of info.
5624 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005625 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005626 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005627 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005628
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 return X == Y;
5630}
5631
5632unsigned clang_hashCursor(CXCursor C) {
5633 unsigned Index = 0;
5634 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5635 Index = 1;
5636
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005637 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005638 std::make_pair(C.kind, C.data[Index]));
5639}
5640
5641unsigned clang_isInvalid(enum CXCursorKind K) {
5642 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5643}
5644
5645unsigned clang_isDeclaration(enum CXCursorKind K) {
5646 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005647 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5648}
5649
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005650unsigned clang_isInvalidDeclaration(CXCursor C) {
5651 if (clang_isDeclaration(C.kind)) {
5652 if (const Decl *D = getCursorDecl(C))
5653 return D->isInvalidDecl();
5654 }
5655
5656 return 0;
5657}
5658
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005659unsigned clang_isReference(enum CXCursorKind K) {
5660 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5661}
Guy Benyei11169dd2012-12-18 14:30:41 +00005662
5663unsigned clang_isExpression(enum CXCursorKind K) {
5664 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5665}
5666
5667unsigned clang_isStatement(enum CXCursorKind K) {
5668 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5669}
5670
5671unsigned clang_isAttribute(enum CXCursorKind K) {
5672 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5673}
5674
5675unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5676 return K == CXCursor_TranslationUnit;
5677}
5678
5679unsigned clang_isPreprocessing(enum CXCursorKind K) {
5680 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5681}
5682
5683unsigned clang_isUnexposed(enum CXCursorKind K) {
5684 switch (K) {
5685 case CXCursor_UnexposedDecl:
5686 case CXCursor_UnexposedExpr:
5687 case CXCursor_UnexposedStmt:
5688 case CXCursor_UnexposedAttr:
5689 return true;
5690 default:
5691 return false;
5692 }
5693}
5694
5695CXCursorKind clang_getCursorKind(CXCursor C) {
5696 return C.kind;
5697}
5698
5699CXSourceLocation clang_getCursorLocation(CXCursor C) {
5700 if (clang_isReference(C.kind)) {
5701 switch (C.kind) {
5702 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005703 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005704 = getCursorObjCSuperClassRef(C);
5705 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5706 }
5707
5708 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005709 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005710 = getCursorObjCProtocolRef(C);
5711 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5712 }
5713
5714 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005715 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005716 = getCursorObjCClassRef(C);
5717 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5718 }
5719
5720 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005721 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005722 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5723 }
5724
5725 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005726 std::pair<const TemplateDecl *, SourceLocation> P =
5727 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005728 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5729 }
5730
5731 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005732 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005733 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5734 }
5735
5736 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005737 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005738 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5739 }
5740
5741 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005742 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005743 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5744 }
5745
5746 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005747 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005748 if (!BaseSpec)
5749 return clang_getNullLocation();
5750
5751 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5752 return cxloc::translateSourceLocation(getCursorContext(C),
5753 TSInfo->getTypeLoc().getBeginLoc());
5754
5755 return cxloc::translateSourceLocation(getCursorContext(C),
5756 BaseSpec->getLocStart());
5757 }
5758
5759 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005760 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005761 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5762 }
5763
5764 case CXCursor_OverloadedDeclRef:
5765 return cxloc::translateSourceLocation(getCursorContext(C),
5766 getCursorOverloadedDeclRef(C).second);
5767
5768 default:
5769 // FIXME: Need a way to enumerate all non-reference cases.
5770 llvm_unreachable("Missed a reference kind");
5771 }
5772 }
5773
5774 if (clang_isExpression(C.kind))
5775 return cxloc::translateSourceLocation(getCursorContext(C),
5776 getLocationFromExpr(getCursorExpr(C)));
5777
5778 if (clang_isStatement(C.kind))
5779 return cxloc::translateSourceLocation(getCursorContext(C),
5780 getCursorStmt(C)->getLocStart());
5781
5782 if (C.kind == CXCursor_PreprocessingDirective) {
5783 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5784 return cxloc::translateSourceLocation(getCursorContext(C), L);
5785 }
5786
5787 if (C.kind == CXCursor_MacroExpansion) {
5788 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005789 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005790 return cxloc::translateSourceLocation(getCursorContext(C), L);
5791 }
5792
5793 if (C.kind == CXCursor_MacroDefinition) {
5794 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5795 return cxloc::translateSourceLocation(getCursorContext(C), L);
5796 }
5797
5798 if (C.kind == CXCursor_InclusionDirective) {
5799 SourceLocation L
5800 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5801 return cxloc::translateSourceLocation(getCursorContext(C), L);
5802 }
5803
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005804 if (clang_isAttribute(C.kind)) {
5805 SourceLocation L
5806 = cxcursor::getCursorAttr(C)->getLocation();
5807 return cxloc::translateSourceLocation(getCursorContext(C), L);
5808 }
5809
Guy Benyei11169dd2012-12-18 14:30:41 +00005810 if (!clang_isDeclaration(C.kind))
5811 return clang_getNullLocation();
5812
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005813 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005814 if (!D)
5815 return clang_getNullLocation();
5816
5817 SourceLocation Loc = D->getLocation();
5818 // FIXME: Multiple variables declared in a single declaration
5819 // currently lack the information needed to correctly determine their
5820 // ranges when accounting for the type-specifier. We use context
5821 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5822 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005823 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005824 if (!cxcursor::isFirstInDeclGroup(C))
5825 Loc = VD->getLocation();
5826 }
5827
5828 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005829 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005830 Loc = MD->getSelectorStartLoc();
5831
5832 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5833}
5834
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005835} // end extern "C"
5836
Guy Benyei11169dd2012-12-18 14:30:41 +00005837CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5838 assert(TU);
5839
5840 // Guard against an invalid SourceLocation, or we may assert in one
5841 // of the following calls.
5842 if (SLoc.isInvalid())
5843 return clang_getNullCursor();
5844
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005845 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005846
5847 // Translate the given source location to make it point at the beginning of
5848 // the token under the cursor.
5849 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5850 CXXUnit->getASTContext().getLangOpts());
5851
5852 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5853 if (SLoc.isValid()) {
5854 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5855 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5856 /*VisitPreprocessorLast=*/true,
5857 /*VisitIncludedEntities=*/false,
5858 SourceLocation(SLoc));
5859 CursorVis.visitFileRegion();
5860 }
5861
5862 return Result;
5863}
5864
5865static SourceRange getRawCursorExtent(CXCursor C) {
5866 if (clang_isReference(C.kind)) {
5867 switch (C.kind) {
5868 case CXCursor_ObjCSuperClassRef:
5869 return getCursorObjCSuperClassRef(C).second;
5870
5871 case CXCursor_ObjCProtocolRef:
5872 return getCursorObjCProtocolRef(C).second;
5873
5874 case CXCursor_ObjCClassRef:
5875 return getCursorObjCClassRef(C).second;
5876
5877 case CXCursor_TypeRef:
5878 return getCursorTypeRef(C).second;
5879
5880 case CXCursor_TemplateRef:
5881 return getCursorTemplateRef(C).second;
5882
5883 case CXCursor_NamespaceRef:
5884 return getCursorNamespaceRef(C).second;
5885
5886 case CXCursor_MemberRef:
5887 return getCursorMemberRef(C).second;
5888
5889 case CXCursor_CXXBaseSpecifier:
5890 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5891
5892 case CXCursor_LabelRef:
5893 return getCursorLabelRef(C).second;
5894
5895 case CXCursor_OverloadedDeclRef:
5896 return getCursorOverloadedDeclRef(C).second;
5897
5898 case CXCursor_VariableRef:
5899 return getCursorVariableRef(C).second;
5900
5901 default:
5902 // FIXME: Need a way to enumerate all non-reference cases.
5903 llvm_unreachable("Missed a reference kind");
5904 }
5905 }
5906
5907 if (clang_isExpression(C.kind))
5908 return getCursorExpr(C)->getSourceRange();
5909
5910 if (clang_isStatement(C.kind))
5911 return getCursorStmt(C)->getSourceRange();
5912
5913 if (clang_isAttribute(C.kind))
5914 return getCursorAttr(C)->getRange();
5915
5916 if (C.kind == CXCursor_PreprocessingDirective)
5917 return cxcursor::getCursorPreprocessingDirective(C);
5918
5919 if (C.kind == CXCursor_MacroExpansion) {
5920 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005921 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005922 return TU->mapRangeFromPreamble(Range);
5923 }
5924
5925 if (C.kind == CXCursor_MacroDefinition) {
5926 ASTUnit *TU = getCursorASTUnit(C);
5927 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5928 return TU->mapRangeFromPreamble(Range);
5929 }
5930
5931 if (C.kind == CXCursor_InclusionDirective) {
5932 ASTUnit *TU = getCursorASTUnit(C);
5933 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5934 return TU->mapRangeFromPreamble(Range);
5935 }
5936
5937 if (C.kind == CXCursor_TranslationUnit) {
5938 ASTUnit *TU = getCursorASTUnit(C);
5939 FileID MainID = TU->getSourceManager().getMainFileID();
5940 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5941 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5942 return SourceRange(Start, End);
5943 }
5944
5945 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005946 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005947 if (!D)
5948 return SourceRange();
5949
5950 SourceRange R = D->getSourceRange();
5951 // FIXME: Multiple variables declared in a single declaration
5952 // currently lack the information needed to correctly determine their
5953 // ranges when accounting for the type-specifier. We use context
5954 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5955 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005956 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005957 if (!cxcursor::isFirstInDeclGroup(C))
5958 R.setBegin(VD->getLocation());
5959 }
5960 return R;
5961 }
5962 return SourceRange();
5963}
5964
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005965/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00005966/// the decl-specifier-seq for declarations.
5967static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5968 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005969 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 if (!D)
5971 return SourceRange();
5972
5973 SourceRange R = D->getSourceRange();
5974
5975 // Adjust the start of the location for declarations preceded by
5976 // declaration specifiers.
5977 SourceLocation StartLoc;
5978 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5979 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5980 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005981 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005982 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5983 StartLoc = TI->getTypeLoc().getLocStart();
5984 }
5985
5986 if (StartLoc.isValid() && R.getBegin().isValid() &&
5987 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5988 R.setBegin(StartLoc);
5989
5990 // FIXME: Multiple variables declared in a single declaration
5991 // currently lack the information needed to correctly determine their
5992 // ranges when accounting for the type-specifier. We use context
5993 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5994 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005995 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005996 if (!cxcursor::isFirstInDeclGroup(C))
5997 R.setBegin(VD->getLocation());
5998 }
5999
6000 return R;
6001 }
6002
6003 return getRawCursorExtent(C);
6004}
6005
Guy Benyei11169dd2012-12-18 14:30:41 +00006006CXSourceRange clang_getCursorExtent(CXCursor C) {
6007 SourceRange R = getRawCursorExtent(C);
6008 if (R.isInvalid())
6009 return clang_getNullRange();
6010
6011 return cxloc::translateSourceRange(getCursorContext(C), R);
6012}
6013
6014CXCursor clang_getCursorReferenced(CXCursor C) {
6015 if (clang_isInvalid(C.kind))
6016 return clang_getNullCursor();
6017
6018 CXTranslationUnit tu = getCursorTU(C);
6019 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006020 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006021 if (!D)
6022 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006023 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006024 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006025 if (const ObjCPropertyImplDecl *PropImpl =
6026 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006027 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6028 return MakeCXCursor(Property, tu);
6029
6030 return C;
6031 }
6032
6033 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006034 const Expr *E = getCursorExpr(C);
6035 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006036 if (D) {
6037 CXCursor declCursor = MakeCXCursor(D, tu);
6038 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6039 declCursor);
6040 return declCursor;
6041 }
6042
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006043 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006044 return MakeCursorOverloadedDeclRef(Ovl, tu);
6045
6046 return clang_getNullCursor();
6047 }
6048
6049 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006050 const Stmt *S = getCursorStmt(C);
6051 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006052 if (LabelDecl *label = Goto->getLabel())
6053 if (LabelStmt *labelS = label->getStmt())
6054 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6055
6056 return clang_getNullCursor();
6057 }
Richard Smith66a81862015-05-04 02:25:31 +00006058
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006060 if (const MacroDefinitionRecord *Def =
6061 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006062 return MakeMacroDefinitionCursor(Def, tu);
6063 }
6064
6065 if (!clang_isReference(C.kind))
6066 return clang_getNullCursor();
6067
6068 switch (C.kind) {
6069 case CXCursor_ObjCSuperClassRef:
6070 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6071
6072 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006073 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6074 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 return MakeCXCursor(Def, tu);
6076
6077 return MakeCXCursor(Prot, tu);
6078 }
6079
6080 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006081 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6082 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006083 return MakeCXCursor(Def, tu);
6084
6085 return MakeCXCursor(Class, tu);
6086 }
6087
6088 case CXCursor_TypeRef:
6089 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6090
6091 case CXCursor_TemplateRef:
6092 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6093
6094 case CXCursor_NamespaceRef:
6095 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6096
6097 case CXCursor_MemberRef:
6098 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6099
6100 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006101 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006102 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6103 tu ));
6104 }
6105
6106 case CXCursor_LabelRef:
6107 // FIXME: We end up faking the "parent" declaration here because we
6108 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006109 return MakeCXCursor(getCursorLabelRef(C).first,
6110 cxtu::getASTUnit(tu)->getASTContext()
6111 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006112 tu);
6113
6114 case CXCursor_OverloadedDeclRef:
6115 return C;
6116
6117 case CXCursor_VariableRef:
6118 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6119
6120 default:
6121 // We would prefer to enumerate all non-reference cursor kinds here.
6122 llvm_unreachable("Unhandled reference cursor kind");
6123 }
6124}
6125
6126CXCursor clang_getCursorDefinition(CXCursor C) {
6127 if (clang_isInvalid(C.kind))
6128 return clang_getNullCursor();
6129
6130 CXTranslationUnit TU = getCursorTU(C);
6131
6132 bool WasReference = false;
6133 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6134 C = clang_getCursorReferenced(C);
6135 WasReference = true;
6136 }
6137
6138 if (C.kind == CXCursor_MacroExpansion)
6139 return clang_getCursorReferenced(C);
6140
6141 if (!clang_isDeclaration(C.kind))
6142 return clang_getNullCursor();
6143
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006144 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 if (!D)
6146 return clang_getNullCursor();
6147
6148 switch (D->getKind()) {
6149 // Declaration kinds that don't really separate the notions of
6150 // declaration and definition.
6151 case Decl::Namespace:
6152 case Decl::Typedef:
6153 case Decl::TypeAlias:
6154 case Decl::TypeAliasTemplate:
6155 case Decl::TemplateTypeParm:
6156 case Decl::EnumConstant:
6157 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006158 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006159 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006160 case Decl::IndirectField:
6161 case Decl::ObjCIvar:
6162 case Decl::ObjCAtDefsField:
6163 case Decl::ImplicitParam:
6164 case Decl::ParmVar:
6165 case Decl::NonTypeTemplateParm:
6166 case Decl::TemplateTemplateParm:
6167 case Decl::ObjCCategoryImpl:
6168 case Decl::ObjCImplementation:
6169 case Decl::AccessSpec:
6170 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006171 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006172 case Decl::ObjCPropertyImpl:
6173 case Decl::FileScopeAsm:
6174 case Decl::StaticAssert:
6175 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006176 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006177 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 case Decl::Label: // FIXME: Is this right??
6179 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006180 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006182 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006183 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006184 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006185 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006186 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006187 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006188 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006189 return C;
6190
6191 // Declaration kinds that don't make any sense here, but are
6192 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006193 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006194 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006195 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 break;
6197
6198 // Declaration kinds for which the definition is not resolvable.
6199 case Decl::UnresolvedUsingTypename:
6200 case Decl::UnresolvedUsingValue:
6201 break;
6202
6203 case Decl::UsingDirective:
6204 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6205 TU);
6206
6207 case Decl::NamespaceAlias:
6208 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6209
6210 case Decl::Enum:
6211 case Decl::Record:
6212 case Decl::CXXRecord:
6213 case Decl::ClassTemplateSpecialization:
6214 case Decl::ClassTemplatePartialSpecialization:
6215 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6216 return MakeCXCursor(Def, TU);
6217 return clang_getNullCursor();
6218
6219 case Decl::Function:
6220 case Decl::CXXMethod:
6221 case Decl::CXXConstructor:
6222 case Decl::CXXDestructor:
6223 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006224 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006225 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006226 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006227 return clang_getNullCursor();
6228 }
6229
Larisse Voufo39a1e502013-08-06 01:03:05 +00006230 case Decl::Var:
6231 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006232 case Decl::VarTemplatePartialSpecialization:
6233 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006235 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006236 return MakeCXCursor(Def, TU);
6237 return clang_getNullCursor();
6238 }
6239
6240 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006241 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006242 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6243 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6244 return clang_getNullCursor();
6245 }
6246
6247 case Decl::ClassTemplate: {
6248 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6249 ->getDefinition())
6250 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6251 TU);
6252 return clang_getNullCursor();
6253 }
6254
Larisse Voufo39a1e502013-08-06 01:03:05 +00006255 case Decl::VarTemplate: {
6256 if (VarDecl *Def =
6257 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6258 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6259 return clang_getNullCursor();
6260 }
6261
Guy Benyei11169dd2012-12-18 14:30:41 +00006262 case Decl::Using:
6263 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6264 D->getLocation(), TU);
6265
6266 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006267 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006268 return clang_getCursorDefinition(
6269 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6270 TU));
6271
6272 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006273 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006274 if (Method->isThisDeclarationADefinition())
6275 return C;
6276
6277 // Dig out the method definition in the associated
6278 // @implementation, if we have it.
6279 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006280 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006281 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6282 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6283 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6284 Method->isInstanceMethod()))
6285 if (Def->isThisDeclarationADefinition())
6286 return MakeCXCursor(Def, TU);
6287
6288 return clang_getNullCursor();
6289 }
6290
6291 case Decl::ObjCCategory:
6292 if (ObjCCategoryImplDecl *Impl
6293 = cast<ObjCCategoryDecl>(D)->getImplementation())
6294 return MakeCXCursor(Impl, TU);
6295 return clang_getNullCursor();
6296
6297 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006298 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006299 return MakeCXCursor(Def, TU);
6300 return clang_getNullCursor();
6301
6302 case Decl::ObjCInterface: {
6303 // There are two notions of a "definition" for an Objective-C
6304 // class: the interface and its implementation. When we resolved a
6305 // reference to an Objective-C class, produce the @interface as
6306 // the definition; when we were provided with the interface,
6307 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006308 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006309 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006310 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006311 return MakeCXCursor(Def, TU);
6312 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6313 return MakeCXCursor(Impl, TU);
6314 return clang_getNullCursor();
6315 }
6316
6317 case Decl::ObjCProperty:
6318 // FIXME: We don't really know where to find the
6319 // ObjCPropertyImplDecls that implement this property.
6320 return clang_getNullCursor();
6321
6322 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006323 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006324 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006325 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006326 return MakeCXCursor(Def, TU);
6327
6328 return clang_getNullCursor();
6329
6330 case Decl::Friend:
6331 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6332 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6333 return clang_getNullCursor();
6334
6335 case Decl::FriendTemplate:
6336 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6337 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6338 return clang_getNullCursor();
6339 }
6340
6341 return clang_getNullCursor();
6342}
6343
6344unsigned clang_isCursorDefinition(CXCursor C) {
6345 if (!clang_isDeclaration(C.kind))
6346 return 0;
6347
6348 return clang_getCursorDefinition(C) == C;
6349}
6350
6351CXCursor clang_getCanonicalCursor(CXCursor C) {
6352 if (!clang_isDeclaration(C.kind))
6353 return C;
6354
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006355 if (const Decl *D = getCursorDecl(C)) {
6356 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006357 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6358 return MakeCXCursor(CatD, getCursorTU(C));
6359
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006360 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6361 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006362 return MakeCXCursor(IFD, getCursorTU(C));
6363
6364 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6365 }
6366
6367 return C;
6368}
6369
6370int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6371 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6372}
6373
6374unsigned clang_getNumOverloadedDecls(CXCursor C) {
6375 if (C.kind != CXCursor_OverloadedDeclRef)
6376 return 0;
6377
6378 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006379 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 return E->getNumDecls();
6381
6382 if (OverloadedTemplateStorage *S
6383 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6384 return S->size();
6385
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006386 const Decl *D = Storage.get<const Decl *>();
6387 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006388 return Using->shadow_size();
6389
6390 return 0;
6391}
6392
6393CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6394 if (cursor.kind != CXCursor_OverloadedDeclRef)
6395 return clang_getNullCursor();
6396
6397 if (index >= clang_getNumOverloadedDecls(cursor))
6398 return clang_getNullCursor();
6399
6400 CXTranslationUnit TU = getCursorTU(cursor);
6401 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006402 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 return MakeCXCursor(E->decls_begin()[index], TU);
6404
6405 if (OverloadedTemplateStorage *S
6406 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6407 return MakeCXCursor(S->begin()[index], TU);
6408
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006409 const Decl *D = Storage.get<const Decl *>();
6410 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006411 // FIXME: This is, unfortunately, linear time.
6412 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6413 std::advance(Pos, index);
6414 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6415 }
6416
6417 return clang_getNullCursor();
6418}
6419
6420void clang_getDefinitionSpellingAndExtent(CXCursor C,
6421 const char **startBuf,
6422 const char **endBuf,
6423 unsigned *startLine,
6424 unsigned *startColumn,
6425 unsigned *endLine,
6426 unsigned *endColumn) {
6427 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006428 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006429 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6430
6431 SourceManager &SM = FD->getASTContext().getSourceManager();
6432 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6433 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6434 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6435 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6436 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6437 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6438}
6439
6440
6441CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6442 unsigned PieceIndex) {
6443 RefNamePieces Pieces;
6444
6445 switch (C.kind) {
6446 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006447 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006448 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6449 E->getQualifierLoc().getSourceRange());
6450 break;
6451
6452 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006453 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6454 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6455 Pieces =
6456 buildPieces(NameFlags, false, E->getNameInfo(),
6457 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6458 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006459 break;
6460
6461 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006462 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006463 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006464 const Expr *Callee = OCE->getCallee();
6465 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006466 Callee = ICE->getSubExpr();
6467
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006468 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006469 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6470 DRE->getQualifierLoc().getSourceRange());
6471 }
6472 break;
6473
6474 default:
6475 break;
6476 }
6477
6478 if (Pieces.empty()) {
6479 if (PieceIndex == 0)
6480 return clang_getCursorExtent(C);
6481 } else if (PieceIndex < Pieces.size()) {
6482 SourceRange R = Pieces[PieceIndex];
6483 if (R.isValid())
6484 return cxloc::translateSourceRange(getCursorContext(C), R);
6485 }
6486
6487 return clang_getNullRange();
6488}
6489
6490void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006491 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6492 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006493}
6494
6495void clang_executeOnThread(void (*fn)(void*), void *user_data,
6496 unsigned stack_size) {
6497 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6498}
6499
Guy Benyei11169dd2012-12-18 14:30:41 +00006500//===----------------------------------------------------------------------===//
6501// Token-based Operations.
6502//===----------------------------------------------------------------------===//
6503
6504/* CXToken layout:
6505 * int_data[0]: a CXTokenKind
6506 * int_data[1]: starting token location
6507 * int_data[2]: token length
6508 * int_data[3]: reserved
6509 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6510 * otherwise unused.
6511 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006512CXTokenKind clang_getTokenKind(CXToken CXTok) {
6513 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6514}
6515
6516CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6517 switch (clang_getTokenKind(CXTok)) {
6518 case CXToken_Identifier:
6519 case CXToken_Keyword:
6520 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006521 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 ->getNameStart());
6523
6524 case CXToken_Literal: {
6525 // We have stashed the starting pointer in the ptr_data field. Use it.
6526 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006527 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006528 }
6529
6530 case CXToken_Punctuation:
6531 case CXToken_Comment:
6532 break;
6533 }
6534
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006535 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006536 LOG_BAD_TU(TU);
6537 return cxstring::createEmpty();
6538 }
6539
Guy Benyei11169dd2012-12-18 14:30:41 +00006540 // We have to find the starting buffer pointer the hard way, by
6541 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006542 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006543 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006544 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006545
6546 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6547 std::pair<FileID, unsigned> LocInfo
6548 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6549 bool Invalid = false;
6550 StringRef Buffer
6551 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6552 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006553 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006554
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006555 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006556}
6557
6558CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006559 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006560 LOG_BAD_TU(TU);
6561 return clang_getNullLocation();
6562 }
6563
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006564 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006565 if (!CXXUnit)
6566 return clang_getNullLocation();
6567
6568 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6569 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6570}
6571
6572CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006573 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006574 LOG_BAD_TU(TU);
6575 return clang_getNullRange();
6576 }
6577
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006578 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006579 if (!CXXUnit)
6580 return clang_getNullRange();
6581
6582 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6583 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6584}
6585
6586static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6587 SmallVectorImpl<CXToken> &CXTokens) {
6588 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6589 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006590 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006591 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006592 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006593
6594 // Cannot tokenize across files.
6595 if (BeginLocInfo.first != EndLocInfo.first)
6596 return;
6597
6598 // Create a lexer
6599 bool Invalid = false;
6600 StringRef Buffer
6601 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6602 if (Invalid)
6603 return;
6604
6605 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6606 CXXUnit->getASTContext().getLangOpts(),
6607 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6608 Lex.SetCommentRetentionState(true);
6609
6610 // Lex tokens until we hit the end of the range.
6611 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6612 Token Tok;
6613 bool previousWasAt = false;
6614 do {
6615 // Lex the next token
6616 Lex.LexFromRawLexer(Tok);
6617 if (Tok.is(tok::eof))
6618 break;
6619
6620 // Initialize the CXToken.
6621 CXToken CXTok;
6622
6623 // - Common fields
6624 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6625 CXTok.int_data[2] = Tok.getLength();
6626 CXTok.int_data[3] = 0;
6627
6628 // - Kind-specific fields
6629 if (Tok.isLiteral()) {
6630 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006631 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006632 } else if (Tok.is(tok::raw_identifier)) {
6633 // Lookup the identifier to determine whether we have a keyword.
6634 IdentifierInfo *II
6635 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6636
6637 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6638 CXTok.int_data[0] = CXToken_Keyword;
6639 }
6640 else {
6641 CXTok.int_data[0] = Tok.is(tok::identifier)
6642 ? CXToken_Identifier
6643 : CXToken_Keyword;
6644 }
6645 CXTok.ptr_data = II;
6646 } else if (Tok.is(tok::comment)) {
6647 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006648 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006649 } else {
6650 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006651 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006652 }
6653 CXTokens.push_back(CXTok);
6654 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006655 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006656}
6657
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006658CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6659 LOG_FUNC_SECTION {
6660 *Log << TU << ' ' << Location;
6661 }
6662
6663 if (isNotUsableTU(TU)) {
6664 LOG_BAD_TU(TU);
6665 return NULL;
6666 }
6667
6668 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6669 if (!CXXUnit)
6670 return NULL;
6671
6672 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6673 if (Begin.isInvalid())
6674 return NULL;
6675 SourceManager &SM = CXXUnit->getSourceManager();
6676 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6677 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6678
6679 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6680
6681 SmallVector<CXToken, 32> CXTokens;
6682 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6683
6684 if (CXTokens.empty())
6685 return NULL;
6686
6687 CXTokens.resize(1);
6688 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6689
6690 memmove(Token, CXTokens.data(), sizeof(CXToken));
6691 return Token;
6692}
6693
Guy Benyei11169dd2012-12-18 14:30:41 +00006694void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6695 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006696 LOG_FUNC_SECTION {
6697 *Log << TU << ' ' << Range;
6698 }
6699
Guy Benyei11169dd2012-12-18 14:30:41 +00006700 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006701 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006702 if (NumTokens)
6703 *NumTokens = 0;
6704
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006705 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006706 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006707 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006708 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006709
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006710 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006711 if (!CXXUnit || !Tokens || !NumTokens)
6712 return;
6713
6714 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6715
6716 SourceRange R = cxloc::translateCXSourceRange(Range);
6717 if (R.isInvalid())
6718 return;
6719
6720 SmallVector<CXToken, 32> CXTokens;
6721 getTokens(CXXUnit, R, CXTokens);
6722
6723 if (CXTokens.empty())
6724 return;
6725
Serge Pavlov52525732018-02-21 02:02:39 +00006726 *Tokens = static_cast<CXToken *>(
6727 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006728 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6729 *NumTokens = CXTokens.size();
6730}
6731
6732void clang_disposeTokens(CXTranslationUnit TU,
6733 CXToken *Tokens, unsigned NumTokens) {
6734 free(Tokens);
6735}
6736
Guy Benyei11169dd2012-12-18 14:30:41 +00006737//===----------------------------------------------------------------------===//
6738// Token annotation APIs.
6739//===----------------------------------------------------------------------===//
6740
Guy Benyei11169dd2012-12-18 14:30:41 +00006741static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6742 CXCursor parent,
6743 CXClientData client_data);
6744static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6745 CXClientData client_data);
6746
6747namespace {
6748class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006749 CXToken *Tokens;
6750 CXCursor *Cursors;
6751 unsigned NumTokens;
6752 unsigned TokIdx;
6753 unsigned PreprocessingTokIdx;
6754 CursorVisitor AnnotateVis;
6755 SourceManager &SrcMgr;
6756 bool HasContextSensitiveKeywords;
6757
6758 struct PostChildrenInfo {
6759 CXCursor Cursor;
6760 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006761 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006762 unsigned BeforeChildrenTokenIdx;
6763 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006764 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006765
6766 CXToken &getTok(unsigned Idx) {
6767 assert(Idx < NumTokens);
6768 return Tokens[Idx];
6769 }
6770 const CXToken &getTok(unsigned Idx) const {
6771 assert(Idx < NumTokens);
6772 return Tokens[Idx];
6773 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006774 bool MoreTokens() const { return TokIdx < NumTokens; }
6775 unsigned NextToken() const { return TokIdx; }
6776 void AdvanceToken() { ++TokIdx; }
6777 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006778 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006779 }
6780 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006781 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006782 }
6783 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006784 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006785 }
6786
6787 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006788 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006789 SourceRange);
6790
6791public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006792 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006793 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006794 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006795 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006796 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006797 AnnotateTokensVisitor, this,
6798 /*VisitPreprocessorLast=*/true,
6799 /*VisitIncludedEntities=*/false,
6800 RegionOfInterest,
6801 /*VisitDeclsOnly=*/false,
6802 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006803 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006804 HasContextSensitiveKeywords(false) { }
6805
6806 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6807 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6808 bool postVisitChildren(CXCursor cursor);
6809 void AnnotateTokens();
6810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006811 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006812 /// context-sensitive keywords.
6813 bool hasContextSensitiveKeywords() const {
6814 return HasContextSensitiveKeywords;
6815 }
6816
6817 ~AnnotateTokensWorker() {
6818 assert(PostChildrenInfos.empty());
6819 }
6820};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006821}
Guy Benyei11169dd2012-12-18 14:30:41 +00006822
6823void AnnotateTokensWorker::AnnotateTokens() {
6824 // Walk the AST within the region of interest, annotating tokens
6825 // along the way.
6826 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006827}
Guy Benyei11169dd2012-12-18 14:30:41 +00006828
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006829static inline void updateCursorAnnotation(CXCursor &Cursor,
6830 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006831 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006832 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006833 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006834}
6835
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006836/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006837//// between the cursor location and the source range is the same as
6838/// \arg compResult.
6839///
6840/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6841/// Pass RangeOverlap to annotate tokens inside a range.
6842void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6843 RangeComparisonResult compResult,
6844 SourceRange range) {
6845 while (MoreTokens()) {
6846 const unsigned I = NextToken();
6847 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006848 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6849 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006850
6851 SourceLocation TokLoc = GetTokenLoc(I);
6852 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006853 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006854 AdvanceToken();
6855 continue;
6856 }
6857 break;
6858 }
6859}
6860
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006861/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006862/// \returns true if it advanced beyond all macro tokens, false otherwise.
6863bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006864 CXCursor updateC,
6865 RangeComparisonResult compResult,
6866 SourceRange range) {
6867 assert(MoreTokens());
6868 assert(isFunctionMacroToken(NextToken()) &&
6869 "Should be called only for macro arg tokens");
6870
6871 // This works differently than annotateAndAdvanceTokens; because expanded
6872 // macro arguments can have arbitrary translation-unit source order, we do not
6873 // advance the token index one by one until a token fails the range test.
6874 // We only advance once past all of the macro arg tokens if all of them
6875 // pass the range test. If one of them fails we keep the token index pointing
6876 // at the start of the macro arg tokens so that the failing token will be
6877 // annotated by a subsequent annotation try.
6878
6879 bool atLeastOneCompFail = false;
6880
6881 unsigned I = NextToken();
6882 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6883 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6884 if (TokLoc.isFileID())
6885 continue; // not macro arg token, it's parens or comma.
6886 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6887 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6888 Cursors[I] = updateC;
6889 } else
6890 atLeastOneCompFail = true;
6891 }
6892
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006893 if (atLeastOneCompFail)
6894 return false;
6895
6896 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6897 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006898}
6899
6900enum CXChildVisitResult
6901AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 SourceRange cursorRange = getRawCursorExtent(cursor);
6903 if (cursorRange.isInvalid())
6904 return CXChildVisit_Recurse;
6905
6906 if (!HasContextSensitiveKeywords) {
6907 // Objective-C properties can have context-sensitive keywords.
6908 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006909 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6911 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6912 }
6913 // Objective-C methods can have context-sensitive keywords.
6914 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6915 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006916 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006917 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6918 if (Method->getObjCDeclQualifier())
6919 HasContextSensitiveKeywords = true;
6920 else {
David Majnemer59f77922016-06-24 04:05:48 +00006921 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006922 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006923 HasContextSensitiveKeywords = true;
6924 break;
6925 }
6926 }
6927 }
6928 }
6929 }
6930 // C++ methods can have context-sensitive keywords.
6931 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006932 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6934 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6935 HasContextSensitiveKeywords = true;
6936 }
6937 }
6938 // C++ classes can have context-sensitive keywords.
6939 else if (cursor.kind == CXCursor_StructDecl ||
6940 cursor.kind == CXCursor_ClassDecl ||
6941 cursor.kind == CXCursor_ClassTemplate ||
6942 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006943 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 if (D->hasAttr<FinalAttr>())
6945 HasContextSensitiveKeywords = true;
6946 }
6947 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006948
6949 // Don't override a property annotation with its getter/setter method.
6950 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6951 parent.kind == CXCursor_ObjCPropertyDecl)
6952 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006953
6954 if (clang_isPreprocessing(cursor.kind)) {
6955 // Items in the preprocessing record are kept separate from items in
6956 // declarations, so we keep a separate token index.
6957 unsigned SavedTokIdx = TokIdx;
6958 TokIdx = PreprocessingTokIdx;
6959
6960 // Skip tokens up until we catch up to the beginning of the preprocessing
6961 // entry.
6962 while (MoreTokens()) {
6963 const unsigned I = NextToken();
6964 SourceLocation TokLoc = GetTokenLoc(I);
6965 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6966 case RangeBefore:
6967 AdvanceToken();
6968 continue;
6969 case RangeAfter:
6970 case RangeOverlap:
6971 break;
6972 }
6973 break;
6974 }
6975
6976 // Look at all of the tokens within this range.
6977 while (MoreTokens()) {
6978 const unsigned I = NextToken();
6979 SourceLocation TokLoc = GetTokenLoc(I);
6980 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6981 case RangeBefore:
6982 llvm_unreachable("Infeasible");
6983 case RangeAfter:
6984 break;
6985 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006986 // For macro expansions, just note where the beginning of the macro
6987 // expansion occurs.
6988 if (cursor.kind == CXCursor_MacroExpansion) {
6989 if (TokLoc == cursorRange.getBegin())
6990 Cursors[I] = cursor;
6991 AdvanceToken();
6992 break;
6993 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006994 // We may have already annotated macro names inside macro definitions.
6995 if (Cursors[I].kind != CXCursor_MacroExpansion)
6996 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006997 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006998 continue;
6999 }
7000 break;
7001 }
7002
7003 // Save the preprocessing token index; restore the non-preprocessing
7004 // token index.
7005 PreprocessingTokIdx = TokIdx;
7006 TokIdx = SavedTokIdx;
7007 return CXChildVisit_Recurse;
7008 }
7009
7010 if (cursorRange.isInvalid())
7011 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007012
7013 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007014 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007015 const enum CXCursorKind K = clang_getCursorKind(parent);
7016 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007017 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7018 // Attributes are annotated out-of-order, skip tokens until we reach it.
7019 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007020 ? clang_getNullCursor() : parent;
7021
7022 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7023
7024 // Avoid having the cursor of an expression "overwrite" the annotation of the
7025 // variable declaration that it belongs to.
7026 // This can happen for C++ constructor expressions whose range generally
7027 // include the variable declaration, e.g.:
7028 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007029 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007030 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00007031 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 const unsigned I = NextToken();
7033 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
7034 E->getLocStart() == D->getLocation() &&
7035 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007036 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007037 AdvanceToken();
7038 }
7039 }
7040 }
7041
7042 // Before recursing into the children keep some state that we are going
7043 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7044 // extra work after the child nodes are visited.
7045 // Note that we don't call VisitChildren here to avoid traversing statements
7046 // code-recursively which can blow the stack.
7047
7048 PostChildrenInfo Info;
7049 Info.Cursor = cursor;
7050 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007051 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007052 Info.BeforeChildrenTokenIdx = NextToken();
7053 PostChildrenInfos.push_back(Info);
7054
7055 return CXChildVisit_Recurse;
7056}
7057
7058bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7059 if (PostChildrenInfos.empty())
7060 return false;
7061 const PostChildrenInfo &Info = PostChildrenInfos.back();
7062 if (!clang_equalCursors(Info.Cursor, cursor))
7063 return false;
7064
7065 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7066 const unsigned AfterChildren = NextToken();
7067 SourceRange cursorRange = Info.CursorRange;
7068
7069 // Scan the tokens that are at the end of the cursor, but are not captured
7070 // but the child cursors.
7071 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7072
7073 // Scan the tokens that are at the beginning of the cursor, but are not
7074 // capture by the child cursors.
7075 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7076 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7077 break;
7078
7079 Cursors[I] = cursor;
7080 }
7081
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007082 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7083 // encountered the attribute cursor.
7084 if (clang_isAttribute(cursor.kind))
7085 TokIdx = Info.BeforeReachingCursorIdx;
7086
Guy Benyei11169dd2012-12-18 14:30:41 +00007087 PostChildrenInfos.pop_back();
7088 return false;
7089}
7090
7091static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7092 CXCursor parent,
7093 CXClientData client_data) {
7094 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7095}
7096
7097static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7098 CXClientData client_data) {
7099 return static_cast<AnnotateTokensWorker*>(client_data)->
7100 postVisitChildren(cursor);
7101}
7102
7103namespace {
7104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007105/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007106/// and mark tokens that are macro arguments. This info is used by the
7107/// AnnotateTokensWorker.
7108class MarkMacroArgTokensVisitor {
7109 SourceManager &SM;
7110 CXToken *Tokens;
7111 unsigned NumTokens;
7112 unsigned CurIdx;
7113
7114public:
7115 MarkMacroArgTokensVisitor(SourceManager &SM,
7116 CXToken *tokens, unsigned numTokens)
7117 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7118
7119 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7120 if (cursor.kind != CXCursor_MacroExpansion)
7121 return CXChildVisit_Continue;
7122
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007123 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007124 if (macroRange.getBegin() == macroRange.getEnd())
7125 return CXChildVisit_Continue; // it's not a function macro.
7126
7127 for (; CurIdx < NumTokens; ++CurIdx) {
7128 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7129 macroRange.getBegin()))
7130 break;
7131 }
7132
7133 if (CurIdx == NumTokens)
7134 return CXChildVisit_Break;
7135
7136 for (; CurIdx < NumTokens; ++CurIdx) {
7137 SourceLocation tokLoc = getTokenLoc(CurIdx);
7138 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7139 break;
7140
7141 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7142 }
7143
7144 if (CurIdx == NumTokens)
7145 return CXChildVisit_Break;
7146
7147 return CXChildVisit_Continue;
7148 }
7149
7150private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007151 CXToken &getTok(unsigned Idx) {
7152 assert(Idx < NumTokens);
7153 return Tokens[Idx];
7154 }
7155 const CXToken &getTok(unsigned Idx) const {
7156 assert(Idx < NumTokens);
7157 return Tokens[Idx];
7158 }
7159
Guy Benyei11169dd2012-12-18 14:30:41 +00007160 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007161 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007162 }
7163
7164 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7165 // The third field is reserved and currently not used. Use it here
7166 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007167 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007168 }
7169};
7170
7171} // end anonymous namespace
7172
7173static CXChildVisitResult
7174MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7175 CXClientData client_data) {
7176 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7177 parent);
7178}
7179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007180/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007181/// \returns true if lexing was finished, false otherwise.
7182static bool lexNext(Lexer &Lex, Token &Tok,
7183 unsigned &NextIdx, unsigned NumTokens) {
7184 if (NextIdx >= NumTokens)
7185 return true;
7186
7187 ++NextIdx;
7188 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007189 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007190}
7191
Guy Benyei11169dd2012-12-18 14:30:41 +00007192static void annotatePreprocessorTokens(CXTranslationUnit TU,
7193 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007194 CXCursor *Cursors,
7195 CXToken *Tokens,
7196 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007197 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007198
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007199 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7201 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007202 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007204 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007205
7206 if (BeginLocInfo.first != EndLocInfo.first)
7207 return;
7208
7209 StringRef Buffer;
7210 bool Invalid = false;
7211 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7212 if (Buffer.empty() || Invalid)
7213 return;
7214
7215 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7216 CXXUnit->getASTContext().getLangOpts(),
7217 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7218 Buffer.end());
7219 Lex.SetCommentRetentionState(true);
7220
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007221 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007222 // Lex tokens in raw mode until we hit the end of the range, to avoid
7223 // entering #includes or expanding macros.
7224 while (true) {
7225 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007226 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7227 break;
7228 unsigned TokIdx = NextIdx-1;
7229 assert(Tok.getLocation() ==
7230 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007231
7232 reprocess:
7233 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007234 // We have found a preprocessing directive. Annotate the tokens
7235 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007236 //
7237 // FIXME: Some simple tests here could identify macro definitions and
7238 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007239
7240 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007241 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7242 break;
7243
Craig Topper69186e72014-06-08 08:38:04 +00007244 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007245 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007246 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7247 break;
7248
7249 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007250 IdentifierInfo &II =
7251 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007252 SourceLocation MappedTokLoc =
7253 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7254 MI = getMacroInfo(II, MappedTokLoc, TU);
7255 }
7256 }
7257
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007258 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007259 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007260 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7261 finished = true;
7262 break;
7263 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007264 // If we are in a macro definition, check if the token was ever a
7265 // macro name and annotate it if that's the case.
7266 if (MI) {
7267 SourceLocation SaveLoc = Tok.getLocation();
7268 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007269 MacroDefinitionRecord *MacroDef =
7270 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007271 Tok.setLocation(SaveLoc);
7272 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007273 Cursors[NextIdx - 1] =
7274 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007275 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007276 } while (!Tok.isAtStartOfLine());
7277
7278 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7279 assert(TokIdx <= LastIdx);
7280 SourceLocation EndLoc =
7281 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7282 CXCursor Cursor =
7283 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7284
7285 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007286 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007287
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007288 if (finished)
7289 break;
7290 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007291 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007292 }
7293}
7294
7295// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007296static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7297 CXToken *Tokens, unsigned NumTokens,
7298 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007299 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007300 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7301 setThreadBackgroundPriority();
7302
7303 // Determine the region of interest, which contains all of the tokens.
7304 SourceRange RegionOfInterest;
7305 RegionOfInterest.setBegin(
7306 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7307 RegionOfInterest.setEnd(
7308 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7309 Tokens[NumTokens-1])));
7310
Guy Benyei11169dd2012-12-18 14:30:41 +00007311 // Relex the tokens within the source range to look for preprocessing
7312 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007313 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007314
7315 // If begin location points inside a macro argument, set it to the expansion
7316 // location so we can have the full context when annotating semantically.
7317 {
7318 SourceManager &SM = CXXUnit->getSourceManager();
7319 SourceLocation Loc =
7320 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7321 if (Loc.isMacroID())
7322 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7323 }
7324
Guy Benyei11169dd2012-12-18 14:30:41 +00007325 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7326 // Search and mark tokens that are macro argument expansions.
7327 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7328 Tokens, NumTokens);
7329 CursorVisitor MacroArgMarker(TU,
7330 MarkMacroArgTokensVisitorDelegate, &Visitor,
7331 /*VisitPreprocessorLast=*/true,
7332 /*VisitIncludedEntities=*/false,
7333 RegionOfInterest);
7334 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7335 }
7336
7337 // Annotate all of the source locations in the region of interest that map to
7338 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007339 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007340
7341 // FIXME: We use a ridiculous stack size here because the data-recursion
7342 // algorithm uses a large stack frame than the non-data recursive version,
7343 // and AnnotationTokensWorker currently transforms the data-recursion
7344 // algorithm back into a traditional recursion by explicitly calling
7345 // VisitChildren(). We will need to remove this explicit recursive call.
7346 W.AnnotateTokens();
7347
7348 // If we ran into any entities that involve context-sensitive keywords,
7349 // take another pass through the tokens to mark them as such.
7350 if (W.hasContextSensitiveKeywords()) {
7351 for (unsigned I = 0; I != NumTokens; ++I) {
7352 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7353 continue;
7354
7355 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7356 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007357 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007358 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7359 if (Property->getPropertyAttributesAsWritten() != 0 &&
7360 llvm::StringSwitch<bool>(II->getName())
7361 .Case("readonly", true)
7362 .Case("assign", true)
7363 .Case("unsafe_unretained", true)
7364 .Case("readwrite", true)
7365 .Case("retain", true)
7366 .Case("copy", true)
7367 .Case("nonatomic", true)
7368 .Case("atomic", true)
7369 .Case("getter", true)
7370 .Case("setter", true)
7371 .Case("strong", true)
7372 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007373 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007374 .Default(false))
7375 Tokens[I].int_data[0] = CXToken_Keyword;
7376 }
7377 continue;
7378 }
7379
7380 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7381 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7382 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7383 if (llvm::StringSwitch<bool>(II->getName())
7384 .Case("in", true)
7385 .Case("out", true)
7386 .Case("inout", true)
7387 .Case("oneway", true)
7388 .Case("bycopy", true)
7389 .Case("byref", true)
7390 .Default(false))
7391 Tokens[I].int_data[0] = CXToken_Keyword;
7392 continue;
7393 }
7394
7395 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7396 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7397 Tokens[I].int_data[0] = CXToken_Keyword;
7398 continue;
7399 }
7400 }
7401 }
7402}
7403
Guy Benyei11169dd2012-12-18 14:30:41 +00007404void clang_annotateTokens(CXTranslationUnit TU,
7405 CXToken *Tokens, unsigned NumTokens,
7406 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007407 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007408 LOG_BAD_TU(TU);
7409 return;
7410 }
7411 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007412 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007413 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007414 }
7415
7416 LOG_FUNC_SECTION {
7417 *Log << TU << ' ';
7418 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7419 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7420 *Log << clang_getRange(bloc, eloc);
7421 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007422
7423 // Any token we don't specifically annotate will have a NULL cursor.
7424 CXCursor C = clang_getNullCursor();
7425 for (unsigned I = 0; I != NumTokens; ++I)
7426 Cursors[I] = C;
7427
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007428 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007429 if (!CXXUnit)
7430 return;
7431
7432 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007433
7434 auto AnnotateTokensImpl = [=]() {
7435 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7436 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007437 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007438 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7440 }
7441}
7442
Guy Benyei11169dd2012-12-18 14:30:41 +00007443//===----------------------------------------------------------------------===//
7444// Operations for querying linkage of a cursor.
7445//===----------------------------------------------------------------------===//
7446
Guy Benyei11169dd2012-12-18 14:30:41 +00007447CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7448 if (!clang_isDeclaration(cursor.kind))
7449 return CXLinkage_Invalid;
7450
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007451 const Decl *D = cxcursor::getCursorDecl(cursor);
7452 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007453 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007454 case NoLinkage:
7455 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007456 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 case InternalLinkage: return CXLinkage_Internal;
7458 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007459 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007460 case ExternalLinkage: return CXLinkage_External;
7461 };
7462
7463 return CXLinkage_Invalid;
7464}
Guy Benyei11169dd2012-12-18 14:30:41 +00007465
7466//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007467// Operations for querying visibility of a cursor.
7468//===----------------------------------------------------------------------===//
7469
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007470CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7471 if (!clang_isDeclaration(cursor.kind))
7472 return CXVisibility_Invalid;
7473
7474 const Decl *D = cxcursor::getCursorDecl(cursor);
7475 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7476 switch (ND->getVisibility()) {
7477 case HiddenVisibility: return CXVisibility_Hidden;
7478 case ProtectedVisibility: return CXVisibility_Protected;
7479 case DefaultVisibility: return CXVisibility_Default;
7480 };
7481
7482 return CXVisibility_Invalid;
7483}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007484
7485//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007486// Operations for querying language of a cursor.
7487//===----------------------------------------------------------------------===//
7488
7489static CXLanguageKind getDeclLanguage(const Decl *D) {
7490 if (!D)
7491 return CXLanguage_C;
7492
7493 switch (D->getKind()) {
7494 default:
7495 break;
7496 case Decl::ImplicitParam:
7497 case Decl::ObjCAtDefsField:
7498 case Decl::ObjCCategory:
7499 case Decl::ObjCCategoryImpl:
7500 case Decl::ObjCCompatibleAlias:
7501 case Decl::ObjCImplementation:
7502 case Decl::ObjCInterface:
7503 case Decl::ObjCIvar:
7504 case Decl::ObjCMethod:
7505 case Decl::ObjCProperty:
7506 case Decl::ObjCPropertyImpl:
7507 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007508 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007509 return CXLanguage_ObjC;
7510 case Decl::CXXConstructor:
7511 case Decl::CXXConversion:
7512 case Decl::CXXDestructor:
7513 case Decl::CXXMethod:
7514 case Decl::CXXRecord:
7515 case Decl::ClassTemplate:
7516 case Decl::ClassTemplatePartialSpecialization:
7517 case Decl::ClassTemplateSpecialization:
7518 case Decl::Friend:
7519 case Decl::FriendTemplate:
7520 case Decl::FunctionTemplate:
7521 case Decl::LinkageSpec:
7522 case Decl::Namespace:
7523 case Decl::NamespaceAlias:
7524 case Decl::NonTypeTemplateParm:
7525 case Decl::StaticAssert:
7526 case Decl::TemplateTemplateParm:
7527 case Decl::TemplateTypeParm:
7528 case Decl::UnresolvedUsingTypename:
7529 case Decl::UnresolvedUsingValue:
7530 case Decl::Using:
7531 case Decl::UsingDirective:
7532 case Decl::UsingShadow:
7533 return CXLanguage_CPlusPlus;
7534 }
7535
7536 return CXLanguage_C;
7537}
7538
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007539static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7540 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007541 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007542
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007543 switch (D->getAvailability()) {
7544 case AR_Available:
7545 case AR_NotYetIntroduced:
7546 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007547 return getCursorAvailabilityForDecl(
7548 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007549 return CXAvailability_Available;
7550
7551 case AR_Deprecated:
7552 return CXAvailability_Deprecated;
7553
7554 case AR_Unavailable:
7555 return CXAvailability_NotAvailable;
7556 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007557
7558 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007559}
7560
Guy Benyei11169dd2012-12-18 14:30:41 +00007561enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7562 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007563 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7564 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007565
7566 return CXAvailability_Available;
7567}
7568
7569static CXVersion convertVersion(VersionTuple In) {
7570 CXVersion Out = { -1, -1, -1 };
7571 if (In.empty())
7572 return Out;
7573
7574 Out.Major = In.getMajor();
7575
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007576 Optional<unsigned> Minor = In.getMinor();
7577 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007578 Out.Minor = *Minor;
7579 else
7580 return Out;
7581
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007582 Optional<unsigned> Subminor = In.getSubminor();
7583 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007584 Out.Subminor = *Subminor;
7585
7586 return Out;
7587}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007588
Alex Lorenz1345ea22017-06-12 19:06:30 +00007589static void getCursorPlatformAvailabilityForDecl(
7590 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7591 int *always_unavailable, CXString *unavailable_message,
7592 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007593 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007594 for (auto A : D->attrs()) {
7595 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007596 HadAvailAttr = true;
7597 if (always_deprecated)
7598 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007599 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007600 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007601 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007602 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007603 continue;
7604 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007605
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007606 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007607 HadAvailAttr = true;
7608 if (always_unavailable)
7609 *always_unavailable = 1;
7610 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007611 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007612 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7613 }
7614 continue;
7615 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007616
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007617 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007618 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007619 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007620 }
7621 }
7622
7623 if (!HadAvailAttr)
7624 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7625 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007626 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7627 deprecated_message, always_unavailable, unavailable_message,
7628 AvailabilityAttrs);
7629
7630 if (AvailabilityAttrs.empty())
7631 return;
7632
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007633 llvm::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7634 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7635 return LHS->getPlatform()->getName() <
7636 RHS->getPlatform()->getName();
Alex Lorenz1345ea22017-06-12 19:06:30 +00007637 });
7638 ASTContext &Ctx = D->getASTContext();
7639 auto It = std::unique(
7640 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7641 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7642 if (LHS->getPlatform() != RHS->getPlatform())
7643 return false;
7644
7645 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7646 LHS->getDeprecated() == RHS->getDeprecated() &&
7647 LHS->getObsoleted() == RHS->getObsoleted() &&
7648 LHS->getMessage() == RHS->getMessage() &&
7649 LHS->getReplacement() == RHS->getReplacement())
7650 return true;
7651
7652 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7653 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7654 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7655 return false;
7656
7657 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7658 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7659
7660 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7661 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7662 if (LHS->getMessage().empty())
7663 LHS->setMessage(Ctx, RHS->getMessage());
7664 if (LHS->getReplacement().empty())
7665 LHS->setReplacement(Ctx, RHS->getReplacement());
7666 }
7667
7668 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7669 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7670 if (LHS->getMessage().empty())
7671 LHS->setMessage(Ctx, RHS->getMessage());
7672 if (LHS->getReplacement().empty())
7673 LHS->setReplacement(Ctx, RHS->getReplacement());
7674 }
7675
7676 return true;
7677 });
7678 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007679}
7680
Alex Lorenz1345ea22017-06-12 19:06:30 +00007681int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007682 CXString *deprecated_message,
7683 int *always_unavailable,
7684 CXString *unavailable_message,
7685 CXPlatformAvailability *availability,
7686 int availability_size) {
7687 if (always_deprecated)
7688 *always_deprecated = 0;
7689 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007690 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007691 if (always_unavailable)
7692 *always_unavailable = 0;
7693 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007694 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007695
Guy Benyei11169dd2012-12-18 14:30:41 +00007696 if (!clang_isDeclaration(cursor.kind))
7697 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007698
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007699 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 if (!D)
7701 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007702
Alex Lorenz1345ea22017-06-12 19:06:30 +00007703 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7704 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7705 always_unavailable, unavailable_message,
7706 AvailabilityAttrs);
7707 for (const auto &Avail :
7708 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7709 .take_front(availability_size))) {
7710 availability[Avail.index()].Platform =
7711 cxstring::createDup(Avail.value()->getPlatform()->getName());
7712 availability[Avail.index()].Introduced =
7713 convertVersion(Avail.value()->getIntroduced());
7714 availability[Avail.index()].Deprecated =
7715 convertVersion(Avail.value()->getDeprecated());
7716 availability[Avail.index()].Obsoleted =
7717 convertVersion(Avail.value()->getObsoleted());
7718 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7719 availability[Avail.index()].Message =
7720 cxstring::createDup(Avail.value()->getMessage());
7721 }
7722
7723 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007724}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007725
Guy Benyei11169dd2012-12-18 14:30:41 +00007726void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7727 clang_disposeString(availability->Platform);
7728 clang_disposeString(availability->Message);
7729}
7730
7731CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7732 if (clang_isDeclaration(cursor.kind))
7733 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7734
7735 return CXLanguage_Invalid;
7736}
7737
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007738CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7739 const Decl *D = cxcursor::getCursorDecl(cursor);
7740 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7741 switch (VD->getTLSKind()) {
7742 case VarDecl::TLS_None:
7743 return CXTLS_None;
7744 case VarDecl::TLS_Dynamic:
7745 return CXTLS_Dynamic;
7746 case VarDecl::TLS_Static:
7747 return CXTLS_Static;
7748 }
7749 }
7750
7751 return CXTLS_None;
7752}
7753
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007754 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007755 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007756 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007757static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007758 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007759 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007760
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007761 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007762 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7763 return FunTmpl;
7764
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007765 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007766 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7767 return ClassTmpl;
7768
7769 return D;
7770}
7771
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007772
7773enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7774 StorageClass sc = SC_None;
7775 const Decl *D = getCursorDecl(C);
7776 if (D) {
7777 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7778 sc = FD->getStorageClass();
7779 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7780 sc = VD->getStorageClass();
7781 } else {
7782 return CX_SC_Invalid;
7783 }
7784 } else {
7785 return CX_SC_Invalid;
7786 }
7787 switch (sc) {
7788 case SC_None:
7789 return CX_SC_None;
7790 case SC_Extern:
7791 return CX_SC_Extern;
7792 case SC_Static:
7793 return CX_SC_Static;
7794 case SC_PrivateExtern:
7795 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007796 case SC_Auto:
7797 return CX_SC_Auto;
7798 case SC_Register:
7799 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007800 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007801 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007802}
7803
Guy Benyei11169dd2012-12-18 14:30:41 +00007804CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7805 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007806 if (const Decl *D = getCursorDecl(cursor)) {
7807 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007808 if (!DC)
7809 return clang_getNullCursor();
7810
7811 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7812 getCursorTU(cursor));
7813 }
7814 }
7815
7816 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007817 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007818 return MakeCXCursor(D, getCursorTU(cursor));
7819 }
7820
7821 return clang_getNullCursor();
7822}
7823
7824CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7825 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007826 if (const Decl *D = getCursorDecl(cursor)) {
7827 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007828 if (!DC)
7829 return clang_getNullCursor();
7830
7831 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7832 getCursorTU(cursor));
7833 }
7834 }
7835
7836 // FIXME: Note that we can't easily compute the lexical context of a
7837 // statement or expression, so we return nothing.
7838 return clang_getNullCursor();
7839}
7840
7841CXFile clang_getIncludedFile(CXCursor cursor) {
7842 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007843 return nullptr;
7844
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007845 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007846 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007847}
7848
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007849unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7850 if (C.kind != CXCursor_ObjCPropertyDecl)
7851 return CXObjCPropertyAttr_noattr;
7852
7853 unsigned Result = CXObjCPropertyAttr_noattr;
7854 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7855 ObjCPropertyDecl::PropertyAttributeKind Attr =
7856 PD->getPropertyAttributesAsWritten();
7857
7858#define SET_CXOBJCPROP_ATTR(A) \
7859 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7860 Result |= CXObjCPropertyAttr_##A
7861 SET_CXOBJCPROP_ATTR(readonly);
7862 SET_CXOBJCPROP_ATTR(getter);
7863 SET_CXOBJCPROP_ATTR(assign);
7864 SET_CXOBJCPROP_ATTR(readwrite);
7865 SET_CXOBJCPROP_ATTR(retain);
7866 SET_CXOBJCPROP_ATTR(copy);
7867 SET_CXOBJCPROP_ATTR(nonatomic);
7868 SET_CXOBJCPROP_ATTR(setter);
7869 SET_CXOBJCPROP_ATTR(atomic);
7870 SET_CXOBJCPROP_ATTR(weak);
7871 SET_CXOBJCPROP_ATTR(strong);
7872 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007873 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007874#undef SET_CXOBJCPROP_ATTR
7875
7876 return Result;
7877}
7878
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007879unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7880 if (!clang_isDeclaration(C.kind))
7881 return CXObjCDeclQualifier_None;
7882
7883 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7884 const Decl *D = getCursorDecl(C);
7885 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7886 QT = MD->getObjCDeclQualifier();
7887 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7888 QT = PD->getObjCDeclQualifier();
7889 if (QT == Decl::OBJC_TQ_None)
7890 return CXObjCDeclQualifier_None;
7891
7892 unsigned Result = CXObjCDeclQualifier_None;
7893 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7894 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7895 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7896 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7897 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7898 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7899
7900 return Result;
7901}
7902
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007903unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7904 if (!clang_isDeclaration(C.kind))
7905 return 0;
7906
7907 const Decl *D = getCursorDecl(C);
7908 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7909 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7910 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7911 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7912
7913 return 0;
7914}
7915
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007916unsigned clang_Cursor_isVariadic(CXCursor C) {
7917 if (!clang_isDeclaration(C.kind))
7918 return 0;
7919
7920 const Decl *D = getCursorDecl(C);
7921 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7922 return FD->isVariadic();
7923 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7924 return MD->isVariadic();
7925
7926 return 0;
7927}
7928
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007929unsigned clang_Cursor_isExternalSymbol(CXCursor C,
7930 CXString *language, CXString *definedIn,
7931 unsigned *isGenerated) {
7932 if (!clang_isDeclaration(C.kind))
7933 return 0;
7934
7935 const Decl *D = getCursorDecl(C);
7936
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00007937 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007938 if (language)
7939 *language = cxstring::createDup(attr->getLanguage());
7940 if (definedIn)
7941 *definedIn = cxstring::createDup(attr->getDefinedIn());
7942 if (isGenerated)
7943 *isGenerated = attr->getGeneratedDeclaration();
7944 return 1;
7945 }
7946 return 0;
7947}
7948
Guy Benyei11169dd2012-12-18 14:30:41 +00007949CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7950 if (!clang_isDeclaration(C.kind))
7951 return clang_getNullRange();
7952
7953 const Decl *D = getCursorDecl(C);
7954 ASTContext &Context = getCursorContext(C);
7955 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7956 if (!RC)
7957 return clang_getNullRange();
7958
7959 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7960}
7961
7962CXString clang_Cursor_getRawCommentText(CXCursor C) {
7963 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007964 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007965
7966 const Decl *D = getCursorDecl(C);
7967 ASTContext &Context = getCursorContext(C);
7968 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7969 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7970 StringRef();
7971
7972 // Don't duplicate the string because RawText points directly into source
7973 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007974 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007975}
7976
7977CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7978 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007979 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007980
7981 const Decl *D = getCursorDecl(C);
7982 const ASTContext &Context = getCursorContext(C);
7983 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7984
7985 if (RC) {
7986 StringRef BriefText = RC->getBriefText(Context);
7987
7988 // Don't duplicate the string because RawComment ensures that this memory
7989 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007990 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007991 }
7992
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007993 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007994}
7995
Guy Benyei11169dd2012-12-18 14:30:41 +00007996CXModule clang_Cursor_getModule(CXCursor C) {
7997 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007998 if (const ImportDecl *ImportD =
7999 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008000 return ImportD->getImportedModule();
8001 }
8002
Craig Topper69186e72014-06-08 08:38:04 +00008003 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008004}
8005
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008006CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8007 if (isNotUsableTU(TU)) {
8008 LOG_BAD_TU(TU);
8009 return nullptr;
8010 }
8011 if (!File)
8012 return nullptr;
8013 FileEntry *FE = static_cast<FileEntry *>(File);
8014
8015 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8016 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8017 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8018
Richard Smithfeb54b62014-10-23 02:01:19 +00008019 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008020}
8021
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008022CXFile clang_Module_getASTFile(CXModule CXMod) {
8023 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008024 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008025 Module *Mod = static_cast<Module*>(CXMod);
8026 return const_cast<FileEntry *>(Mod->getASTFile());
8027}
8028
Guy Benyei11169dd2012-12-18 14:30:41 +00008029CXModule clang_Module_getParent(CXModule CXMod) {
8030 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008031 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008032 Module *Mod = static_cast<Module*>(CXMod);
8033 return Mod->Parent;
8034}
8035
8036CXString clang_Module_getName(CXModule CXMod) {
8037 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008038 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008039 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008040 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008041}
8042
8043CXString clang_Module_getFullName(CXModule CXMod) {
8044 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008045 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008046 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008047 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008048}
8049
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008050int clang_Module_isSystem(CXModule CXMod) {
8051 if (!CXMod)
8052 return 0;
8053 Module *Mod = static_cast<Module*>(CXMod);
8054 return Mod->IsSystem;
8055}
8056
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008057unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8058 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008059 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008060 LOG_BAD_TU(TU);
8061 return 0;
8062 }
8063 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 return 0;
8065 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008066 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8067 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8068 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008069}
8070
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008071CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8072 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008073 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008074 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008075 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008076 }
8077 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008078 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008079 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008080 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008081
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008082 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8083 if (Index < TopHeaders.size())
8084 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008085
Craig Topper69186e72014-06-08 08:38:04 +00008086 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008087}
8088
Guy Benyei11169dd2012-12-18 14:30:41 +00008089//===----------------------------------------------------------------------===//
8090// C++ AST instrospection.
8091//===----------------------------------------------------------------------===//
8092
Jonathan Coe29565352016-04-27 12:48:25 +00008093unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8094 if (!clang_isDeclaration(C.kind))
8095 return 0;
8096
8097 const Decl *D = cxcursor::getCursorDecl(C);
8098 const CXXConstructorDecl *Constructor =
8099 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8100 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8101}
8102
8103unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8104 if (!clang_isDeclaration(C.kind))
8105 return 0;
8106
8107 const Decl *D = cxcursor::getCursorDecl(C);
8108 const CXXConstructorDecl *Constructor =
8109 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8110 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8111}
8112
8113unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8114 if (!clang_isDeclaration(C.kind))
8115 return 0;
8116
8117 const Decl *D = cxcursor::getCursorDecl(C);
8118 const CXXConstructorDecl *Constructor =
8119 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8120 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8121}
8122
8123unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8124 if (!clang_isDeclaration(C.kind))
8125 return 0;
8126
8127 const Decl *D = cxcursor::getCursorDecl(C);
8128 const CXXConstructorDecl *Constructor =
8129 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8130 // Passing 'false' excludes constructors marked 'explicit'.
8131 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8132}
8133
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008134unsigned clang_CXXField_isMutable(CXCursor C) {
8135 if (!clang_isDeclaration(C.kind))
8136 return 0;
8137
8138 if (const auto D = cxcursor::getCursorDecl(C))
8139 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8140 return FD->isMutable() ? 1 : 0;
8141 return 0;
8142}
8143
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008144unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8145 if (!clang_isDeclaration(C.kind))
8146 return 0;
8147
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008148 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008149 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008150 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008151 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8152}
8153
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008154unsigned clang_CXXMethod_isConst(CXCursor C) {
8155 if (!clang_isDeclaration(C.kind))
8156 return 0;
8157
8158 const Decl *D = cxcursor::getCursorDecl(C);
8159 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008160 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008161 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
8162}
8163
Jonathan Coe29565352016-04-27 12:48:25 +00008164unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8165 if (!clang_isDeclaration(C.kind))
8166 return 0;
8167
8168 const Decl *D = cxcursor::getCursorDecl(C);
8169 const CXXMethodDecl *Method =
8170 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8171 return (Method && Method->isDefaulted()) ? 1 : 0;
8172}
8173
Guy Benyei11169dd2012-12-18 14:30:41 +00008174unsigned clang_CXXMethod_isStatic(CXCursor C) {
8175 if (!clang_isDeclaration(C.kind))
8176 return 0;
8177
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008178 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008179 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008180 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008181 return (Method && Method->isStatic()) ? 1 : 0;
8182}
8183
8184unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8185 if (!clang_isDeclaration(C.kind))
8186 return 0;
8187
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008188 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008189 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008190 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 return (Method && Method->isVirtual()) ? 1 : 0;
8192}
Guy Benyei11169dd2012-12-18 14:30:41 +00008193
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008194unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8195 if (!clang_isDeclaration(C.kind))
8196 return 0;
8197
8198 const auto *D = cxcursor::getCursorDecl(C);
8199 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8200 if (RD)
8201 RD = RD->getDefinition();
8202 return (RD && RD->isAbstract()) ? 1 : 0;
8203}
8204
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008205unsigned clang_EnumDecl_isScoped(CXCursor C) {
8206 if (!clang_isDeclaration(C.kind))
8207 return 0;
8208
8209 const Decl *D = cxcursor::getCursorDecl(C);
8210 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8211 return (Enum && Enum->isScoped()) ? 1 : 0;
8212}
8213
Guy Benyei11169dd2012-12-18 14:30:41 +00008214//===----------------------------------------------------------------------===//
8215// Attribute introspection.
8216//===----------------------------------------------------------------------===//
8217
Guy Benyei11169dd2012-12-18 14:30:41 +00008218CXType clang_getIBOutletCollectionType(CXCursor C) {
8219 if (C.kind != CXCursor_IBOutletCollectionAttr)
8220 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8221
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008222 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008223 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8224
8225 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8226}
Guy Benyei11169dd2012-12-18 14:30:41 +00008227
8228//===----------------------------------------------------------------------===//
8229// Inspecting memory usage.
8230//===----------------------------------------------------------------------===//
8231
8232typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8233
8234static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8235 enum CXTUResourceUsageKind k,
8236 unsigned long amount) {
8237 CXTUResourceUsageEntry entry = { k, amount };
8238 entries.push_back(entry);
8239}
8240
Guy Benyei11169dd2012-12-18 14:30:41 +00008241const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8242 const char *str = "";
8243 switch (kind) {
8244 case CXTUResourceUsage_AST:
8245 str = "ASTContext: expressions, declarations, and types";
8246 break;
8247 case CXTUResourceUsage_Identifiers:
8248 str = "ASTContext: identifiers";
8249 break;
8250 case CXTUResourceUsage_Selectors:
8251 str = "ASTContext: selectors";
8252 break;
8253 case CXTUResourceUsage_GlobalCompletionResults:
8254 str = "Code completion: cached global results";
8255 break;
8256 case CXTUResourceUsage_SourceManagerContentCache:
8257 str = "SourceManager: content cache allocator";
8258 break;
8259 case CXTUResourceUsage_AST_SideTables:
8260 str = "ASTContext: side tables";
8261 break;
8262 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8263 str = "SourceManager: malloc'ed memory buffers";
8264 break;
8265 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8266 str = "SourceManager: mmap'ed memory buffers";
8267 break;
8268 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8269 str = "ExternalASTSource: malloc'ed memory buffers";
8270 break;
8271 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8272 str = "ExternalASTSource: mmap'ed memory buffers";
8273 break;
8274 case CXTUResourceUsage_Preprocessor:
8275 str = "Preprocessor: malloc'ed memory";
8276 break;
8277 case CXTUResourceUsage_PreprocessingRecord:
8278 str = "Preprocessor: PreprocessingRecord";
8279 break;
8280 case CXTUResourceUsage_SourceManager_DataStructures:
8281 str = "SourceManager: data structures and tables";
8282 break;
8283 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8284 str = "Preprocessor: header search tables";
8285 break;
8286 }
8287 return str;
8288}
8289
8290CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008291 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008292 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008293 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008294 return usage;
8295 }
8296
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008297 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008298 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 ASTContext &astContext = astUnit->getASTContext();
8300
8301 // How much memory is used by AST nodes and types?
8302 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8303 (unsigned long) astContext.getASTAllocatedMemory());
8304
8305 // How much memory is used by identifiers?
8306 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8307 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8308
8309 // How much memory is used for selectors?
8310 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8311 (unsigned long) astContext.Selectors.getTotalMemory());
8312
8313 // How much memory is used by ASTContext's side tables?
8314 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8315 (unsigned long) astContext.getSideTableAllocatedMemory());
8316
8317 // How much memory is used for caching global code completion results?
8318 unsigned long completionBytes = 0;
8319 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008320 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008321 completionBytes = completionAllocator->getTotalMemory();
8322 }
8323 createCXTUResourceUsageEntry(*entries,
8324 CXTUResourceUsage_GlobalCompletionResults,
8325 completionBytes);
8326
8327 // How much memory is being used by SourceManager's content cache?
8328 createCXTUResourceUsageEntry(*entries,
8329 CXTUResourceUsage_SourceManagerContentCache,
8330 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8331
8332 // How much memory is being used by the MemoryBuffer's in SourceManager?
8333 const SourceManager::MemoryBufferSizes &srcBufs =
8334 astUnit->getSourceManager().getMemoryBufferSizes();
8335
8336 createCXTUResourceUsageEntry(*entries,
8337 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8338 (unsigned long) srcBufs.malloc_bytes);
8339 createCXTUResourceUsageEntry(*entries,
8340 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8341 (unsigned long) srcBufs.mmap_bytes);
8342 createCXTUResourceUsageEntry(*entries,
8343 CXTUResourceUsage_SourceManager_DataStructures,
8344 (unsigned long) astContext.getSourceManager()
8345 .getDataStructureSizes());
8346
8347 // How much memory is being used by the ExternalASTSource?
8348 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8349 const ExternalASTSource::MemoryBufferSizes &sizes =
8350 esrc->getMemoryBufferSizes();
8351
8352 createCXTUResourceUsageEntry(*entries,
8353 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8354 (unsigned long) sizes.malloc_bytes);
8355 createCXTUResourceUsageEntry(*entries,
8356 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8357 (unsigned long) sizes.mmap_bytes);
8358 }
8359
8360 // How much memory is being used by the Preprocessor?
8361 Preprocessor &pp = astUnit->getPreprocessor();
8362 createCXTUResourceUsageEntry(*entries,
8363 CXTUResourceUsage_Preprocessor,
8364 pp.getTotalMemory());
8365
8366 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8367 createCXTUResourceUsageEntry(*entries,
8368 CXTUResourceUsage_PreprocessingRecord,
8369 pRec->getTotalMemory());
8370 }
8371
8372 createCXTUResourceUsageEntry(*entries,
8373 CXTUResourceUsage_Preprocessor_HeaderSearch,
8374 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008375
Guy Benyei11169dd2012-12-18 14:30:41 +00008376 CXTUResourceUsage usage = { (void*) entries.get(),
8377 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008378 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008379 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008380 return usage;
8381}
8382
8383void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8384 if (usage.data)
8385 delete (MemUsageEntries*) usage.data;
8386}
8387
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008388CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8389 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008390 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008391 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008392
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008393 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008394 LOG_BAD_TU(TU);
8395 return skipped;
8396 }
8397
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008398 if (!file)
8399 return skipped;
8400
8401 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8402 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8403 if (!ppRec)
8404 return skipped;
8405
8406 ASTContext &Ctx = astUnit->getASTContext();
8407 SourceManager &sm = Ctx.getSourceManager();
8408 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8409 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008410 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008411
8412 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8413 std::vector<SourceRange> wantedRanges;
8414 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8415 i != ei; ++i) {
8416 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8417 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008418 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8419 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008420 }
8421
8422 skipped->count = wantedRanges.size();
8423 skipped->ranges = new CXSourceRange[skipped->count];
8424 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8425 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8426
8427 return skipped;
8428}
8429
Cameron Desrochersd8091282016-08-18 15:43:55 +00008430CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8431 CXSourceRangeList *skipped = new CXSourceRangeList;
8432 skipped->count = 0;
8433 skipped->ranges = nullptr;
8434
8435 if (isNotUsableTU(TU)) {
8436 LOG_BAD_TU(TU);
8437 return skipped;
8438 }
8439
8440 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8441 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8442 if (!ppRec)
8443 return skipped;
8444
8445 ASTContext &Ctx = astUnit->getASTContext();
8446
8447 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8448
8449 skipped->count = SkippedRanges.size();
8450 skipped->ranges = new CXSourceRange[skipped->count];
8451 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8452 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8453
8454 return skipped;
8455}
8456
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008457void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8458 if (ranges) {
8459 delete[] ranges->ranges;
8460 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008461 }
8462}
8463
Guy Benyei11169dd2012-12-18 14:30:41 +00008464void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8465 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8466 for (unsigned I = 0; I != Usage.numEntries; ++I)
8467 fprintf(stderr, " %s: %lu\n",
8468 clang_getTUResourceUsageName(Usage.entries[I].kind),
8469 Usage.entries[I].amount);
8470
8471 clang_disposeCXTUResourceUsage(Usage);
8472}
8473
8474//===----------------------------------------------------------------------===//
8475// Misc. utility functions.
8476//===----------------------------------------------------------------------===//
8477
Richard Smith0a7b2972018-07-03 21:34:13 +00008478/// Default to using our desired 8 MB stack size on "safety" threads.
8479static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008480
8481namespace clang {
8482
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008483bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008484 unsigned Size) {
8485 if (!Size)
8486 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008487 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008488 return CRC.RunSafelyOnThread(Fn, Size);
8489 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008490}
8491
8492unsigned GetSafetyThreadStackSize() {
8493 return SafetyStackThreadSize;
8494}
8495
8496void SetSafetyThreadStackSize(unsigned Value) {
8497 SafetyStackThreadSize = Value;
8498}
8499
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008500}
Guy Benyei11169dd2012-12-18 14:30:41 +00008501
8502void clang::setThreadBackgroundPriority() {
8503 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8504 return;
8505
Alp Toker1a86ad22014-07-06 06:24:00 +00008506#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008507 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8508#endif
8509}
8510
8511void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8512 if (!Unit)
8513 return;
8514
8515 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8516 DEnd = Unit->stored_diag_end();
8517 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008518 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008519 CXString Msg = clang_formatDiagnostic(&Diag,
8520 clang_defaultDiagnosticDisplayOptions());
8521 fprintf(stderr, "%s\n", clang_getCString(Msg));
8522 clang_disposeString(Msg);
8523 }
Nico Weber1865df42018-04-27 19:11:14 +00008524#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008525 // On Windows, force a flush, since there may be multiple copies of
8526 // stderr and stdout in the file system, all with different buffers
8527 // but writing to the same device.
8528 fflush(stderr);
8529#endif
8530}
8531
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008532MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8533 SourceLocation MacroDefLoc,
8534 CXTranslationUnit TU){
8535 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008536 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008537 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008538 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008539
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008540 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008541 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008542 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008543 if (MD) {
8544 for (MacroDirective::DefInfo
8545 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8546 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8547 return Def.getMacroInfo();
8548 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008549 }
8550
Craig Topper69186e72014-06-08 08:38:04 +00008551 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008552}
8553
Richard Smith66a81862015-05-04 02:25:31 +00008554const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008555 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008556 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008557 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008558 const IdentifierInfo *II = MacroDef->getName();
8559 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008560 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008561
8562 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8563}
8564
Richard Smith66a81862015-05-04 02:25:31 +00008565MacroDefinitionRecord *
8566cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8567 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008568 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008569 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008570 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008571 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008572
8573 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008574 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008575 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8576 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008577 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008578
8579 // Check that the token is inside the definition and not its argument list.
8580 SourceManager &SM = Unit->getSourceManager();
8581 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008582 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008583 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008584 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008585
8586 Preprocessor &PP = Unit->getPreprocessor();
8587 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8588 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008589 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008590
Alp Toker2d57cea2014-05-17 04:53:25 +00008591 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008592 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008593 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008594
8595 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008596 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008597 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008598
Richard Smith20e883e2015-04-29 23:20:19 +00008599 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008600 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008601 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008602
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008603 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008604}
8605
Richard Smith66a81862015-05-04 02:25:31 +00008606MacroDefinitionRecord *
8607cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8608 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008609 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008610 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008611
8612 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008613 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008614 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008615 Preprocessor &PP = Unit->getPreprocessor();
8616 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008617 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008618 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8619 Token Tok;
8620 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008621 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008622
8623 return checkForMacroInMacroDefinition(MI, Tok, TU);
8624}
8625
Guy Benyei11169dd2012-12-18 14:30:41 +00008626CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008627 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008628}
8629
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008630Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8631 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008632 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008633 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008634 if (Unit->isMainFileAST())
8635 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008636 return *this;
8637 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008638 } else {
8639 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008640 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008641 return *this;
8642}
8643
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008644Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8645 *this << FE->getName();
8646 return *this;
8647}
8648
8649Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8650 CXString cursorName = clang_getCursorDisplayName(cursor);
8651 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8652 clang_disposeString(cursorName);
8653 return *this;
8654}
8655
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008656Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8657 CXFile File;
8658 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008659 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008660 CXString FileName = clang_getFileName(File);
8661 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8662 clang_disposeString(FileName);
8663 return *this;
8664}
8665
8666Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8667 CXSourceLocation BLoc = clang_getRangeStart(range);
8668 CXSourceLocation ELoc = clang_getRangeEnd(range);
8669
8670 CXFile BFile;
8671 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008672 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008673
8674 CXFile EFile;
8675 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008676 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008677
8678 CXString BFileName = clang_getFileName(BFile);
8679 if (BFile == EFile) {
8680 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8681 BLine, BColumn, ELine, EColumn);
8682 } else {
8683 CXString EFileName = clang_getFileName(EFile);
8684 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8685 BLine, BColumn)
8686 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8687 ELine, EColumn);
8688 clang_disposeString(EFileName);
8689 }
8690 clang_disposeString(BFileName);
8691 return *this;
8692}
8693
8694Logger &cxindex::Logger::operator<<(CXString Str) {
8695 *this << clang_getCString(Str);
8696 return *this;
8697}
8698
8699Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8700 LogOS << Fmt;
8701 return *this;
8702}
8703
Chandler Carruth37ad2582014-06-27 15:14:39 +00008704static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8705
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008706cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008707 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008708
8709 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8710
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008711 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008712 OS << "[libclang:" << Name << ':';
8713
Alp Toker1a86ad22014-07-06 06:24:00 +00008714#ifdef USE_DARWIN_THREADS
8715 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008716 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8717 OS << tid << ':';
8718#endif
8719
8720 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8721 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008722 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008723
8724 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008725 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008726 OS << "--------------------------------------------------\n";
8727 }
8728}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008729
8730#ifdef CLANG_TOOL_EXTRA_BUILD
8731// This anchor is used to force the linker to link the clang-tidy plugin.
8732extern volatile int ClangTidyPluginAnchorSource;
8733static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8734 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008735
8736// This anchor is used to force the linker to link the clang-include-fixer
8737// plugin.
8738extern volatile int ClangIncludeFixerPluginAnchorSource;
8739static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8740 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008741#endif