blob: 07aeb50695bc14beec804a09b91aba505fff26c8 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the main API hooks in the Clang-C Source Indexing
10// library.
11//
12//===----------------------------------------------------------------------===//
13
Guy Benyei11169dd2012-12-18 14:30:41 +000014#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000015#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000016#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CXCursor.h"
18#include "CXSourceLocation.h"
19#include "CXString.h"
20#include "CXTranslationUnit.h"
21#include "CXType.h"
22#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000023#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/StmtVisitor.h"
25#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000026#include "clang/Basic/DiagnosticCategories.h"
27#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000028#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000029#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/Basic/Version.h"
31#include "clang/Frontend/ASTUnit.h"
32#include "clang/Frontend/CompilerInstance.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "llvm/ADT/Optional.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000042#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000043#include "llvm/Support/Compiler.h"
44#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000045#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000046#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/Support/Program.h"
50#include "llvm/Support/SaveAndRestore.h"
51#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000052#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000053#include "llvm/Support/Threading.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000056
Alp Toker1a86ad22014-07-06 06:24:00 +000057#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
58#define USE_DARWIN_THREADS
59#endif
60
61#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000062#include <pthread.h>
63#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000064
65using namespace clang;
66using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000067using namespace clang::cxtu;
68using namespace clang::cxindex;
69
David Blaikieea4395e2017-01-06 19:49:01 +000070CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
71 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000072 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000073 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000074 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000075 CXTranslationUnit D = new CXTranslationUnitImpl();
76 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000077 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000078 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000079 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000080 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000082 D->ParsingOptions = 0;
83 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000084 return D;
85}
86
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000087bool cxtu::isASTReadError(ASTUnit *AU) {
88 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
89 DEnd = AU->stored_diag_end();
90 D != DEnd; ++D) {
91 if (D->getLevel() >= DiagnosticsEngine::Error &&
92 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
93 diag::DiagCat_AST_Deserialization_Issue)
94 return true;
95 }
96 return false;
97}
98
Guy Benyei11169dd2012-12-18 14:30:41 +000099cxtu::CXTUOwner::~CXTUOwner() {
100 if (TU)
101 clang_disposeTranslationUnit(TU);
102}
103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000104/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000105/// the translation unit.
106static RangeComparisonResult RangeCompare(SourceManager &SM,
107 SourceRange R1,
108 SourceRange R2) {
109 assert(R1.isValid() && "First range is invalid?");
110 assert(R2.isValid() && "Second range is invalid?");
111 if (R1.getEnd() != R2.getBegin() &&
112 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
113 return RangeBefore;
114 if (R2.getEnd() != R1.getBegin() &&
115 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
116 return RangeAfter;
117 return RangeOverlap;
118}
119
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000120/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000121/// a given source range.
122static RangeComparisonResult LocationCompare(SourceManager &SM,
123 SourceLocation L, SourceRange R) {
124 assert(R.isValid() && "First range is invalid?");
125 assert(L.isValid() && "Second range is invalid?");
126 if (L == R.getBegin() || L == R.getEnd())
127 return RangeOverlap;
128 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
129 return RangeBefore;
130 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
131 return RangeAfter;
132 return RangeOverlap;
133}
134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000135/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000136///
137/// Clang internally represents ranges where the end location points to the
138/// start of the token at the end. However, for external clients it is more
139/// useful to have a CXSourceRange be a proper half-open interval. This routine
140/// does the appropriate translation.
141CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
142 const LangOptions &LangOpts,
143 const CharSourceRange &R) {
144 // We want the last character in this location, so we will adjust the
145 // location accordingly.
146 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000147 bool IsTokenRange = R.isTokenRange();
148 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
149 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
150 EndLoc = Expansion.getEnd();
151 IsTokenRange = Expansion.isTokenRange();
152 }
153 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000154 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
155 SM, LangOpts);
156 EndLoc = EndLoc.getLocWithOffset(Length);
157 }
158
Bill Wendlingeade3622013-01-23 08:25:41 +0000159 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000160 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000161 R.getBegin().getRawEncoding(),
162 EndLoc.getRawEncoding()
163 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000164 return Result;
165}
166
167//===----------------------------------------------------------------------===//
168// Cursor visitor.
169//===----------------------------------------------------------------------===//
170
171static SourceRange getRawCursorExtent(CXCursor C);
172static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
173
174
175RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
176 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
177}
178
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000179/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000180/// its children.
181///
182/// \param Cursor the cursor to visit.
183///
184/// \param CheckedRegionOfInterest if true, then the caller already checked
185/// that this cursor is within the region of interest.
186///
187/// \returns true if the visitation should be aborted, false if it
188/// should continue.
189bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
190 if (clang_isInvalid(Cursor.kind))
191 return false;
192
193 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000194 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000195 if (!D) {
196 assert(0 && "Invalid declaration cursor");
197 return true; // abort.
198 }
199
200 // Ignore implicit declarations, unless it's an objc method because
201 // currently we should report implicit methods for properties when indexing.
202 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
203 return false;
204 }
205
206 // If we have a range of interest, and this cursor doesn't intersect with it,
207 // we're done.
208 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
209 SourceRange Range = getRawCursorExtent(Cursor);
210 if (Range.isInvalid() || CompareRegionOfInterest(Range))
211 return false;
212 }
213
214 switch (Visitor(Cursor, Parent, ClientData)) {
215 case CXChildVisit_Break:
216 return true;
217
218 case CXChildVisit_Continue:
219 return false;
220
221 case CXChildVisit_Recurse: {
222 bool ret = VisitChildren(Cursor);
223 if (PostChildrenVisitor)
224 if (PostChildrenVisitor(Cursor, ClientData))
225 return true;
226 return ret;
227 }
228 }
229
230 llvm_unreachable("Invalid CXChildVisitResult!");
231}
232
233static bool visitPreprocessedEntitiesInRange(SourceRange R,
234 PreprocessingRecord &PPRec,
235 CursorVisitor &Visitor) {
236 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
237 FileID FID;
238
239 if (!Visitor.shouldVisitIncludedEntities()) {
240 // If the begin/end of the range lie in the same FileID, do the optimization
241 // where we skip preprocessed entities that do not come from the same FileID.
242 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
243 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
244 FID = FileID();
245 }
246
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000247 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
248 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 PPRec, FID);
250}
251
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000252bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000253 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000254 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000255
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000256 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000257 SourceManager &SM = Unit->getSourceManager();
258
259 std::pair<FileID, unsigned>
260 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
261 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
262
263 if (End.first != Begin.first) {
264 // If the end does not reside in the same file, try to recover by
265 // picking the end of the file of begin location.
266 End.first = Begin.first;
267 End.second = SM.getFileIDSize(Begin.first);
268 }
269
270 assert(Begin.first == End.first);
271 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000272 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000273
274 FileID File = Begin.first;
275 unsigned Offset = Begin.second;
276 unsigned Length = End.second - Begin.second;
277
278 if (!VisitDeclsOnly && !VisitPreprocessorLast)
279 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000281
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000282 if (visitDeclsFromFileRegion(File, Offset, Length))
283 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
285 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000286 return visitPreprocessedEntitiesInRegion();
287
288 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000289}
290
291static bool isInLexicalContext(Decl *D, DeclContext *DC) {
292 if (!DC)
293 return false;
294
295 for (DeclContext *DeclDC = D->getLexicalDeclContext();
296 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
297 if (DeclDC == DC)
298 return true;
299 }
300 return false;
301}
302
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000303bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000304 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000305 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 SourceManager &SM = Unit->getSourceManager();
307 SourceRange Range = RegionOfInterest;
308
309 SmallVector<Decl *, 16> Decls;
310 Unit->findFileRegionDecls(File, Offset, Length, Decls);
311
312 // If we didn't find any file level decls for the file, try looking at the
313 // file that it was included from.
314 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
315 bool Invalid = false;
316 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
317 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000318 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000319
320 SourceLocation Outer;
321 if (SLEntry.isFile())
322 Outer = SLEntry.getFile().getIncludeLoc();
323 else
324 Outer = SLEntry.getExpansion().getExpansionLocStart();
325 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000326 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000327
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000328 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000329 Length = 0;
330 Unit->findFileRegionDecls(File, Offset, Length, Decls);
331 }
332
333 assert(!Decls.empty());
334
335 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000336 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000337 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
338 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000339 Decl *D = *DIt;
340 if (D->getSourceRange().isInvalid())
341 continue;
342
343 if (isInLexicalContext(D, CurDC))
344 continue;
345
346 CurDC = dyn_cast<DeclContext>(D);
347
348 if (TagDecl *TD = dyn_cast<TagDecl>(D))
349 if (!TD->isFreeStanding())
350 continue;
351
352 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
353 if (CompRes == RangeBefore)
354 continue;
355 if (CompRes == RangeAfter)
356 break;
357
358 assert(CompRes == RangeOverlap);
359 VisitedAtLeastOnce = true;
360
361 if (isa<ObjCContainerDecl>(D)) {
362 FileDI_current = &DIt;
363 FileDE_current = DE;
364 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000365 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 }
367
368 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000369 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000370 }
371
372 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000373 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000374
375 // No Decls overlapped with the range. Move up the lexical context until there
376 // is a context that contains the range or we reach the translation unit
377 // level.
378 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
379 : (*(DIt-1))->getLexicalDeclContext();
380
381 while (DC && !DC->isTranslationUnit()) {
382 Decl *D = cast<Decl>(DC);
383 SourceRange CurDeclRange = D->getSourceRange();
384 if (CurDeclRange.isInvalid())
385 break;
386
387 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000388 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
389 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000390 }
391
392 DC = D->getLexicalDeclContext();
393 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000394
395 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000396}
397
398bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
399 if (!AU->getPreprocessor().getPreprocessingRecord())
400 return false;
401
402 PreprocessingRecord &PPRec
403 = *AU->getPreprocessor().getPreprocessingRecord();
404 SourceManager &SM = AU->getSourceManager();
405
406 if (RegionOfInterest.isValid()) {
407 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
408 SourceLocation B = MappedRange.getBegin();
409 SourceLocation E = MappedRange.getEnd();
410
411 if (AU->isInPreambleFileID(B)) {
412 if (SM.isLoadedSourceLocation(E))
413 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
414 PPRec, *this);
415
416 // Beginning of range lies in the preamble but it also extends beyond
417 // it into the main file. Split the range into 2 parts, one covering
418 // the preamble and another covering the main file. This allows subsequent
419 // calls to visitPreprocessedEntitiesInRange to accept a source range that
420 // lies in the same FileID, allowing it to skip preprocessed entities that
421 // do not come from the same FileID.
422 bool breaked =
423 visitPreprocessedEntitiesInRange(
424 SourceRange(B, AU->getEndOfPreambleFileID()),
425 PPRec, *this);
426 if (breaked) return true;
427 return visitPreprocessedEntitiesInRange(
428 SourceRange(AU->getStartOfMainFileID(), E),
429 PPRec, *this);
430 }
431
432 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
433 }
434
435 bool OnlyLocalDecls
436 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
437
438 if (OnlyLocalDecls)
439 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
440 PPRec);
441
442 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
443}
444
445template<typename InputIterator>
446bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
447 InputIterator Last,
448 PreprocessingRecord &PPRec,
449 FileID FID) {
450 for (; First != Last; ++First) {
451 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
452 continue;
453
454 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000455 if (!PPE)
456 continue;
457
Guy Benyei11169dd2012-12-18 14:30:41 +0000458 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
459 if (Visit(MakeMacroExpansionCursor(ME, TU)))
460 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000461
Guy Benyei11169dd2012-12-18 14:30:41 +0000462 continue;
463 }
Richard Smith66a81862015-05-04 02:25:31 +0000464
465 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000466 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
467 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000468
Guy Benyei11169dd2012-12-18 14:30:41 +0000469 continue;
470 }
471
472 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
473 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
474 return true;
475
476 continue;
477 }
478 }
479
480 return false;
481}
482
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000483/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000484///
485/// \returns true if the visitation should be aborted, false if it
486/// should continue.
487bool CursorVisitor::VisitChildren(CXCursor Cursor) {
488 if (clang_isReference(Cursor.kind) &&
489 Cursor.kind != CXCursor_CXXBaseSpecifier) {
490 // By definition, references have no children.
491 return false;
492 }
493
494 // Set the Parent field to Cursor, then back to its old value once we're
495 // done.
496 SetParentRAII SetParent(Parent, StmtParent, Cursor);
497
498 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000499 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000500 if (!D)
501 return false;
502
503 return VisitAttributes(D) || Visit(D);
504 }
505
506 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000507 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000508 return Visit(S);
509
510 return false;
511 }
512
513 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000514 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000515 return Visit(E);
516
517 return false;
518 }
519
520 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000521 CXTranslationUnit TU = getCursorTU(Cursor);
522 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000523
524 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
525 for (unsigned I = 0; I != 2; ++I) {
526 if (VisitOrder[I]) {
527 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
528 RegionOfInterest.isInvalid()) {
529 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
530 TLEnd = CXXUnit->top_level_end();
531 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000532 const Optional<bool> V = handleDeclForVisitation(*TL);
533 if (!V.hasValue())
534 continue;
535 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000536 }
537 } else if (VisitDeclContext(
538 CXXUnit->getASTContext().getTranslationUnitDecl()))
539 return true;
540 continue;
541 }
542
543 // Walk the preprocessing record.
544 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
545 visitPreprocessedEntitiesInRegion();
546 }
547
548 return false;
549 }
550
551 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000552 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000553 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
554 return Visit(BaseTSInfo->getTypeLoc());
555 }
556 }
557 }
558
559 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000560 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000562 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000563 return Visit(cxcursor::MakeCursorObjCClassRef(
564 ObjT->getInterface(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000565 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 }
567
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000568 // If pointing inside a macro definition, check if the token is an identifier
569 // that was ever defined as a macro. In such a case, create a "pseudo" macro
570 // expansion cursor for that token.
571 SourceLocation BeginLoc = RegionOfInterest.getBegin();
572 if (Cursor.kind == CXCursor_MacroDefinition &&
573 BeginLoc == RegionOfInterest.getEnd()) {
574 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000575 const MacroInfo *MI =
576 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000577 if (MacroDefinitionRecord *MacroDef =
578 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000579 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
580 }
581
Guy Benyei11169dd2012-12-18 14:30:41 +0000582 // Nothing to visit at the moment.
583 return false;
584}
585
586bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
587 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
588 if (Visit(TSInfo->getTypeLoc()))
589 return true;
590
591 if (Stmt *Body = B->getBody())
592 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
593
594 return false;
595}
596
Ted Kremenek03325582013-02-21 01:29:01 +0000597Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000598 if (RegionOfInterest.isValid()) {
599 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
600 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000601 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000602
603 switch (CompareRegionOfInterest(Range)) {
604 case RangeBefore:
605 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000606 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000607
608 case RangeAfter:
609 // This declaration comes after the region of interest; we're done.
610 return false;
611
612 case RangeOverlap:
613 // This declaration overlaps the region of interest; visit it.
614 break;
615 }
616 }
617 return true;
618}
619
620bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
621 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
622
623 // FIXME: Eventually remove. This part of a hack to support proper
624 // iteration over all Decls contained lexically within an ObjC container.
625 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
626 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
627
628 for ( ; I != E; ++I) {
629 Decl *D = *I;
630 if (D->getLexicalDeclContext() != DC)
631 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000632 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000633 if (!V.hasValue())
634 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000635 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000636 }
637 return false;
638}
639
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000640Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
641 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
642
643 // Ignore synthesized ivars here, otherwise if we have something like:
644 // @synthesize prop = _prop;
645 // and '_prop' is not declared, we will encounter a '_prop' ivar before
646 // encountering the 'prop' synthesize declaration and we will think that
647 // we passed the region-of-interest.
648 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
649 if (ivarD->getSynthesize())
650 return None;
651 }
652
653 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
654 // declarations is a mismatch with the compiler semantics.
655 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
656 auto *ID = cast<ObjCInterfaceDecl>(D);
657 if (!ID->isThisDeclarationADefinition())
658 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
659
660 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
661 auto *PD = cast<ObjCProtocolDecl>(D);
662 if (!PD->isThisDeclarationADefinition())
663 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
664 }
665
666 const Optional<bool> V = shouldVisitCursor(Cursor);
667 if (!V.hasValue())
668 return None;
669 if (!V.getValue())
670 return false;
671 if (Visit(Cursor, true))
672 return true;
673 return None;
674}
675
Guy Benyei11169dd2012-12-18 14:30:41 +0000676bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
677 llvm_unreachable("Translation units are visited directly by Visit()");
678}
679
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000680bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
681 if (VisitTemplateParameters(D->getTemplateParameters()))
682 return true;
683
684 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
685}
686
Guy Benyei11169dd2012-12-18 14:30:41 +0000687bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
688 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
689 return Visit(TSInfo->getTypeLoc());
690
691 return false;
692}
693
694bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
695 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
696 return Visit(TSInfo->getTypeLoc());
697
698 return false;
699}
700
701bool CursorVisitor::VisitTagDecl(TagDecl *D) {
702 return VisitDeclContext(D);
703}
704
705bool CursorVisitor::VisitClassTemplateSpecializationDecl(
706 ClassTemplateSpecializationDecl *D) {
707 bool ShouldVisitBody = false;
708 switch (D->getSpecializationKind()) {
709 case TSK_Undeclared:
710 case TSK_ImplicitInstantiation:
711 // Nothing to visit
712 return false;
713
714 case TSK_ExplicitInstantiationDeclaration:
715 case TSK_ExplicitInstantiationDefinition:
716 break;
717
718 case TSK_ExplicitSpecialization:
719 ShouldVisitBody = true;
720 break;
721 }
722
723 // Visit the template arguments used in the specialization.
724 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
725 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000726 if (TemplateSpecializationTypeLoc TSTLoc =
727 TL.getAs<TemplateSpecializationTypeLoc>()) {
728 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
729 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 return true;
731 }
732 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000733
734 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735}
736
737bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
738 ClassTemplatePartialSpecializationDecl *D) {
739 // FIXME: Visit the "outer" template parameter lists on the TagDecl
740 // before visiting these template parameters.
741 if (VisitTemplateParameters(D->getTemplateParameters()))
742 return true;
743
744 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000745 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
746 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
747 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000748 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
749 return true;
750
751 return VisitCXXRecordDecl(D);
752}
753
754bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
755 // Visit the default argument.
756 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
757 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
758 if (Visit(DefArg->getTypeLoc()))
759 return true;
760
761 return false;
762}
763
764bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
765 if (Expr *Init = D->getInitExpr())
766 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
767 return false;
768}
769
770bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000771 unsigned NumParamList = DD->getNumTemplateParameterLists();
772 for (unsigned i = 0; i < NumParamList; i++) {
773 TemplateParameterList* Params = DD->getTemplateParameterList(i);
774 if (VisitTemplateParameters(Params))
775 return true;
776 }
777
Guy Benyei11169dd2012-12-18 14:30:41 +0000778 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
779 if (Visit(TSInfo->getTypeLoc()))
780 return true;
781
782 // Visit the nested-name-specifier, if present.
783 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
784 if (VisitNestedNameSpecifierLoc(QualifierLoc))
785 return true;
786
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000787 return false;
788}
789
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000790static bool HasTrailingReturnType(FunctionDecl *ND) {
791 const QualType Ty = ND->getType();
792 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
793 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
794 return FT->hasTrailingReturn();
795 }
796
797 return false;
798}
799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000800/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000801static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
802 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000803 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
804}
805
Guy Benyei11169dd2012-12-18 14:30:41 +0000806bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000807 unsigned NumParamList = ND->getNumTemplateParameterLists();
808 for (unsigned i = 0; i < NumParamList; i++) {
809 TemplateParameterList* Params = ND->getTemplateParameterList(i);
810 if (VisitTemplateParameters(Params))
811 return true;
812 }
813
Guy Benyei11169dd2012-12-18 14:30:41 +0000814 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
815 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000816 // written. This requires a bit of work.
817 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
818 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000819 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000820
821 // If we have a function declared directly (without the use of a typedef),
822 // visit just the return type. Otherwise, just visit the function's type
823 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000824 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
825 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000826 (!FTL && Visit(TL)))
827 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000828
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000829 // Visit the nested-name-specifier, if present.
830 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
831 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000832 return true;
833
834 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000835 if (!isa<CXXDestructorDecl>(ND))
836 if (VisitDeclarationNameInfo(ND->getNameInfo()))
837 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000838
839 // FIXME: Visit explicitly-specified template arguments!
840
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000841 // Visit the function parameters, if we have a function type.
842 if (FTL && VisitFunctionTypeLoc(FTL, true))
843 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000844
845 // Visit the function's trailing return type.
846 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
847 return true;
848
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000849 // FIXME: Attributes?
850 }
851
Guy Benyei11169dd2012-12-18 14:30:41 +0000852 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
853 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
854 // Find the initializers that were written in the source.
855 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000856 for (auto *I : Constructor->inits()) {
857 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000858 continue;
859
Aaron Ballman0ad78302014-03-13 17:34:31 +0000860 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000861 }
862
863 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000864 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
865 &CompareCXXCtorInitializers);
866
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 // Visit the initializers in source order
868 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
869 CXXCtorInitializer *Init = WrittenInits[I];
870 if (Init->isAnyMemberInitializer()) {
871 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
872 Init->getMemberLocation(), TU)))
873 return true;
874 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
875 if (Visit(TInfo->getTypeLoc()))
876 return true;
877 }
878
879 // Visit the initializer value.
880 if (Expr *Initializer = Init->getInit())
881 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
882 return true;
883 }
884 }
885
886 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
887 return true;
888 }
889
890 return false;
891}
892
893bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
894 if (VisitDeclaratorDecl(D))
895 return true;
896
897 if (Expr *BitWidth = D->getBitWidth())
898 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
899
Benjamin Kramer99f97592017-11-15 12:20:41 +0000900 if (Expr *Init = D->getInClassInitializer())
901 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
902
Guy Benyei11169dd2012-12-18 14:30:41 +0000903 return false;
904}
905
906bool CursorVisitor::VisitVarDecl(VarDecl *D) {
907 if (VisitDeclaratorDecl(D))
908 return true;
909
910 if (Expr *Init = D->getInit())
911 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
912
913 return false;
914}
915
916bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
917 if (VisitDeclaratorDecl(D))
918 return true;
919
920 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
921 if (Expr *DefArg = D->getDefaultArgument())
922 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
923
924 return false;
925}
926
927bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
928 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
929 // before visiting these template parameters.
930 if (VisitTemplateParameters(D->getTemplateParameters()))
931 return true;
932
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000933 auto* FD = D->getTemplatedDecl();
934 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000935}
936
937bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
938 // FIXME: Visit the "outer" template parameter lists on the TagDecl
939 // before visiting these template parameters.
940 if (VisitTemplateParameters(D->getTemplateParameters()))
941 return true;
942
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000943 auto* CD = D->getTemplatedDecl();
944 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000945}
946
947bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
948 if (VisitTemplateParameters(D->getTemplateParameters()))
949 return true;
950
951 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
952 VisitTemplateArgumentLoc(D->getDefaultArgument()))
953 return true;
954
955 return false;
956}
957
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000958bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
959 // Visit the bound, if it's explicit.
960 if (D->hasExplicitBound()) {
961 if (auto TInfo = D->getTypeSourceInfo()) {
962 if (Visit(TInfo->getTypeLoc()))
963 return true;
964 }
965 }
966
967 return false;
968}
969
Guy Benyei11169dd2012-12-18 14:30:41 +0000970bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000971 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 if (Visit(TSInfo->getTypeLoc()))
973 return true;
974
David Majnemer59f77922016-06-24 04:05:48 +0000975 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000976 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 return true;
978 }
979
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000980 return ND->isThisDeclarationADefinition() &&
981 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000982}
983
984template <typename DeclIt>
985static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
986 SourceManager &SM, SourceLocation EndLoc,
987 SmallVectorImpl<Decl *> &Decls) {
988 DeclIt next = *DI_current;
989 while (++next != DE_current) {
990 Decl *D_next = *next;
991 if (!D_next)
992 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000993 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 if (!L.isValid())
995 break;
996 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
997 *DI_current = next;
998 Decls.push_back(D_next);
999 continue;
1000 }
1001 break;
1002 }
1003}
1004
Guy Benyei11169dd2012-12-18 14:30:41 +00001005bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1006 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1007 // an @implementation can lexically contain Decls that are not properly
1008 // nested in the AST. When we identify such cases, we need to retrofit
1009 // this nesting here.
1010 if (!DI_current && !FileDI_current)
1011 return VisitDeclContext(D);
1012
1013 // Scan the Decls that immediately come after the container
1014 // in the current DeclContext. If any fall within the
1015 // container's lexical region, stash them into a vector
1016 // for later processing.
1017 SmallVector<Decl *, 24> DeclsInContainer;
1018 SourceLocation EndLoc = D->getSourceRange().getEnd();
1019 SourceManager &SM = AU->getSourceManager();
1020 if (EndLoc.isValid()) {
1021 if (DI_current) {
1022 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1023 DeclsInContainer);
1024 } else {
1025 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1026 DeclsInContainer);
1027 }
1028 }
1029
1030 // The common case.
1031 if (DeclsInContainer.empty())
1032 return VisitDeclContext(D);
1033
1034 // Get all the Decls in the DeclContext, and sort them with the
1035 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001036 for (auto *SubDecl : D->decls()) {
1037 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001038 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001040 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 }
1042
1043 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001044 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001045 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001046 SourceLocation L_A = A->getBeginLoc();
1047 SourceLocation L_B = B->getBeginLoc();
1048 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001049 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1050 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001051 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001052
1053 // Now visit the decls.
1054 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1055 E = DeclsInContainer.end(); I != E; ++I) {
1056 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001057 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001058 if (!V.hasValue())
1059 continue;
1060 if (!V.getValue())
1061 return false;
1062 if (Visit(Cursor, true))
1063 return true;
1064 }
1065 return false;
1066}
1067
1068bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1069 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1070 TU)))
1071 return true;
1072
Douglas Gregore9d95f12015-07-07 03:57:35 +00001073 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1074 return true;
1075
Guy Benyei11169dd2012-12-18 14:30:41 +00001076 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1077 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1078 E = ND->protocol_end(); I != E; ++I, ++PL)
1079 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1080 return true;
1081
1082 return VisitObjCContainerDecl(ND);
1083}
1084
1085bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1086 if (!PID->isThisDeclarationADefinition())
1087 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1088
1089 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1090 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1091 E = PID->protocol_end(); I != E; ++I, ++PL)
1092 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1093 return true;
1094
1095 return VisitObjCContainerDecl(PID);
1096}
1097
1098bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1099 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1100 return true;
1101
1102 // FIXME: This implements a workaround with @property declarations also being
1103 // installed in the DeclContext for the @interface. Eventually this code
1104 // should be removed.
1105 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1106 if (!CDecl || !CDecl->IsClassExtension())
1107 return false;
1108
1109 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1110 if (!ID)
1111 return false;
1112
1113 IdentifierInfo *PropertyId = PD->getIdentifier();
1114 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001115 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1116 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001117
1118 if (!prevDecl)
1119 return false;
1120
1121 // Visit synthesized methods since they will be skipped when visiting
1122 // the @interface.
1123 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1124 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1125 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1126 return true;
1127
1128 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1129 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1130 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1131 return true;
1132
1133 return false;
1134}
1135
Douglas Gregore9d95f12015-07-07 03:57:35 +00001136bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1137 if (!typeParamList)
1138 return false;
1139
1140 for (auto *typeParam : *typeParamList) {
1141 // Visit the type parameter.
1142 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1143 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001144 }
1145
1146 return false;
1147}
1148
Guy Benyei11169dd2012-12-18 14:30:41 +00001149bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1150 if (!D->isThisDeclarationADefinition()) {
1151 // Forward declaration is treated like a reference.
1152 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1153 }
1154
Douglas Gregore9d95f12015-07-07 03:57:35 +00001155 // Objective-C type parameters.
1156 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1157 return true;
1158
Guy Benyei11169dd2012-12-18 14:30:41 +00001159 // Issue callbacks for super class.
1160 if (D->getSuperClass() &&
1161 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1162 D->getSuperClassLoc(),
1163 TU)))
1164 return true;
1165
Douglas Gregore9d95f12015-07-07 03:57:35 +00001166 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1167 if (Visit(SuperClassTInfo->getTypeLoc()))
1168 return true;
1169
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1171 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1172 E = D->protocol_end(); I != E; ++I, ++PL)
1173 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1174 return true;
1175
1176 return VisitObjCContainerDecl(D);
1177}
1178
1179bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1180 return VisitObjCContainerDecl(D);
1181}
1182
1183bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1184 // 'ID' could be null when dealing with invalid code.
1185 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1186 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1187 return true;
1188
1189 return VisitObjCImplDecl(D);
1190}
1191
1192bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1193#if 0
1194 // Issue callbacks for super class.
1195 // FIXME: No source location information!
1196 if (D->getSuperClass() &&
1197 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1198 D->getSuperClassLoc(),
1199 TU)))
1200 return true;
1201#endif
1202
1203 return VisitObjCImplDecl(D);
1204}
1205
1206bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1207 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1208 if (PD->isIvarNameSpecified())
1209 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1210
1211 return false;
1212}
1213
1214bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1215 return VisitDeclContext(D);
1216}
1217
1218bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1219 // Visit nested-name-specifier.
1220 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1221 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1222 return true;
1223
1224 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1225 D->getTargetNameLoc(), TU));
1226}
1227
1228bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1229 // Visit nested-name-specifier.
1230 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1231 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1232 return true;
1233 }
1234
1235 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1236 return true;
1237
1238 return VisitDeclarationNameInfo(D->getNameInfo());
1239}
1240
1241bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1242 // Visit nested-name-specifier.
1243 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1244 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1245 return true;
1246
1247 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1248 D->getIdentLocation(), TU));
1249}
1250
1251bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1252 // Visit nested-name-specifier.
1253 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1254 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1255 return true;
1256 }
1257
1258 return VisitDeclarationNameInfo(D->getNameInfo());
1259}
1260
1261bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1262 UnresolvedUsingTypenameDecl *D) {
1263 // Visit nested-name-specifier.
1264 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1265 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1266 return true;
1267
1268 return false;
1269}
1270
Olivier Goffart81978012016-06-09 16:15:55 +00001271bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1272 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1273 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001274 if (StringLiteral *Message = D->getMessage())
1275 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1276 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001277 return false;
1278}
1279
Olivier Goffartd211c642016-11-04 06:29:27 +00001280bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1281 if (NamedDecl *FriendD = D->getFriendDecl()) {
1282 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1283 return true;
1284 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1285 if (Visit(TI->getTypeLoc()))
1286 return true;
1287 }
1288 return false;
1289}
1290
Guy Benyei11169dd2012-12-18 14:30:41 +00001291bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1292 switch (Name.getName().getNameKind()) {
1293 case clang::DeclarationName::Identifier:
1294 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001295 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001296 case clang::DeclarationName::CXXOperatorName:
1297 case clang::DeclarationName::CXXUsingDirective:
1298 return false;
Richard Smith35845152017-02-07 01:37:30 +00001299
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 case clang::DeclarationName::CXXConstructorName:
1301 case clang::DeclarationName::CXXDestructorName:
1302 case clang::DeclarationName::CXXConversionFunctionName:
1303 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1304 return Visit(TSInfo->getTypeLoc());
1305 return false;
1306
1307 case clang::DeclarationName::ObjCZeroArgSelector:
1308 case clang::DeclarationName::ObjCOneArgSelector:
1309 case clang::DeclarationName::ObjCMultiArgSelector:
1310 // FIXME: Per-identifier location info?
1311 return false;
1312 }
1313
1314 llvm_unreachable("Invalid DeclarationName::Kind!");
1315}
1316
1317bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1318 SourceRange Range) {
1319 // FIXME: This whole routine is a hack to work around the lack of proper
1320 // source information in nested-name-specifiers (PR5791). Since we do have
1321 // a beginning source location, we can visit the first component of the
1322 // nested-name-specifier, if it's a single-token component.
1323 if (!NNS)
1324 return false;
1325
1326 // Get the first component in the nested-name-specifier.
1327 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1328 NNS = Prefix;
1329
1330 switch (NNS->getKind()) {
1331 case NestedNameSpecifier::Namespace:
1332 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1333 TU));
1334
1335 case NestedNameSpecifier::NamespaceAlias:
1336 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1337 Range.getBegin(), TU));
1338
1339 case NestedNameSpecifier::TypeSpec: {
1340 // If the type has a form where we know that the beginning of the source
1341 // range matches up with a reference cursor. Visit the appropriate reference
1342 // cursor.
1343 const Type *T = NNS->getAsType();
1344 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1345 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1346 if (const TagType *Tag = dyn_cast<TagType>(T))
1347 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1348 if (const TemplateSpecializationType *TST
1349 = dyn_cast<TemplateSpecializationType>(T))
1350 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1351 break;
1352 }
1353
1354 case NestedNameSpecifier::TypeSpecWithTemplate:
1355 case NestedNameSpecifier::Global:
1356 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001357 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 break;
1359 }
1360
1361 return false;
1362}
1363
1364bool
1365CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1366 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1367 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1368 Qualifiers.push_back(Qualifier);
1369
1370 while (!Qualifiers.empty()) {
1371 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1372 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1373 switch (NNS->getKind()) {
1374 case NestedNameSpecifier::Namespace:
1375 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1376 Q.getLocalBeginLoc(),
1377 TU)))
1378 return true;
1379
1380 break;
1381
1382 case NestedNameSpecifier::NamespaceAlias:
1383 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1384 Q.getLocalBeginLoc(),
1385 TU)))
1386 return true;
1387
1388 break;
1389
1390 case NestedNameSpecifier::TypeSpec:
1391 case NestedNameSpecifier::TypeSpecWithTemplate:
1392 if (Visit(Q.getTypeLoc()))
1393 return true;
1394
1395 break;
1396
1397 case NestedNameSpecifier::Global:
1398 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001399 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 break;
1401 }
1402 }
1403
1404 return false;
1405}
1406
1407bool CursorVisitor::VisitTemplateParameters(
1408 const TemplateParameterList *Params) {
1409 if (!Params)
1410 return false;
1411
1412 for (TemplateParameterList::const_iterator P = Params->begin(),
1413 PEnd = Params->end();
1414 P != PEnd; ++P) {
1415 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1416 return true;
1417 }
1418
1419 return false;
1420}
1421
1422bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1423 switch (Name.getKind()) {
1424 case TemplateName::Template:
1425 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1426
1427 case TemplateName::OverloadedTemplate:
1428 // Visit the overloaded template set.
1429 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1430 return true;
1431
1432 return false;
1433
1434 case TemplateName::DependentTemplate:
1435 // FIXME: Visit nested-name-specifier.
1436 return false;
1437
1438 case TemplateName::QualifiedTemplate:
1439 // FIXME: Visit nested-name-specifier.
1440 return Visit(MakeCursorTemplateRef(
1441 Name.getAsQualifiedTemplateName()->getDecl(),
1442 Loc, TU));
1443
1444 case TemplateName::SubstTemplateTemplateParm:
1445 return Visit(MakeCursorTemplateRef(
1446 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1447 Loc, TU));
1448
1449 case TemplateName::SubstTemplateTemplateParmPack:
1450 return Visit(MakeCursorTemplateRef(
1451 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1452 Loc, TU));
1453 }
1454
1455 llvm_unreachable("Invalid TemplateName::Kind!");
1456}
1457
1458bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1459 switch (TAL.getArgument().getKind()) {
1460 case TemplateArgument::Null:
1461 case TemplateArgument::Integral:
1462 case TemplateArgument::Pack:
1463 return false;
1464
1465 case TemplateArgument::Type:
1466 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1467 return Visit(TSInfo->getTypeLoc());
1468 return false;
1469
1470 case TemplateArgument::Declaration:
1471 if (Expr *E = TAL.getSourceDeclExpression())
1472 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1473 return false;
1474
1475 case TemplateArgument::NullPtr:
1476 if (Expr *E = TAL.getSourceNullPtrExpression())
1477 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1478 return false;
1479
1480 case TemplateArgument::Expression:
1481 if (Expr *E = TAL.getSourceExpression())
1482 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1483 return false;
1484
1485 case TemplateArgument::Template:
1486 case TemplateArgument::TemplateExpansion:
1487 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1488 return true;
1489
1490 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1491 TAL.getTemplateNameLoc());
1492 }
1493
1494 llvm_unreachable("Invalid TemplateArgument::Kind!");
1495}
1496
1497bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1498 return VisitDeclContext(D);
1499}
1500
1501bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1502 return Visit(TL.getUnqualifiedLoc());
1503}
1504
1505bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1506 ASTContext &Context = AU->getASTContext();
1507
1508 // Some builtin types (such as Objective-C's "id", "sel", and
1509 // "Class") have associated declarations. Create cursors for those.
1510 QualType VisitType;
1511 switch (TL.getTypePtr()->getKind()) {
1512
1513 case BuiltinType::Void:
1514 case BuiltinType::NullPtr:
1515 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001516#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1517 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001518#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001519#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1520 case BuiltinType::Id:
1521#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001522 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001523 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001524 case BuiltinType::OCLClkEvent:
1525 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001526 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001527#define BUILTIN_TYPE(Id, SingletonId)
1528#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1529#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1530#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1531#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1532#include "clang/AST/BuiltinTypes.def"
1533 break;
1534
1535 case BuiltinType::ObjCId:
1536 VisitType = Context.getObjCIdType();
1537 break;
1538
1539 case BuiltinType::ObjCClass:
1540 VisitType = Context.getObjCClassType();
1541 break;
1542
1543 case BuiltinType::ObjCSel:
1544 VisitType = Context.getObjCSelType();
1545 break;
1546 }
1547
1548 if (!VisitType.isNull()) {
1549 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1550 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1551 TU));
1552 }
1553
1554 return false;
1555}
1556
1557bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1558 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1559}
1560
1561bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1562 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1563}
1564
1565bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1566 if (TL.isDefinition())
1567 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1568
1569 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1570}
1571
1572bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1573 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1574}
1575
1576bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001577 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001578}
1579
Manman Rene6be26c2016-09-13 17:25:08 +00001580bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001581 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001582 return true;
1583 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1584 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1585 TU)))
1586 return true;
1587 }
1588
1589 return false;
1590}
1591
Guy Benyei11169dd2012-12-18 14:30:41 +00001592bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1593 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1594 return true;
1595
Douglas Gregore9d95f12015-07-07 03:57:35 +00001596 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1597 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1598 return true;
1599 }
1600
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1602 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1603 TU)))
1604 return true;
1605 }
1606
1607 return false;
1608}
1609
1610bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1611 return Visit(TL.getPointeeLoc());
1612}
1613
1614bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1615 return Visit(TL.getInnerLoc());
1616}
1617
1618bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1619 return Visit(TL.getPointeeLoc());
1620}
1621
1622bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1623 return Visit(TL.getPointeeLoc());
1624}
1625
1626bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1627 return Visit(TL.getPointeeLoc());
1628}
1629
1630bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1631 return Visit(TL.getPointeeLoc());
1632}
1633
1634bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1635 return Visit(TL.getPointeeLoc());
1636}
1637
1638bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1639 return Visit(TL.getModifiedLoc());
1640}
1641
1642bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1643 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001644 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 return true;
1646
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001647 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1648 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1650 return true;
1651
1652 return false;
1653}
1654
1655bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1656 if (Visit(TL.getElementLoc()))
1657 return true;
1658
1659 if (Expr *Size = TL.getSizeExpr())
1660 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1661
1662 return false;
1663}
1664
Reid Kleckner8a365022013-06-24 17:51:48 +00001665bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1666 return Visit(TL.getOriginalLoc());
1667}
1668
Reid Kleckner0503a872013-12-05 01:23:43 +00001669bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1670 return Visit(TL.getOriginalLoc());
1671}
1672
Richard Smith600b5262017-01-26 20:40:47 +00001673bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1674 DeducedTemplateSpecializationTypeLoc TL) {
1675 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1676 TL.getTemplateNameLoc()))
1677 return true;
1678
1679 return false;
1680}
1681
Guy Benyei11169dd2012-12-18 14:30:41 +00001682bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1683 TemplateSpecializationTypeLoc TL) {
1684 // Visit the template name.
1685 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1686 TL.getTemplateNameLoc()))
1687 return true;
1688
1689 // Visit the template arguments.
1690 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1691 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1692 return true;
1693
1694 return false;
1695}
1696
1697bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1698 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1699}
1700
1701bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1702 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1703 return Visit(TSInfo->getTypeLoc());
1704
1705 return false;
1706}
1707
1708bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1709 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1710 return Visit(TSInfo->getTypeLoc());
1711
1712 return false;
1713}
1714
1715bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001716 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001717}
1718
1719bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1720 DependentTemplateSpecializationTypeLoc TL) {
1721 // Visit the nested-name-specifier, if there is one.
1722 if (TL.getQualifierLoc() &&
1723 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1724 return true;
1725
1726 // Visit the template arguments.
1727 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1728 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1729 return true;
1730
1731 return false;
1732}
1733
1734bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1735 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1736 return true;
1737
1738 return Visit(TL.getNamedTypeLoc());
1739}
1740
1741bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1742 return Visit(TL.getPatternLoc());
1743}
1744
1745bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1746 if (Expr *E = TL.getUnderlyingExpr())
1747 return Visit(MakeCXCursor(E, StmtParent, TU));
1748
1749 return false;
1750}
1751
1752bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1753 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1754}
1755
1756bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1757 return Visit(TL.getValueLoc());
1758}
1759
Xiuli Pan9c14e282016-01-09 12:53:17 +00001760bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1761 return Visit(TL.getValueLoc());
1762}
1763
Guy Benyei11169dd2012-12-18 14:30:41 +00001764#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1765bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1766 return Visit##PARENT##Loc(TL); \
1767}
1768
1769DEFAULT_TYPELOC_IMPL(Complex, Type)
1770DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1771DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1772DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1773DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001774DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001775DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001776DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1777DEFAULT_TYPELOC_IMPL(Vector, Type)
1778DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1779DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1780DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1781DEFAULT_TYPELOC_IMPL(Record, TagType)
1782DEFAULT_TYPELOC_IMPL(Enum, TagType)
1783DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1784DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1785DEFAULT_TYPELOC_IMPL(Auto, Type)
1786
1787bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1788 // Visit the nested-name-specifier, if present.
1789 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1790 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1791 return true;
1792
1793 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001794 for (const auto &I : D->bases()) {
1795 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 return true;
1797 }
1798 }
1799
1800 return VisitTagDecl(D);
1801}
1802
1803bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001804 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001805 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1806 !I->isImplicit()) &&
1807 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 return true;
1809
1810 return false;
1811}
1812
1813//===----------------------------------------------------------------------===//
1814// Data-recursive visitor methods.
1815//===----------------------------------------------------------------------===//
1816
1817namespace {
1818#define DEF_JOB(NAME, DATA, KIND)\
1819class NAME : public VisitorJob {\
1820public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001821 NAME(const DATA *d, CXCursor parent) : \
1822 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001824 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001825};
1826
1827DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1828DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1829DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1830DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001831DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1832DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1833DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1834#undef DEF_JOB
1835
James Y Knight04ec5bf2015-12-24 02:59:37 +00001836class ExplicitTemplateArgsVisit : public VisitorJob {
1837public:
1838 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1839 const TemplateArgumentLoc *End, CXCursor parent)
1840 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1841 End) {}
1842 static bool classof(const VisitorJob *VJ) {
1843 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1844 }
1845 const TemplateArgumentLoc *begin() const {
1846 return static_cast<const TemplateArgumentLoc *>(data[0]);
1847 }
1848 const TemplateArgumentLoc *end() {
1849 return static_cast<const TemplateArgumentLoc *>(data[1]);
1850 }
1851};
Guy Benyei11169dd2012-12-18 14:30:41 +00001852class DeclVisit : public VisitorJob {
1853public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001854 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001855 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001856 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001857 static bool classof(const VisitorJob *VJ) {
1858 return VJ->getKind() == DeclVisitKind;
1859 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001860 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001861 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001862};
1863class TypeLocVisit : public VisitorJob {
1864public:
1865 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1866 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1867 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1868
1869 static bool classof(const VisitorJob *VJ) {
1870 return VJ->getKind() == TypeLocVisitKind;
1871 }
1872
1873 TypeLoc get() const {
1874 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001875 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 }
1877};
1878
1879class LabelRefVisit : public VisitorJob {
1880public:
1881 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1882 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1883 labelLoc.getPtrEncoding()) {}
1884
1885 static bool classof(const VisitorJob *VJ) {
1886 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1887 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001888 const LabelDecl *get() const {
1889 return static_cast<const LabelDecl *>(data[0]);
1890 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 SourceLocation getLoc() const {
1892 return SourceLocation::getFromPtrEncoding(data[1]); }
1893};
1894
1895class NestedNameSpecifierLocVisit : public VisitorJob {
1896public:
1897 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1898 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1899 Qualifier.getNestedNameSpecifier(),
1900 Qualifier.getOpaqueData()) { }
1901
1902 static bool classof(const VisitorJob *VJ) {
1903 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1904 }
1905
1906 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001907 return NestedNameSpecifierLoc(
1908 const_cast<NestedNameSpecifier *>(
1909 static_cast<const NestedNameSpecifier *>(data[0])),
1910 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001911 }
1912};
1913
1914class DeclarationNameInfoVisit : public VisitorJob {
1915public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001916 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001917 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001918 static bool classof(const VisitorJob *VJ) {
1919 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1920 }
1921 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001922 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001923 switch (S->getStmtClass()) {
1924 default:
1925 llvm_unreachable("Unhandled Stmt");
1926 case clang::Stmt::MSDependentExistsStmtClass:
1927 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1928 case Stmt::CXXDependentScopeMemberExprClass:
1929 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1930 case Stmt::DependentScopeDeclRefExprClass:
1931 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001932 case Stmt::OMPCriticalDirectiveClass:
1933 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 }
1935 }
1936};
1937class MemberRefVisit : public VisitorJob {
1938public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001939 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1941 L.getPtrEncoding()) {}
1942 static bool classof(const VisitorJob *VJ) {
1943 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1944 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001945 const FieldDecl *get() const {
1946 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001947 }
1948 SourceLocation getLoc() const {
1949 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1950 }
1951};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001952class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001953 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 VisitorWorkList &WL;
1955 CXCursor Parent;
1956public:
1957 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1958 : WL(wl), Parent(parent) {}
1959
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001960 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1961 void VisitBlockExpr(const BlockExpr *B);
1962 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1963 void VisitCompoundStmt(const CompoundStmt *S);
1964 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1965 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1966 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1967 void VisitCXXNewExpr(const CXXNewExpr *E);
1968 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1969 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1970 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1971 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1972 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1973 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1974 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1975 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001976 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001977 void VisitDeclRefExpr(const DeclRefExpr *D);
1978 void VisitDeclStmt(const DeclStmt *S);
1979 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1980 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1981 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1982 void VisitForStmt(const ForStmt *FS);
1983 void VisitGotoStmt(const GotoStmt *GS);
1984 void VisitIfStmt(const IfStmt *If);
1985 void VisitInitListExpr(const InitListExpr *IE);
1986 void VisitMemberExpr(const MemberExpr *M);
1987 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1988 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1989 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1990 void VisitOverloadExpr(const OverloadExpr *E);
1991 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1992 void VisitStmt(const Stmt *S);
1993 void VisitSwitchStmt(const SwitchStmt *S);
1994 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001995 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1996 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1997 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1998 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1999 void VisitVAArgExpr(const VAArgExpr *E);
2000 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2001 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2002 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2003 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002004 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002005 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002006 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002007 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002008 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002009 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002010 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002011 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002012 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002013 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002014 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002015 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002016 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002017 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002018 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002019 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002020 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002021 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002022 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002023 void
2024 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002025 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002026 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002027 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002028 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002029 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002030 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002031 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002032 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002033 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002034 void
2035 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002036 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002037 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002038 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002039 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002040 void VisitOMPDistributeParallelForDirective(
2041 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002042 void VisitOMPDistributeParallelForSimdDirective(
2043 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002044 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002045 void VisitOMPTargetParallelForSimdDirective(
2046 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002047 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002048 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002049 void VisitOMPTeamsDistributeSimdDirective(
2050 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002051 void VisitOMPTeamsDistributeParallelForSimdDirective(
2052 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002053 void VisitOMPTeamsDistributeParallelForDirective(
2054 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002055 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002056 void VisitOMPTargetTeamsDistributeDirective(
2057 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002058 void VisitOMPTargetTeamsDistributeParallelForDirective(
2059 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002060 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2061 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002062 void VisitOMPTargetTeamsDistributeSimdDirective(
2063 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002064
Guy Benyei11169dd2012-12-18 14:30:41 +00002065private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002066 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002067 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002068 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2069 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002070 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2071 void AddStmt(const Stmt *S);
2072 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002073 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002074 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002075 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002076};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002077} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002078
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002079void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 // 'S' should always be non-null, since it comes from the
2081 // statement we are visiting.
2082 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2083}
2084
2085void
2086EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2087 if (Qualifier)
2088 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2089}
2090
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002091void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002092 if (S)
2093 WL.push_back(StmtVisit(S, Parent));
2094}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002095void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 if (D)
2097 WL.push_back(DeclVisit(D, Parent, isFirst));
2098}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002099void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2100 unsigned NumTemplateArgs) {
2101 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002102}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002103void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 if (D)
2105 WL.push_back(MemberRefVisit(D, L, Parent));
2106}
2107void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2108 if (TI)
2109 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2110 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002111void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002112 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002113 for (const Stmt *SubStmt : S->children()) {
2114 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 }
2116 if (size == WL.size())
2117 return;
2118 // Now reverse the entries we just added. This will match the DFS
2119 // ordering performed by the worklist.
2120 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2121 std::reverse(I, E);
2122}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002123namespace {
2124class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2125 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002126 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002127 template <typename T>
2128 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002129public:
2130 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2131#define OPENMP_CLAUSE(Name, Class) \
2132 void Visit##Class(const Class *C);
2133#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002134 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002135 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002136};
2137
Alexey Bataev3392d762016-02-16 11:18:12 +00002138void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2139 const OMPClauseWithPreInit *C) {
2140 Visitor->AddStmt(C->getPreInitStmt());
2141}
2142
Alexey Bataev005248a2016-02-25 05:25:57 +00002143void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2144 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002145 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002146 Visitor->AddStmt(C->getPostUpdateExpr());
2147}
2148
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002149void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002150 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002151 Visitor->AddStmt(C->getCondition());
2152}
2153
Alexey Bataev3778b602014-07-17 07:32:53 +00002154void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2155 Visitor->AddStmt(C->getCondition());
2156}
2157
Alexey Bataev568a8332014-03-06 06:15:19 +00002158void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002159 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002160 Visitor->AddStmt(C->getNumThreads());
2161}
2162
Alexey Bataev62c87d22014-03-21 04:51:18 +00002163void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2164 Visitor->AddStmt(C->getSafelen());
2165}
2166
Alexey Bataev66b15b52015-08-21 11:14:16 +00002167void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2168 Visitor->AddStmt(C->getSimdlen());
2169}
2170
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002171void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2172 Visitor->AddStmt(C->getAllocator());
2173}
2174
Alexander Musman8bd31e62014-05-27 15:12:19 +00002175void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2176 Visitor->AddStmt(C->getNumForLoops());
2177}
2178
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002179void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002180
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002181void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2182
Alexey Bataev56dafe82014-06-20 07:16:17 +00002183void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002184 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002185 Visitor->AddStmt(C->getChunkSize());
2186}
2187
Alexey Bataev10e775f2015-07-30 11:36:16 +00002188void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2189 Visitor->AddStmt(C->getNumForLoops());
2190}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002191
Alexey Bataev236070f2014-06-20 11:19:47 +00002192void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2193
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002194void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2195
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002196void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2197
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002198void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2199
Alexey Bataevdea47612014-07-23 07:46:59 +00002200void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2201
Alexey Bataev67a4f222014-07-23 10:25:33 +00002202void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2203
Alexey Bataev459dec02014-07-24 06:46:57 +00002204void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2205
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002206void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2207
Alexey Bataev346265e2015-09-25 10:37:12 +00002208void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2209
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002210void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2211
Alexey Bataevb825de12015-12-07 10:51:44 +00002212void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2213
Kelvin Li1408f912018-09-26 04:28:39 +00002214void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2215 const OMPUnifiedAddressClause *) {}
2216
Patrick Lyster4a370b92018-10-01 13:47:43 +00002217void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2218 const OMPUnifiedSharedMemoryClause *) {}
2219
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002220void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2221 const OMPReverseOffloadClause *) {}
2222
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002223void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2224 const OMPDynamicAllocatorsClause *) {}
2225
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002226void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2227 const OMPAtomicDefaultMemOrderClause *) {}
2228
Michael Wonge710d542015-08-07 16:16:36 +00002229void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2230 Visitor->AddStmt(C->getDevice());
2231}
2232
Kelvin Li099bb8c2015-11-24 20:50:12 +00002233void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002234 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002235 Visitor->AddStmt(C->getNumTeams());
2236}
2237
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002238void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002239 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002240 Visitor->AddStmt(C->getThreadLimit());
2241}
2242
Alexey Bataeva0569352015-12-01 10:17:31 +00002243void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2244 Visitor->AddStmt(C->getPriority());
2245}
2246
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002247void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2248 Visitor->AddStmt(C->getGrainsize());
2249}
2250
Alexey Bataev382967a2015-12-08 12:06:20 +00002251void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2252 Visitor->AddStmt(C->getNumTasks());
2253}
2254
Alexey Bataev28c75412015-12-15 08:19:24 +00002255void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2256 Visitor->AddStmt(C->getHint());
2257}
2258
Alexey Bataev756c1962013-09-24 03:17:45 +00002259template<typename T>
2260void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002261 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002262 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002263 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002264}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002265
Alexey Bataeve04483e2019-03-27 14:14:31 +00002266void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2267 VisitOMPClauseList(C);
2268 Visitor->AddStmt(C->getAllocator());
2269}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002270void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002271 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002272 for (const auto *E : C->private_copies()) {
2273 Visitor->AddStmt(E);
2274 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002275}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002276void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2277 const OMPFirstprivateClause *C) {
2278 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002279 VisitOMPClauseWithPreInit(C);
2280 for (const auto *E : C->private_copies()) {
2281 Visitor->AddStmt(E);
2282 }
2283 for (const auto *E : C->inits()) {
2284 Visitor->AddStmt(E);
2285 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002286}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002287void OMPClauseEnqueue::VisitOMPLastprivateClause(
2288 const OMPLastprivateClause *C) {
2289 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002290 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002291 for (auto *E : C->private_copies()) {
2292 Visitor->AddStmt(E);
2293 }
2294 for (auto *E : C->source_exprs()) {
2295 Visitor->AddStmt(E);
2296 }
2297 for (auto *E : C->destination_exprs()) {
2298 Visitor->AddStmt(E);
2299 }
2300 for (auto *E : C->assignment_ops()) {
2301 Visitor->AddStmt(E);
2302 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002303}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002304void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002305 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002306}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002307void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2308 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002309 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002310 for (auto *E : C->privates()) {
2311 Visitor->AddStmt(E);
2312 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002313 for (auto *E : C->lhs_exprs()) {
2314 Visitor->AddStmt(E);
2315 }
2316 for (auto *E : C->rhs_exprs()) {
2317 Visitor->AddStmt(E);
2318 }
2319 for (auto *E : C->reduction_ops()) {
2320 Visitor->AddStmt(E);
2321 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002322}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002323void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2324 const OMPTaskReductionClause *C) {
2325 VisitOMPClauseList(C);
2326 VisitOMPClauseWithPostUpdate(C);
2327 for (auto *E : C->privates()) {
2328 Visitor->AddStmt(E);
2329 }
2330 for (auto *E : C->lhs_exprs()) {
2331 Visitor->AddStmt(E);
2332 }
2333 for (auto *E : C->rhs_exprs()) {
2334 Visitor->AddStmt(E);
2335 }
2336 for (auto *E : C->reduction_ops()) {
2337 Visitor->AddStmt(E);
2338 }
2339}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002340void OMPClauseEnqueue::VisitOMPInReductionClause(
2341 const OMPInReductionClause *C) {
2342 VisitOMPClauseList(C);
2343 VisitOMPClauseWithPostUpdate(C);
2344 for (auto *E : C->privates()) {
2345 Visitor->AddStmt(E);
2346 }
2347 for (auto *E : C->lhs_exprs()) {
2348 Visitor->AddStmt(E);
2349 }
2350 for (auto *E : C->rhs_exprs()) {
2351 Visitor->AddStmt(E);
2352 }
2353 for (auto *E : C->reduction_ops()) {
2354 Visitor->AddStmt(E);
2355 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002356 for (auto *E : C->taskgroup_descriptors())
2357 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002358}
Alexander Musman8dba6642014-04-22 13:09:42 +00002359void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2360 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002361 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002362 for (const auto *E : C->privates()) {
2363 Visitor->AddStmt(E);
2364 }
Alexander Musman3276a272015-03-21 10:12:56 +00002365 for (const auto *E : C->inits()) {
2366 Visitor->AddStmt(E);
2367 }
2368 for (const auto *E : C->updates()) {
2369 Visitor->AddStmt(E);
2370 }
2371 for (const auto *E : C->finals()) {
2372 Visitor->AddStmt(E);
2373 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002374 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002375 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002376}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002377void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2378 VisitOMPClauseList(C);
2379 Visitor->AddStmt(C->getAlignment());
2380}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002381void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2382 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002383 for (auto *E : C->source_exprs()) {
2384 Visitor->AddStmt(E);
2385 }
2386 for (auto *E : C->destination_exprs()) {
2387 Visitor->AddStmt(E);
2388 }
2389 for (auto *E : C->assignment_ops()) {
2390 Visitor->AddStmt(E);
2391 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002392}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002393void
2394OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2395 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002396 for (auto *E : C->source_exprs()) {
2397 Visitor->AddStmt(E);
2398 }
2399 for (auto *E : C->destination_exprs()) {
2400 Visitor->AddStmt(E);
2401 }
2402 for (auto *E : C->assignment_ops()) {
2403 Visitor->AddStmt(E);
2404 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002405}
Alexey Bataev6125da92014-07-21 11:26:11 +00002406void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2407 VisitOMPClauseList(C);
2408}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002409void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2410 VisitOMPClauseList(C);
2411}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002412void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2413 VisitOMPClauseList(C);
2414}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002415void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2416 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002417 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002418 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002419}
Alexey Bataev3392d762016-02-16 11:18:12 +00002420void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2421 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002422void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2423 VisitOMPClauseList(C);
2424}
Samuel Antaoec172c62016-05-26 17:49:04 +00002425void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2426 VisitOMPClauseList(C);
2427}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002428void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2429 VisitOMPClauseList(C);
2430}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002431void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2432 VisitOMPClauseList(C);
2433}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002434}
Alexey Bataev756c1962013-09-24 03:17:45 +00002435
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002436void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2437 unsigned size = WL.size();
2438 OMPClauseEnqueue Visitor(this);
2439 Visitor.Visit(S);
2440 if (size == WL.size())
2441 return;
2442 // Now reverse the entries we just added. This will match the DFS
2443 // ordering performed by the worklist.
2444 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2445 std::reverse(I, E);
2446}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002447void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2449}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002450void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 AddDecl(B->getBlockDecl());
2452}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002453void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 EnqueueChildren(E);
2455 AddTypeLoc(E->getTypeSourceInfo());
2456}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002457void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002458 for (auto &I : llvm::reverse(S->body()))
2459 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002460}
2461void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002462VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 AddStmt(S->getSubStmt());
2464 AddDeclarationNameInfo(S);
2465 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2466 AddNestedNameSpecifierLoc(QualifierLoc);
2467}
2468
2469void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002470VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002471 if (E->hasExplicitTemplateArgs())
2472 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 AddDeclarationNameInfo(E);
2474 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2475 AddNestedNameSpecifierLoc(QualifierLoc);
2476 if (!E->isImplicitAccess())
2477 AddStmt(E->getBase());
2478}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002479void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 // Enqueue the initializer , if any.
2481 AddStmt(E->getInitializer());
2482 // Enqueue the array size, if any.
2483 AddStmt(E->getArraySize());
2484 // Enqueue the allocated type.
2485 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2486 // Enqueue the placement arguments.
2487 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2488 AddStmt(E->getPlacementArg(I-1));
2489}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002490void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2492 AddStmt(CE->getArg(I-1));
2493 AddStmt(CE->getCallee());
2494 AddStmt(CE->getArg(0));
2495}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002496void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2497 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 // Visit the name of the type being destroyed.
2499 AddTypeLoc(E->getDestroyedTypeInfo());
2500 // Visit the scope type that looks disturbingly like the nested-name-specifier
2501 // but isn't.
2502 AddTypeLoc(E->getScopeTypeInfo());
2503 // Visit the nested-name-specifier.
2504 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2505 AddNestedNameSpecifierLoc(QualifierLoc);
2506 // Visit base expression.
2507 AddStmt(E->getBase());
2508}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002509void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2510 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 AddTypeLoc(E->getTypeSourceInfo());
2512}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002513void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2514 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 EnqueueChildren(E);
2516 AddTypeLoc(E->getTypeSourceInfo());
2517}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002518void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 EnqueueChildren(E);
2520 if (E->isTypeOperand())
2521 AddTypeLoc(E->getTypeOperandSourceInfo());
2522}
2523
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002524void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2525 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 EnqueueChildren(E);
2527 AddTypeLoc(E->getTypeSourceInfo());
2528}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002529void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 EnqueueChildren(E);
2531 if (E->isTypeOperand())
2532 AddTypeLoc(E->getTypeOperandSourceInfo());
2533}
2534
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002535void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 EnqueueChildren(S);
2537 AddDecl(S->getExceptionDecl());
2538}
2539
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002540void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002541 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002542 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002543 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002544}
2545
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002546void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002547 if (DR->hasExplicitTemplateArgs())
2548 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 WL.push_back(DeclRefExprParts(DR, Parent));
2550}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002551void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2552 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002553 if (E->hasExplicitTemplateArgs())
2554 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 AddDeclarationNameInfo(E);
2556 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2557}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002558void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 unsigned size = WL.size();
2560 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002561 for (const auto *D : S->decls()) {
2562 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 isFirst = false;
2564 }
2565 if (size == WL.size())
2566 return;
2567 // Now reverse the entries we just added. This will match the DFS
2568 // ordering performed by the worklist.
2569 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2570 std::reverse(I, E);
2571}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002572void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002574 for (const DesignatedInitExpr::Designator &D :
2575 llvm::reverse(E->designators())) {
2576 if (D.isFieldDesignator()) {
2577 if (FieldDecl *Field = D.getField())
2578 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 continue;
2580 }
David Majnemerf7e36092016-06-23 00:15:04 +00002581 if (D.isArrayDesignator()) {
2582 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 continue;
2584 }
David Majnemerf7e36092016-06-23 00:15:04 +00002585 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2586 AddStmt(E->getArrayRangeEnd(D));
2587 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 }
2589}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002590void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 EnqueueChildren(E);
2592 AddTypeLoc(E->getTypeInfoAsWritten());
2593}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002594void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 AddStmt(FS->getBody());
2596 AddStmt(FS->getInc());
2597 AddStmt(FS->getCond());
2598 AddDecl(FS->getConditionVariable());
2599 AddStmt(FS->getInit());
2600}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002601void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2603}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002604void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 AddStmt(If->getElse());
2606 AddStmt(If->getThen());
2607 AddStmt(If->getCond());
2608 AddDecl(If->getConditionVariable());
2609}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002610void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 // We care about the syntactic form of the initializer list, only.
2612 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2613 IE = Syntactic;
2614 EnqueueChildren(IE);
2615}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002616void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 WL.push_back(MemberExprParts(M, Parent));
2618
2619 // If the base of the member access expression is an implicit 'this', don't
2620 // visit it.
2621 // FIXME: If we ever want to show these implicit accesses, this will be
2622 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002623 if (M->isImplicitAccess())
2624 return;
2625
2626 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002627 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002628 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2629 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2630 if (FD->isAnonymousStructOrUnion()) {
2631 AddStmt(SubME->getBase());
2632 return;
2633 }
2634 }
2635 }
2636
2637 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002638}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002639void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 AddTypeLoc(E->getEncodedTypeSourceInfo());
2641}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002642void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 EnqueueChildren(M);
2644 AddTypeLoc(M->getClassReceiverTypeInfo());
2645}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002646void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 // Visit the components of the offsetof expression.
2648 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 const OffsetOfNode &Node = E->getComponent(I-1);
2650 switch (Node.getKind()) {
2651 case OffsetOfNode::Array:
2652 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2653 break;
2654 case OffsetOfNode::Field:
2655 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2656 break;
2657 case OffsetOfNode::Identifier:
2658 case OffsetOfNode::Base:
2659 continue;
2660 }
2661 }
2662 // Visit the type into which we're computing the offset.
2663 AddTypeLoc(E->getTypeSourceInfo());
2664}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002665void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002666 if (E->hasExplicitTemplateArgs())
2667 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 WL.push_back(OverloadExprParts(E, Parent));
2669}
2670void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002671 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 EnqueueChildren(E);
2673 if (E->isArgumentType())
2674 AddTypeLoc(E->getArgumentTypeInfo());
2675}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002676void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002677 EnqueueChildren(S);
2678}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002679void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 AddStmt(S->getBody());
2681 AddStmt(S->getCond());
2682 AddDecl(S->getConditionVariable());
2683}
2684
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002685void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 AddStmt(W->getBody());
2687 AddStmt(W->getCond());
2688 AddDecl(W->getConditionVariable());
2689}
2690
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002691void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 for (unsigned I = E->getNumArgs(); I > 0; --I)
2693 AddTypeLoc(E->getArg(I-1));
2694}
2695
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002696void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 AddTypeLoc(E->getQueriedTypeSourceInfo());
2698}
2699
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002700void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 EnqueueChildren(E);
2702}
2703
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002704void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 VisitOverloadExpr(U);
2706 if (!U->isImplicitAccess())
2707 AddStmt(U->getBase());
2708}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002709void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 AddStmt(E->getSubExpr());
2711 AddTypeLoc(E->getWrittenTypeInfo());
2712}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002713void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 WL.push_back(SizeOfPackExprParts(E, Parent));
2715}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002716void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 // If the opaque value has a source expression, just transparently
2718 // visit that. This is useful for (e.g.) pseudo-object expressions.
2719 if (Expr *SourceExpr = E->getSourceExpr())
2720 return Visit(SourceExpr);
2721}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002722void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 AddStmt(E->getBody());
2724 WL.push_back(LambdaExprParts(E, Parent));
2725}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002726void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 // Treat the expression like its syntactic form.
2728 Visit(E->getSyntacticForm());
2729}
2730
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002731void EnqueueVisitor::VisitOMPExecutableDirective(
2732 const OMPExecutableDirective *D) {
2733 EnqueueChildren(D);
2734 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2735 E = D->clauses().end();
2736 I != E; ++I)
2737 EnqueueChildren(*I);
2738}
2739
Alexander Musman3aaab662014-08-19 11:27:13 +00002740void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2741 VisitOMPExecutableDirective(D);
2742}
2743
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002744void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2745 VisitOMPExecutableDirective(D);
2746}
2747
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002748void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002749 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002750}
2751
Alexey Bataevf29276e2014-06-18 04:14:57 +00002752void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002753 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002754}
2755
Alexander Musmanf82886e2014-09-18 05:12:34 +00002756void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2757 VisitOMPLoopDirective(D);
2758}
2759
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002760void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2761 VisitOMPExecutableDirective(D);
2762}
2763
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002764void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2765 VisitOMPExecutableDirective(D);
2766}
2767
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002768void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2769 VisitOMPExecutableDirective(D);
2770}
2771
Alexander Musman80c22892014-07-17 08:54:58 +00002772void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2773 VisitOMPExecutableDirective(D);
2774}
2775
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002776void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2777 VisitOMPExecutableDirective(D);
2778 AddDeclarationNameInfo(D);
2779}
2780
Alexey Bataev4acb8592014-07-07 13:01:15 +00002781void
2782EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002783 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002784}
2785
Alexander Musmane4e893b2014-09-23 09:33:00 +00002786void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2787 const OMPParallelForSimdDirective *D) {
2788 VisitOMPLoopDirective(D);
2789}
2790
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002791void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2792 const OMPParallelSectionsDirective *D) {
2793 VisitOMPExecutableDirective(D);
2794}
2795
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002796void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2797 VisitOMPExecutableDirective(D);
2798}
2799
Alexey Bataev68446b72014-07-18 07:47:19 +00002800void
2801EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2802 VisitOMPExecutableDirective(D);
2803}
2804
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002805void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2806 VisitOMPExecutableDirective(D);
2807}
2808
Alexey Bataev2df347a2014-07-18 10:17:07 +00002809void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2810 VisitOMPExecutableDirective(D);
2811}
2812
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002813void EnqueueVisitor::VisitOMPTaskgroupDirective(
2814 const OMPTaskgroupDirective *D) {
2815 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002816 if (const Expr *E = D->getReductionRef())
2817 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002818}
2819
Alexey Bataev6125da92014-07-21 11:26:11 +00002820void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2821 VisitOMPExecutableDirective(D);
2822}
2823
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002824void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2825 VisitOMPExecutableDirective(D);
2826}
2827
Alexey Bataev0162e452014-07-22 10:10:35 +00002828void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2829 VisitOMPExecutableDirective(D);
2830}
2831
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002832void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2833 VisitOMPExecutableDirective(D);
2834}
2835
Michael Wong65f367f2015-07-21 13:44:28 +00002836void EnqueueVisitor::VisitOMPTargetDataDirective(const
2837 OMPTargetDataDirective *D) {
2838 VisitOMPExecutableDirective(D);
2839}
2840
Samuel Antaodf67fc42016-01-19 19:15:56 +00002841void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2842 const OMPTargetEnterDataDirective *D) {
2843 VisitOMPExecutableDirective(D);
2844}
2845
Samuel Antao72590762016-01-19 20:04:50 +00002846void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2847 const OMPTargetExitDataDirective *D) {
2848 VisitOMPExecutableDirective(D);
2849}
2850
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002851void EnqueueVisitor::VisitOMPTargetParallelDirective(
2852 const OMPTargetParallelDirective *D) {
2853 VisitOMPExecutableDirective(D);
2854}
2855
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002856void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2857 const OMPTargetParallelForDirective *D) {
2858 VisitOMPLoopDirective(D);
2859}
2860
Alexey Bataev13314bf2014-10-09 04:18:56 +00002861void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2862 VisitOMPExecutableDirective(D);
2863}
2864
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002865void EnqueueVisitor::VisitOMPCancellationPointDirective(
2866 const OMPCancellationPointDirective *D) {
2867 VisitOMPExecutableDirective(D);
2868}
2869
Alexey Bataev80909872015-07-02 11:25:17 +00002870void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2871 VisitOMPExecutableDirective(D);
2872}
2873
Alexey Bataev49f6e782015-12-01 04:18:41 +00002874void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2875 VisitOMPLoopDirective(D);
2876}
2877
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002878void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2879 const OMPTaskLoopSimdDirective *D) {
2880 VisitOMPLoopDirective(D);
2881}
2882
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002883void EnqueueVisitor::VisitOMPDistributeDirective(
2884 const OMPDistributeDirective *D) {
2885 VisitOMPLoopDirective(D);
2886}
2887
Carlo Bertolli9925f152016-06-27 14:55:37 +00002888void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2889 const OMPDistributeParallelForDirective *D) {
2890 VisitOMPLoopDirective(D);
2891}
2892
Kelvin Li4a39add2016-07-05 05:00:15 +00002893void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2894 const OMPDistributeParallelForSimdDirective *D) {
2895 VisitOMPLoopDirective(D);
2896}
2897
Kelvin Li787f3fc2016-07-06 04:45:38 +00002898void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2899 const OMPDistributeSimdDirective *D) {
2900 VisitOMPLoopDirective(D);
2901}
2902
Kelvin Lia579b912016-07-14 02:54:56 +00002903void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2904 const OMPTargetParallelForSimdDirective *D) {
2905 VisitOMPLoopDirective(D);
2906}
2907
Kelvin Li986330c2016-07-20 22:57:10 +00002908void EnqueueVisitor::VisitOMPTargetSimdDirective(
2909 const OMPTargetSimdDirective *D) {
2910 VisitOMPLoopDirective(D);
2911}
2912
Kelvin Li02532872016-08-05 14:37:37 +00002913void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2914 const OMPTeamsDistributeDirective *D) {
2915 VisitOMPLoopDirective(D);
2916}
2917
Kelvin Li4e325f72016-10-25 12:50:55 +00002918void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2919 const OMPTeamsDistributeSimdDirective *D) {
2920 VisitOMPLoopDirective(D);
2921}
2922
Kelvin Li579e41c2016-11-30 23:51:03 +00002923void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2924 const OMPTeamsDistributeParallelForSimdDirective *D) {
2925 VisitOMPLoopDirective(D);
2926}
2927
Kelvin Li7ade93f2016-12-09 03:24:30 +00002928void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2929 const OMPTeamsDistributeParallelForDirective *D) {
2930 VisitOMPLoopDirective(D);
2931}
2932
Kelvin Libf594a52016-12-17 05:48:59 +00002933void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2934 const OMPTargetTeamsDirective *D) {
2935 VisitOMPExecutableDirective(D);
2936}
2937
Kelvin Li83c451e2016-12-25 04:52:54 +00002938void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2939 const OMPTargetTeamsDistributeDirective *D) {
2940 VisitOMPLoopDirective(D);
2941}
2942
Kelvin Li80e8f562016-12-29 22:16:30 +00002943void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2944 const OMPTargetTeamsDistributeParallelForDirective *D) {
2945 VisitOMPLoopDirective(D);
2946}
2947
Kelvin Li1851df52017-01-03 05:23:48 +00002948void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2949 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2950 VisitOMPLoopDirective(D);
2951}
2952
Kelvin Lida681182017-01-10 18:08:18 +00002953void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2954 const OMPTargetTeamsDistributeSimdDirective *D) {
2955 VisitOMPLoopDirective(D);
2956}
2957
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002958void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2960}
2961
2962bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2963 if (RegionOfInterest.isValid()) {
2964 SourceRange Range = getRawCursorExtent(C);
2965 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2966 return false;
2967 }
2968 return true;
2969}
2970
2971bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2972 while (!WL.empty()) {
2973 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002974 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002975
2976 // Set the Parent field, then back to its old value once we're done.
2977 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2978
2979 switch (LI.getKind()) {
2980 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002981 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 if (!D)
2983 continue;
2984
2985 // For now, perform default visitation for Decls.
2986 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2987 cast<DeclVisit>(&LI)->isFirst())))
2988 return true;
2989
2990 continue;
2991 }
2992 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002993 for (const TemplateArgumentLoc &Arg :
2994 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2995 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 return true;
2997 }
2998 continue;
2999 }
3000 case VisitorJob::TypeLocVisitKind: {
3001 // Perform default visitation for TypeLocs.
3002 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3003 return true;
3004 continue;
3005 }
3006 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003007 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003008 if (LabelStmt *stmt = LS->getStmt()) {
3009 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3010 TU))) {
3011 return true;
3012 }
3013 }
3014 continue;
3015 }
3016
3017 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3018 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3019 if (VisitNestedNameSpecifierLoc(V->get()))
3020 return true;
3021 continue;
3022 }
3023
3024 case VisitorJob::DeclarationNameInfoVisitKind: {
3025 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3026 ->get()))
3027 return true;
3028 continue;
3029 }
3030 case VisitorJob::MemberRefVisitKind: {
3031 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3032 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3033 return true;
3034 continue;
3035 }
3036 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003037 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 if (!S)
3039 continue;
3040
3041 // Update the current cursor.
3042 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3043 if (!IsInRegionOfInterest(Cursor))
3044 continue;
3045 switch (Visitor(Cursor, Parent, ClientData)) {
3046 case CXChildVisit_Break: return true;
3047 case CXChildVisit_Continue: break;
3048 case CXChildVisit_Recurse:
3049 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003050 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 EnqueueWorkList(WL, S);
3052 break;
3053 }
3054 continue;
3055 }
3056 case VisitorJob::MemberExprPartsKind: {
3057 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003058 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003059
3060 // Visit the nested-name-specifier
3061 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3062 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3063 return true;
3064
3065 // Visit the declaration name.
3066 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3067 return true;
3068
3069 // Visit the explicitly-specified template arguments, if any.
3070 if (M->hasExplicitTemplateArgs()) {
3071 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3072 *ArgEnd = Arg + M->getNumTemplateArgs();
3073 Arg != ArgEnd; ++Arg) {
3074 if (VisitTemplateArgumentLoc(*Arg))
3075 return true;
3076 }
3077 }
3078 continue;
3079 }
3080 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003081 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 // Visit nested-name-specifier, if present.
3083 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3084 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3085 return true;
3086 // Visit declaration name.
3087 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3088 return true;
3089 continue;
3090 }
3091 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003092 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003093 // Visit the nested-name-specifier.
3094 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3095 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3096 return true;
3097 // Visit the declaration name.
3098 if (VisitDeclarationNameInfo(O->getNameInfo()))
3099 return true;
3100 // Visit the overloaded declaration reference.
3101 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3102 return true;
3103 continue;
3104 }
3105 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003106 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 NamedDecl *Pack = E->getPack();
3108 if (isa<TemplateTypeParmDecl>(Pack)) {
3109 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3110 E->getPackLoc(), TU)))
3111 return true;
3112
3113 continue;
3114 }
3115
3116 if (isa<TemplateTemplateParmDecl>(Pack)) {
3117 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3118 E->getPackLoc(), TU)))
3119 return true;
3120
3121 continue;
3122 }
3123
3124 // Non-type template parameter packs and function parameter packs are
3125 // treated like DeclRefExpr cursors.
3126 continue;
3127 }
3128
3129 case VisitorJob::LambdaExprPartsKind: {
3130 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003131 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3133 CEnd = E->explicit_capture_end();
3134 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003135 // FIXME: Lambda init-captures.
3136 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003138
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3140 C->getLocation(),
3141 TU)))
3142 return true;
3143 }
3144
Haojian Wuef87c262018-12-18 15:29:12 +00003145 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003147 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3148 if (E->hasExplicitParameters()) {
3149 // Visit parameters.
3150 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3151 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003153 }
3154 if (E->hasExplicitResultType()) {
3155 // Visit result type.
3156 if (Visit(Proto.getReturnLoc()))
3157 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 }
3159 }
3160 break;
3161 }
3162
3163 case VisitorJob::PostChildrenVisitKind:
3164 if (PostChildrenVisitor(Parent, ClientData))
3165 return true;
3166 break;
3167 }
3168 }
3169 return false;
3170}
3171
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003172bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003173 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003174 if (!WorkListFreeList.empty()) {
3175 WL = WorkListFreeList.back();
3176 WL->clear();
3177 WorkListFreeList.pop_back();
3178 }
3179 else {
3180 WL = new VisitorWorkList();
3181 WorkListCache.push_back(WL);
3182 }
3183 EnqueueWorkList(*WL, S);
3184 bool result = RunVisitorWorkList(*WL);
3185 WorkListFreeList.push_back(WL);
3186 return result;
3187}
3188
3189namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003190typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003191RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3192 const DeclarationNameInfo &NI, SourceRange QLoc,
3193 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3195 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3196 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3197
3198 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3199
3200 RefNamePieces Pieces;
3201
3202 if (WantQualifier && QLoc.isValid())
3203 Pieces.push_back(QLoc);
3204
3205 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3206 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003207
3208 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3209 Pieces.push_back(*TemplateArgsLoc);
3210
Guy Benyei11169dd2012-12-18 14:30:41 +00003211 if (Kind == DeclarationName::CXXOperatorName) {
3212 Pieces.push_back(SourceLocation::getFromRawEncoding(
3213 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3214 Pieces.push_back(SourceLocation::getFromRawEncoding(
3215 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3216 }
3217
3218 if (WantSinglePiece) {
3219 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3220 Pieces.clear();
3221 Pieces.push_back(R);
3222 }
3223
3224 return Pieces;
3225}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003226}
Guy Benyei11169dd2012-12-18 14:30:41 +00003227
3228//===----------------------------------------------------------------------===//
3229// Misc. API hooks.
3230//===----------------------------------------------------------------------===//
3231
Chad Rosier05c71aa2013-03-27 18:28:23 +00003232static void fatal_error_handler(void *user_data, const std::string& reason,
3233 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 // Write the result out to stderr avoiding errs() because raw_ostreams can
3235 // call report_fatal_error.
3236 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3237 ::abort();
3238}
3239
Chandler Carruth66660742014-06-27 16:37:27 +00003240namespace {
3241struct RegisterFatalErrorHandler {
3242 RegisterFatalErrorHandler() {
3243 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3244 }
3245};
3246}
3247
3248static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3249
Guy Benyei11169dd2012-12-18 14:30:41 +00003250CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3251 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003252 // We use crash recovery to make some of our APIs more reliable, implicitly
3253 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003254 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3255 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003256
Chandler Carruth66660742014-06-27 16:37:27 +00003257 // Look through the managed static to trigger construction of the managed
3258 // static which registers our fatal error handler. This ensures it is only
3259 // registered once.
3260 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003261
Adrian Prantlbc068582015-07-08 01:00:30 +00003262 // Initialize targets for clang module support.
3263 llvm::InitializeAllTargets();
3264 llvm::InitializeAllTargetMCs();
3265 llvm::InitializeAllAsmPrinters();
3266 llvm::InitializeAllAsmParsers();
3267
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003268 CIndexer *CIdxr = new CIndexer();
3269
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 if (excludeDeclarationsFromPCH)
3271 CIdxr->setOnlyLocalDecls();
3272 if (displayDiagnostics)
3273 CIdxr->setDisplayDiagnostics();
3274
3275 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3276 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3277 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3278 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3279 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3280 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3281
3282 return CIdxr;
3283}
3284
3285void clang_disposeIndex(CXIndex CIdx) {
3286 if (CIdx)
3287 delete static_cast<CIndexer *>(CIdx);
3288}
3289
3290void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3291 if (CIdx)
3292 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3293}
3294
3295unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3296 if (CIdx)
3297 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3298 return 0;
3299}
3300
Alex Lorenz08615792017-12-04 21:56:36 +00003301void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3302 const char *Path) {
3303 if (CIdx)
3304 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3305}
3306
Guy Benyei11169dd2012-12-18 14:30:41 +00003307void clang_toggleCrashRecovery(unsigned isEnabled) {
3308 if (isEnabled)
3309 llvm::CrashRecoveryContext::Enable();
3310 else
3311 llvm::CrashRecoveryContext::Disable();
3312}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003313
Guy Benyei11169dd2012-12-18 14:30:41 +00003314CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3315 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003316 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003317 enum CXErrorCode Result =
3318 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003319 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003320 assert((TU && Result == CXError_Success) ||
3321 (!TU && Result != CXError_Success));
3322 return TU;
3323}
3324
3325enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3326 const char *ast_filename,
3327 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003328 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003329 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003330
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003331 if (!CIdx || !ast_filename || !out_TU)
3332 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003333
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003334 LOG_FUNC_SECTION {
3335 *Log << ast_filename;
3336 }
3337
Guy Benyei11169dd2012-12-18 14:30:41 +00003338 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3339 FileSystemOptions FileSystemOpts;
3340
Justin Bognerd512c1e2014-10-15 00:33:06 +00003341 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3342 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003343 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003344 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3345 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003346 FileSystemOpts, /*UseDebugInfo=*/false,
3347 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003348 /*CaptureDiagnostics=*/true,
3349 /*AllowPCHWithCompilerErrors=*/true,
3350 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003351 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003352 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003353}
3354
3355unsigned clang_defaultEditingTranslationUnitOptions() {
3356 return CXTranslationUnit_PrecompiledPreamble |
3357 CXTranslationUnit_CacheCompletionResults;
3358}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003359
Guy Benyei11169dd2012-12-18 14:30:41 +00003360CXTranslationUnit
3361clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3362 const char *source_filename,
3363 int num_command_line_args,
3364 const char * const *command_line_args,
3365 unsigned num_unsaved_files,
3366 struct CXUnsavedFile *unsaved_files) {
3367 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3368 return clang_parseTranslationUnit(CIdx, source_filename,
3369 command_line_args, num_command_line_args,
3370 unsaved_files, num_unsaved_files,
3371 Options);
3372}
3373
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003374static CXErrorCode
3375clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3376 const char *const *command_line_args,
3377 int num_command_line_args,
3378 ArrayRef<CXUnsavedFile> unsaved_files,
3379 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003380 // Set up the initial return values.
3381 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003382 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003383
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003384 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003385 if (!CIdx || !out_TU)
3386 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003387
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3389
3390 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3391 setThreadBackgroundPriority();
3392
3393 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003394 bool CreatePreambleOnFirstParse =
3395 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003396 // FIXME: Add a flag for modules.
3397 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003398 = (options & (CXTranslationUnit_Incomplete |
3399 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003400 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003401 = options & CXTranslationUnit_CacheCompletionResults;
3402 bool IncludeBriefCommentsInCodeCompletion
3403 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003404 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3405 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003406 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3407 if (options & CXTranslationUnit_SkipFunctionBodies) {
3408 SkipFunctionBodies =
3409 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3410 ? SkipFunctionBodiesScope::Preamble
3411 : SkipFunctionBodiesScope::PreambleAndMainFile;
3412 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003413
3414 // Configure the diagnostics.
3415 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003416 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003417
Manuel Klimek016c0242016-03-01 10:56:19 +00003418 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003419 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003420
Guy Benyei11169dd2012-12-18 14:30:41 +00003421 // Recover resources if we crash before exiting this function.
3422 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3423 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003424 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003425
Ahmed Charlesb8984322014-03-07 20:03:18 +00003426 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3427 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003428
3429 // Recover resources if we crash before exiting this function.
3430 llvm::CrashRecoveryContextCleanupRegistrar<
3431 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3432
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003433 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003434 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003435 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003436 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003437 }
3438
Ahmed Charlesb8984322014-03-07 20:03:18 +00003439 std::unique_ptr<std::vector<const char *>> Args(
3440 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003441
3442 // Recover resources if we crash before exiting this method.
3443 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3444 ArgsCleanup(Args.get());
3445
3446 // Since the Clang C library is primarily used by batch tools dealing with
3447 // (often very broken) source code, where spell-checking can have a
3448 // significant negative impact on performance (particularly when
3449 // precompiled headers are involved), we disable it by default.
3450 // Only do this if we haven't found a spell-checking-related argument.
3451 bool FoundSpellCheckingArgument = false;
3452 for (int I = 0; I != num_command_line_args; ++I) {
3453 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3454 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3455 FoundSpellCheckingArgument = true;
3456 break;
3457 }
3458 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003459 Args->insert(Args->end(), command_line_args,
3460 command_line_args + num_command_line_args);
3461
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003462 if (!FoundSpellCheckingArgument)
3463 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3464
Guy Benyei11169dd2012-12-18 14:30:41 +00003465 // The 'source_filename' argument is optional. If the caller does not
3466 // specify it then it is assumed that the source file is specified
3467 // in the actual argument list.
3468 // Put the source file after command_line_args otherwise if '-x' flag is
3469 // present it will be unused.
3470 if (source_filename)
3471 Args->push_back(source_filename);
3472
3473 // Do we need the detailed preprocessing record?
3474 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3475 Args->push_back("-Xclang");
3476 Args->push_back("-detailed-preprocessing-record");
3477 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003478
3479 // Suppress any editor placeholder diagnostics.
3480 Args->push_back("-fallow-editor-placeholders");
3481
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003483 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003484 // Unless the user specified that they want the preamble on the first parse
3485 // set it up to be created on the first reparse. This makes the first parse
3486 // faster, trading for a slower (first) reparse.
3487 unsigned PrecompilePreambleAfterNParses =
3488 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003489
Alex Lorenz08615792017-12-04 21:56:36 +00003490 LibclangInvocationReporter InvocationReporter(
3491 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003492 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3493 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003494 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003495 Args->data(), Args->data() + Args->size(),
3496 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003497 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3498 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003499 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3500 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003501 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003502 /*UserFilesAreVolatile=*/true, ForSerialization,
3503 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3504 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003505
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003506 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003507 if (!Unit && !ErrUnit)
3508 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003509
Guy Benyei11169dd2012-12-18 14:30:41 +00003510 if (NumErrors != Diags->getClient()->getNumErrors()) {
3511 // Make sure to check that 'Unit' is non-NULL.
3512 if (CXXIdx->getDisplayDiagnostics())
3513 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3514 }
3515
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003516 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3517 return CXError_ASTReadError;
3518
David Blaikieea4395e2017-01-06 19:49:01 +00003519 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003520 if (CXTranslationUnitImpl *TU = *out_TU) {
3521 TU->ParsingOptions = options;
3522 TU->Arguments.reserve(Args->size());
3523 for (const char *Arg : *Args)
3524 TU->Arguments.push_back(Arg);
3525 return CXError_Success;
3526 }
3527 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003528}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003529
3530CXTranslationUnit
3531clang_parseTranslationUnit(CXIndex CIdx,
3532 const char *source_filename,
3533 const char *const *command_line_args,
3534 int num_command_line_args,
3535 struct CXUnsavedFile *unsaved_files,
3536 unsigned num_unsaved_files,
3537 unsigned options) {
3538 CXTranslationUnit TU;
3539 enum CXErrorCode Result = clang_parseTranslationUnit2(
3540 CIdx, source_filename, command_line_args, num_command_line_args,
3541 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003542 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003543 assert((TU && Result == CXError_Success) ||
3544 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003545 return TU;
3546}
3547
3548enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003549 CXIndex CIdx, const char *source_filename,
3550 const char *const *command_line_args, int num_command_line_args,
3551 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3552 unsigned options, CXTranslationUnit *out_TU) {
3553 SmallVector<const char *, 4> Args;
3554 Args.push_back("clang");
3555 Args.append(command_line_args, command_line_args + num_command_line_args);
3556 return clang_parseTranslationUnit2FullArgv(
3557 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3558 num_unsaved_files, options, out_TU);
3559}
3560
3561enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3562 CXIndex CIdx, const char *source_filename,
3563 const char *const *command_line_args, int num_command_line_args,
3564 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3565 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003566 LOG_FUNC_SECTION {
3567 *Log << source_filename << ": ";
3568 for (int i = 0; i != num_command_line_args; ++i)
3569 *Log << command_line_args[i] << " ";
3570 }
3571
Alp Toker9d85b182014-07-07 01:23:14 +00003572 if (num_unsaved_files && !unsaved_files)
3573 return CXError_InvalidArguments;
3574
Alp Toker5c532982014-07-07 22:42:03 +00003575 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003576 auto ParseTranslationUnitImpl = [=, &result] {
3577 result = clang_parseTranslationUnit_Impl(
3578 CIdx, source_filename, command_line_args, num_command_line_args,
3579 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3580 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003581
Guy Benyei11169dd2012-12-18 14:30:41 +00003582 llvm::CrashRecoveryContext CRC;
3583
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003584 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003585 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3586 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3587 fprintf(stderr, " 'command_line_args' : [");
3588 for (int i = 0; i != num_command_line_args; ++i) {
3589 if (i)
3590 fprintf(stderr, ", ");
3591 fprintf(stderr, "'%s'", command_line_args[i]);
3592 }
3593 fprintf(stderr, "],\n");
3594 fprintf(stderr, " 'unsaved_files' : [");
3595 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3596 if (i)
3597 fprintf(stderr, ", ");
3598 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3599 unsaved_files[i].Length);
3600 }
3601 fprintf(stderr, "],\n");
3602 fprintf(stderr, " 'options' : %d,\n", options);
3603 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003604
3605 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003606 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003607 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003608 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003609 }
Alp Toker5c532982014-07-07 22:42:03 +00003610
3611 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003612}
3613
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003614CXString clang_Type_getObjCEncoding(CXType CT) {
3615 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3616 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3617 std::string encoding;
3618 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3619 encoding);
3620
3621 return cxstring::createDup(encoding);
3622}
3623
3624static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3625 if (C.kind == CXCursor_MacroDefinition) {
3626 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3627 return MDR->getName();
3628 } else if (C.kind == CXCursor_MacroExpansion) {
3629 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3630 return ME.getName();
3631 }
3632 return nullptr;
3633}
3634
3635unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3636 const IdentifierInfo *II = getMacroIdentifier(C);
3637 if (!II) {
3638 return false;
3639 }
3640 ASTUnit *ASTU = getCursorASTUnit(C);
3641 Preprocessor &PP = ASTU->getPreprocessor();
3642 if (const MacroInfo *MI = PP.getMacroInfo(II))
3643 return MI->isFunctionLike();
3644 return false;
3645}
3646
3647unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3648 const IdentifierInfo *II = getMacroIdentifier(C);
3649 if (!II) {
3650 return false;
3651 }
3652 ASTUnit *ASTU = getCursorASTUnit(C);
3653 Preprocessor &PP = ASTU->getPreprocessor();
3654 if (const MacroInfo *MI = PP.getMacroInfo(II))
3655 return MI->isBuiltinMacro();
3656 return false;
3657}
3658
3659unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3660 const Decl *D = getCursorDecl(C);
3661 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3662 if (!FD) {
3663 return false;
3664 }
3665 return FD->isInlined();
3666}
3667
3668static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3669 if (callExpr->getNumArgs() != 1) {
3670 return nullptr;
3671 }
3672
3673 StringLiteral *S = nullptr;
3674 auto *arg = callExpr->getArg(0);
3675 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3676 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3677 auto *subExpr = I->getSubExprAsWritten();
3678
3679 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3680 return nullptr;
3681 }
3682
3683 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3684 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3685 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3686 } else {
3687 return nullptr;
3688 }
3689 return S;
3690}
3691
David Blaikie59272572016-04-13 18:23:33 +00003692struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003693 CXEvalResultKind EvalType;
3694 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003695 unsigned long long unsignedVal;
3696 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003697 double floatVal;
3698 char *stringVal;
3699 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003700 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003701 ~ExprEvalResult() {
3702 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3703 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003704 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003705 }
3706 }
3707};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003708
3709void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003710 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003711}
3712
3713CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3714 if (!E) {
3715 return CXEval_UnExposed;
3716 }
3717 return ((ExprEvalResult *)E)->EvalType;
3718}
3719
3720int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003721 return clang_EvalResult_getAsLongLong(E);
3722}
3723
3724long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003725 if (!E) {
3726 return 0;
3727 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003728 ExprEvalResult *Result = (ExprEvalResult*)E;
3729 if (Result->IsUnsignedInt)
3730 return Result->EvalData.unsignedVal;
3731 return Result->EvalData.intVal;
3732}
3733
3734unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3735 return ((ExprEvalResult *)E)->IsUnsignedInt;
3736}
3737
3738unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3739 if (!E) {
3740 return 0;
3741 }
3742
3743 ExprEvalResult *Result = (ExprEvalResult*)E;
3744 if (Result->IsUnsignedInt)
3745 return Result->EvalData.unsignedVal;
3746 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003747}
3748
3749double clang_EvalResult_getAsDouble(CXEvalResult E) {
3750 if (!E) {
3751 return 0;
3752 }
3753 return ((ExprEvalResult *)E)->EvalData.floatVal;
3754}
3755
3756const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3757 if (!E) {
3758 return nullptr;
3759 }
3760 return ((ExprEvalResult *)E)->EvalData.stringVal;
3761}
3762
3763static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3764 Expr::EvalResult ER;
3765 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003766 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003767 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003768
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003769 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003770 if (!expr->EvaluateAsRValue(ER, ctx))
3771 return nullptr;
3772
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003773 QualType rettype;
3774 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003775 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003776 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003777 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003778
David Blaikiebbc00882016-04-13 18:36:19 +00003779 if (ER.Val.isInt()) {
3780 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003781
3782 auto& val = ER.Val.getInt();
3783 if (val.isUnsigned()) {
3784 result->IsUnsignedInt = true;
3785 result->EvalData.unsignedVal = val.getZExtValue();
3786 } else {
3787 result->EvalData.intVal = val.getExtValue();
3788 }
3789
David Blaikiebbc00882016-04-13 18:36:19 +00003790 return result.release();
3791 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003792
David Blaikiebbc00882016-04-13 18:36:19 +00003793 if (ER.Val.isFloat()) {
3794 llvm::SmallVector<char, 100> Buffer;
3795 ER.Val.getFloat().toString(Buffer);
3796 std::string floatStr(Buffer.data(), Buffer.size());
3797 result->EvalType = CXEval_Float;
3798 bool ignored;
3799 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003800 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003801 llvm::APFloat::rmNearestTiesToEven, &ignored);
3802 result->EvalData.floatVal = apFloat.convertToDouble();
3803 return result.release();
3804 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003805
David Blaikiebbc00882016-04-13 18:36:19 +00003806 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3807 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3808 auto *subExpr = I->getSubExprAsWritten();
3809 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3810 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003811 const StringLiteral *StrE = nullptr;
3812 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003813 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003814
3815 if (ObjCExpr) {
3816 StrE = ObjCExpr->getString();
3817 result->EvalType = CXEval_ObjCStrLiteral;
3818 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003819 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003820 result->EvalType = CXEval_StrLiteral;
3821 }
3822
3823 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003824 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003825 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3826 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003827 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003828 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003829 }
3830 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3831 expr->getStmtClass() == Stmt::StringLiteralClass) {
3832 const StringLiteral *StrE = nullptr;
3833 const ObjCStringLiteral *ObjCExpr;
3834 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003835
David Blaikiebbc00882016-04-13 18:36:19 +00003836 if (ObjCExpr) {
3837 StrE = ObjCExpr->getString();
3838 result->EvalType = CXEval_ObjCStrLiteral;
3839 } else {
3840 StrE = cast<StringLiteral>(expr);
3841 result->EvalType = CXEval_StrLiteral;
3842 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003843
David Blaikiebbc00882016-04-13 18:36:19 +00003844 std::string strRef(StrE->getString().str());
3845 result->EvalData.stringVal = new char[strRef.size() + 1];
3846 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3847 result->EvalData.stringVal[strRef.size()] = '\0';
3848 return result.release();
3849 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003850
David Blaikiebbc00882016-04-13 18:36:19 +00003851 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3852 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003853
David Blaikiebbc00882016-04-13 18:36:19 +00003854 rettype = CC->getType();
3855 if (rettype.getAsString() == "CFStringRef" &&
3856 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003857
David Blaikiebbc00882016-04-13 18:36:19 +00003858 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3859 StringLiteral *S = getCFSTR_value(callExpr);
3860 if (S) {
3861 std::string strLiteral(S->getString().str());
3862 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003863
David Blaikiebbc00882016-04-13 18:36:19 +00003864 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3865 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3866 strLiteral.size());
3867 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003868 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003869 }
3870 }
3871
David Blaikiebbc00882016-04-13 18:36:19 +00003872 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3873 callExpr = static_cast<CallExpr *>(expr);
3874 rettype = callExpr->getCallReturnType(ctx);
3875
3876 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3877 return nullptr;
3878
3879 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3880 if (callExpr->getNumArgs() == 1 &&
3881 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3882 return nullptr;
3883 } else if (rettype.getAsString() == "CFStringRef") {
3884
3885 StringLiteral *S = getCFSTR_value(callExpr);
3886 if (S) {
3887 std::string strLiteral(S->getString().str());
3888 result->EvalType = CXEval_CFStr;
3889 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3890 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3891 strLiteral.size());
3892 result->EvalData.stringVal[strLiteral.size()] = '\0';
3893 return result.release();
3894 }
3895 }
3896 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3897 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3898 ValueDecl *V = D->getDecl();
3899 if (V->getKind() == Decl::Function) {
3900 std::string strName = V->getNameAsString();
3901 result->EvalType = CXEval_Other;
3902 result->EvalData.stringVal = new char[strName.size() + 1];
3903 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3904 result->EvalData.stringVal[strName.size()] = '\0';
3905 return result.release();
3906 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003907 }
3908
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003909 return nullptr;
3910}
3911
Alex Lorenz65317e12019-01-08 22:32:51 +00003912static const Expr *evaluateDeclExpr(const Decl *D) {
3913 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003914 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003915 if (auto *Var = dyn_cast<VarDecl>(D))
3916 return Var->getInit();
3917 else if (auto *Field = dyn_cast<FieldDecl>(D))
3918 return Field->getInClassInitializer();
3919 return nullptr;
3920}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003921
Alex Lorenz65317e12019-01-08 22:32:51 +00003922static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3923 assert(CS && "invalid compound statement");
3924 for (auto *bodyIterator : CS->body()) {
3925 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3926 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003927 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003928 return nullptr;
3929}
3930
Alex Lorenz65317e12019-01-08 22:32:51 +00003931CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3932 if (const Expr *E =
3933 clang_getCursorKind(C) == CXCursor_CompoundStmt
3934 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3935 : evaluateDeclExpr(getCursorDecl(C)))
3936 return const_cast<CXEvalResult>(
3937 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3938 return nullptr;
3939}
3940
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003941unsigned clang_Cursor_hasAttrs(CXCursor C) {
3942 const Decl *D = getCursorDecl(C);
3943 if (!D) {
3944 return 0;
3945 }
3946
3947 if (D->hasAttrs()) {
3948 return 1;
3949 }
3950
3951 return 0;
3952}
Guy Benyei11169dd2012-12-18 14:30:41 +00003953unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3954 return CXSaveTranslationUnit_None;
3955}
3956
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003957static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3958 const char *FileName,
3959 unsigned options) {
3960 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3962 setThreadBackgroundPriority();
3963
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003964 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3965 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003966}
3967
3968int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3969 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003970 LOG_FUNC_SECTION {
3971 *Log << TU << ' ' << FileName;
3972 }
3973
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003974 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003975 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003977 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003978
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003979 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3981 if (!CXXUnit->hasSema())
3982 return CXSaveError_InvalidTU;
3983
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003984 CXSaveError result;
3985 auto SaveTranslationUnitImpl = [=, &result]() {
3986 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3987 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003988
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003989 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003990 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003991
3992 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3993 PrintLibclangResourceUsage(TU);
3994
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003995 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003996 }
3997
3998 // We have an AST that has invalid nodes due to compiler errors.
3999 // Use a crash recovery thread for protection.
4000
4001 llvm::CrashRecoveryContext CRC;
4002
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004003 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4005 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4006 fprintf(stderr, " 'options' : %d,\n", options);
4007 fprintf(stderr, "}\n");
4008
4009 return CXSaveError_Unknown;
4010
4011 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4012 PrintLibclangResourceUsage(TU);
4013 }
4014
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004015 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004016}
4017
4018void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4019 if (CTUnit) {
4020 // If the translation unit has been marked as unsafe to free, just discard
4021 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004022 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4023 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 return;
4025
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004026 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004027 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004028 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4029 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004030 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004031 delete CTUnit;
4032 }
4033}
4034
Erik Verbruggen346066b2017-05-30 14:25:54 +00004035unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4036 if (CTUnit) {
4037 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4038
4039 if (Unit && Unit->isUnsafeToFree())
4040 return false;
4041
4042 Unit->ResetForParse();
4043 return true;
4044 }
4045
4046 return false;
4047}
4048
Guy Benyei11169dd2012-12-18 14:30:41 +00004049unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4050 return CXReparse_None;
4051}
4052
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004053static CXErrorCode
4054clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4055 ArrayRef<CXUnsavedFile> unsaved_files,
4056 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004057 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004058 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004059 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004060 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004061 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004062
4063 // Reset the associated diagnostics.
4064 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004065 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004066
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004067 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004068 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4069 setThreadBackgroundPriority();
4070
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004071 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004073
4074 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4075 new std::vector<ASTUnit::RemappedFile>());
4076
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 // Recover resources if we crash before exiting this function.
4078 llvm::CrashRecoveryContextCleanupRegistrar<
4079 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004080
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004081 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004082 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004083 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004084 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004085 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004086
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004087 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4088 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004089 return CXError_Success;
4090 if (isASTReadError(CXXUnit))
4091 return CXError_ASTReadError;
4092 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004093}
4094
4095int clang_reparseTranslationUnit(CXTranslationUnit TU,
4096 unsigned num_unsaved_files,
4097 struct CXUnsavedFile *unsaved_files,
4098 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004099 LOG_FUNC_SECTION {
4100 *Log << TU;
4101 }
4102
Alp Toker9d85b182014-07-07 01:23:14 +00004103 if (num_unsaved_files && !unsaved_files)
4104 return CXError_InvalidArguments;
4105
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004106 CXErrorCode result;
4107 auto ReparseTranslationUnitImpl = [=, &result]() {
4108 result = clang_reparseTranslationUnit_Impl(
4109 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4110 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004111
Guy Benyei11169dd2012-12-18 14:30:41 +00004112 llvm::CrashRecoveryContext CRC;
4113
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004114 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004116 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004117 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4119 PrintLibclangResourceUsage(TU);
4120
Alp Toker5c532982014-07-07 22:42:03 +00004121 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004122}
4123
4124
4125CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004126 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004127 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004128 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004129 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004130
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004131 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004132 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004133}
4134
4135CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004136 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004137 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004138 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004139 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004140
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004141 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004142 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4143}
4144
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004145CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4146 if (isNotUsableTU(CTUnit)) {
4147 LOG_BAD_TU(CTUnit);
4148 return nullptr;
4149 }
4150
4151 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4152 impl->TranslationUnit = CTUnit;
4153 return impl;
4154}
4155
4156CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4157 if (!TargetInfo)
4158 return cxstring::createEmpty();
4159
4160 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4161 assert(!isNotUsableTU(CTUnit) &&
4162 "Unexpected unusable translation unit in TargetInfo");
4163
4164 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4165 std::string Triple =
4166 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4167 return cxstring::createDup(Triple);
4168}
4169
4170int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4171 if (!TargetInfo)
4172 return -1;
4173
4174 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4175 assert(!isNotUsableTU(CTUnit) &&
4176 "Unexpected unusable translation unit in TargetInfo");
4177
4178 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4179 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4180}
4181
4182void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4183 if (!TargetInfo)
4184 return;
4185
4186 delete TargetInfo;
4187}
4188
Guy Benyei11169dd2012-12-18 14:30:41 +00004189//===----------------------------------------------------------------------===//
4190// CXFile Operations.
4191//===----------------------------------------------------------------------===//
4192
Guy Benyei11169dd2012-12-18 14:30:41 +00004193CXString clang_getFileName(CXFile SFile) {
4194 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004195 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004196
4197 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004198 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004199}
4200
4201time_t clang_getFileTime(CXFile SFile) {
4202 if (!SFile)
4203 return 0;
4204
4205 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4206 return FEnt->getModificationTime();
4207}
4208
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004209CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004210 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004211 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004212 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004213 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004214
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004215 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004216
4217 FileManager &FMgr = CXXUnit->getFileManager();
4218 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4219}
4220
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004221const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4222 size_t *size) {
4223 if (isNotUsableTU(TU)) {
4224 LOG_BAD_TU(TU);
4225 return nullptr;
4226 }
4227
4228 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4229 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4230 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004231 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004232 if (Invalid) {
4233 if (size)
4234 *size = 0;
4235 return nullptr;
4236 }
4237 if (size)
4238 *size = buf->getBufferSize();
4239 return buf->getBufferStart();
4240}
4241
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004242unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4243 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004244 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004245 LOG_BAD_TU(TU);
4246 return 0;
4247 }
4248
4249 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 return 0;
4251
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004252 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 FileEntry *FEnt = static_cast<FileEntry *>(file);
4254 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4255 .isFileMultipleIncludeGuarded(FEnt);
4256}
4257
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004258int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4259 if (!file || !outID)
4260 return 1;
4261
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004262 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004263 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4264 outID->data[0] = ID.getDevice();
4265 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004266 outID->data[2] = FEnt->getModificationTime();
4267 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004268}
4269
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004270int clang_File_isEqual(CXFile file1, CXFile file2) {
4271 if (file1 == file2)
4272 return true;
4273
4274 if (!file1 || !file2)
4275 return false;
4276
4277 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4278 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4279 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4280}
4281
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004282CXString clang_File_tryGetRealPathName(CXFile SFile) {
4283 if (!SFile)
4284 return cxstring::createNull();
4285
4286 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4287 return cxstring::createRef(FEnt->tryGetRealPathName());
4288}
4289
Guy Benyei11169dd2012-12-18 14:30:41 +00004290//===----------------------------------------------------------------------===//
4291// CXCursor Operations.
4292//===----------------------------------------------------------------------===//
4293
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004294static const Decl *getDeclFromExpr(const Stmt *E) {
4295 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 return getDeclFromExpr(CE->getSubExpr());
4297
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004298 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004300 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004302 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004304 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 if (PRE->isExplicitProperty())
4306 return PRE->getExplicitProperty();
4307 // It could be messaging both getter and setter as in:
4308 // ++myobj.myprop;
4309 // in which case prefer to associate the setter since it is less obvious
4310 // from inspecting the source that the setter is going to get called.
4311 if (PRE->isMessagingSetter())
4312 return PRE->getImplicitPropertySetter();
4313 return PRE->getImplicitPropertyGetter();
4314 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004315 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004317 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004318 if (Expr *Src = OVE->getSourceExpr())
4319 return getDeclFromExpr(Src);
4320
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004321 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004323 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 if (!CE->isElidable())
4325 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004326 if (const CXXInheritedCtorInitExpr *CE =
4327 dyn_cast<CXXInheritedCtorInitExpr>(E))
4328 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004329 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 return OME->getMethodDecl();
4331
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004332 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004334 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4336 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004337 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4339 isa<ParmVarDecl>(SizeOfPack->getPack()))
4340 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004341
4342 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004343}
4344
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004345static SourceLocation getLocationFromExpr(const Expr *E) {
4346 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 return getLocationFromExpr(CE->getSubExpr());
4348
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004349 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004350 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004351 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004353 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004355 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004357 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004359 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004361
4362 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004363}
4364
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004365extern "C" {
4366
Guy Benyei11169dd2012-12-18 14:30:41 +00004367unsigned clang_visitChildren(CXCursor parent,
4368 CXCursorVisitor visitor,
4369 CXClientData client_data) {
4370 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4371 /*VisitPreprocessorLast=*/false);
4372 return CursorVis.VisitChildren(parent);
4373}
4374
4375#ifndef __has_feature
4376#define __has_feature(x) 0
4377#endif
4378#if __has_feature(blocks)
4379typedef enum CXChildVisitResult
4380 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4381
4382static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4383 CXClientData client_data) {
4384 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4385 return block(cursor, parent);
4386}
4387#else
4388// If we are compiled with a compiler that doesn't have native blocks support,
4389// define and call the block manually, so the
4390typedef struct _CXChildVisitResult
4391{
4392 void *isa;
4393 int flags;
4394 int reserved;
4395 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4396 CXCursor);
4397} *CXCursorVisitorBlock;
4398
4399static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4400 CXClientData client_data) {
4401 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4402 return block->invoke(block, cursor, parent);
4403}
4404#endif
4405
4406
4407unsigned clang_visitChildrenWithBlock(CXCursor parent,
4408 CXCursorVisitorBlock block) {
4409 return clang_visitChildren(parent, visitWithBlock, block);
4410}
4411
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004412static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004414 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004415
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004416 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004418 if (const ObjCPropertyImplDecl *PropImpl =
4419 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004421 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004422
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004423 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004425 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004426
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004427 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 }
4429
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004430 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004431 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004432
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004433 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4435 // and returns different names. NamedDecl returns the class name and
4436 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004437 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004438
4439 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004440 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004441
4442 SmallString<1024> S;
4443 llvm::raw_svector_ostream os(S);
4444 ND->printName(os);
4445
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004446 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004447}
4448
4449CXString clang_getCursorSpelling(CXCursor C) {
4450 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004451 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004452
4453 if (clang_isReference(C.kind)) {
4454 switch (C.kind) {
4455 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004456 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004457 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 }
4459 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004460 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004461 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 }
4463 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004464 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004466 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 }
4468 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004469 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004470 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 }
4472 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004473 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 assert(Type && "Missing type decl");
4475
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004476 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 getAsString());
4478 }
4479 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004480 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 assert(Template && "Missing template decl");
4482
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004483 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 }
4485
4486 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004487 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 assert(NS && "Missing namespace decl");
4489
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004490 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 }
4492
4493 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004494 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 assert(Field && "Missing member decl");
4496
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004497 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 }
4499
4500 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004501 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 assert(Label && "Missing label");
4503
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004504 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 }
4506
4507 case CXCursor_OverloadedDeclRef: {
4508 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004509 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4510 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004511 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004512 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004514 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004515 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 OverloadedTemplateStorage *Ovl
4517 = Storage.get<OverloadedTemplateStorage*>();
4518 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004519 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004520 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 }
4522
4523 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004524 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 assert(Var && "Missing variable decl");
4526
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004527 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 }
4529
4530 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004531 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 }
4533 }
4534
4535 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004536 const Expr *E = getCursorExpr(C);
4537
4538 if (C.kind == CXCursor_ObjCStringLiteral ||
4539 C.kind == CXCursor_StringLiteral) {
4540 const StringLiteral *SLit;
4541 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4542 SLit = OSL->getString();
4543 } else {
4544 SLit = cast<StringLiteral>(E);
4545 }
4546 SmallString<256> Buf;
4547 llvm::raw_svector_ostream OS(Buf);
4548 SLit->outputString(OS);
4549 return cxstring::createDup(OS.str());
4550 }
4551
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004552 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 if (D)
4554 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004555 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 }
4557
4558 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004559 const Stmt *S = getCursorStmt(C);
4560 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004561 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004562
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004563 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 }
4565
4566 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004567 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 ->getNameStart());
4569
4570 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004571 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 ->getNameStart());
4573
4574 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004575 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004576
4577 if (clang_isDeclaration(C.kind))
4578 return getDeclSpelling(getCursorDecl(C));
4579
4580 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004581 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004582 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 }
4584
4585 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004586 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004587 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004588 }
4589
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004590 if (C.kind == CXCursor_PackedAttr) {
4591 return cxstring::createRef("packed");
4592 }
4593
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004594 if (C.kind == CXCursor_VisibilityAttr) {
4595 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4596 switch (AA->getVisibility()) {
4597 case VisibilityAttr::VisibilityType::Default:
4598 return cxstring::createRef("default");
4599 case VisibilityAttr::VisibilityType::Hidden:
4600 return cxstring::createRef("hidden");
4601 case VisibilityAttr::VisibilityType::Protected:
4602 return cxstring::createRef("protected");
4603 }
4604 llvm_unreachable("unknown visibility type");
4605 }
4606
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004607 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004608}
4609
4610CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4611 unsigned pieceIndex,
4612 unsigned options) {
4613 if (clang_Cursor_isNull(C))
4614 return clang_getNullRange();
4615
4616 ASTContext &Ctx = getCursorContext(C);
4617
4618 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004619 const Stmt *S = getCursorStmt(C);
4620 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 if (pieceIndex > 0)
4622 return clang_getNullRange();
4623 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4624 }
4625
4626 return clang_getNullRange();
4627 }
4628
4629 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004630 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4632 if (pieceIndex >= ME->getNumSelectorLocs())
4633 return clang_getNullRange();
4634 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4635 }
4636 }
4637
4638 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4639 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004640 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4642 if (pieceIndex >= MD->getNumSelectorLocs())
4643 return clang_getNullRange();
4644 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4645 }
4646 }
4647
4648 if (C.kind == CXCursor_ObjCCategoryDecl ||
4649 C.kind == CXCursor_ObjCCategoryImplDecl) {
4650 if (pieceIndex > 0)
4651 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004652 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4654 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004655 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4657 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4658 }
4659
4660 if (C.kind == CXCursor_ModuleImportDecl) {
4661 if (pieceIndex > 0)
4662 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004663 if (const ImportDecl *ImportD =
4664 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4666 if (!Locs.empty())
4667 return cxloc::translateSourceRange(Ctx,
4668 SourceRange(Locs.front(), Locs.back()));
4669 }
4670 return clang_getNullRange();
4671 }
4672
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004673 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004674 C.kind == CXCursor_ConversionFunction ||
4675 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004676 if (pieceIndex > 0)
4677 return clang_getNullRange();
4678 if (const FunctionDecl *FD =
4679 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4680 DeclarationNameInfo FunctionName = FD->getNameInfo();
4681 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4682 }
4683 return clang_getNullRange();
4684 }
4685
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 // FIXME: A CXCursor_InclusionDirective should give the location of the
4687 // filename, but we don't keep track of this.
4688
4689 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4690 // but we don't keep track of this.
4691
4692 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4693 // but we don't keep track of this.
4694
4695 // Default handling, give the location of the cursor.
4696
4697 if (pieceIndex > 0)
4698 return clang_getNullRange();
4699
4700 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4701 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4702 return cxloc::translateSourceRange(Ctx, Loc);
4703}
4704
Eli Bendersky44a206f2014-07-31 18:04:56 +00004705CXString clang_Cursor_getMangling(CXCursor C) {
4706 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4707 return cxstring::createEmpty();
4708
Eli Bendersky44a206f2014-07-31 18:04:56 +00004709 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004710 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004711 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4712 return cxstring::createEmpty();
4713
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004714 ASTContext &Ctx = D->getASTContext();
4715 index::CodegenNameGenerator CGNameGen(Ctx);
4716 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004717}
4718
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004719CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4720 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4721 return nullptr;
4722
4723 const Decl *D = getCursorDecl(C);
4724 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4725 return nullptr;
4726
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004727 ASTContext &Ctx = D->getASTContext();
4728 index::CodegenNameGenerator CGNameGen(Ctx);
4729 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004730 return cxstring::createSet(Manglings);
4731}
4732
Dave Lee1a532c92017-09-22 16:58:57 +00004733CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4734 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4735 return nullptr;
4736
4737 const Decl *D = getCursorDecl(C);
4738 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4739 return nullptr;
4740
4741 ASTContext &Ctx = D->getASTContext();
4742 index::CodegenNameGenerator CGNameGen(Ctx);
4743 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4744 return cxstring::createSet(Manglings);
4745}
4746
Jonathan Coe45ef5032018-01-16 10:19:56 +00004747CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4748 if (clang_Cursor_isNull(C))
4749 return 0;
4750 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4751}
4752
4753void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4754 if (Policy)
4755 delete static_cast<PrintingPolicy *>(Policy);
4756}
4757
4758unsigned
4759clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4760 enum CXPrintingPolicyProperty Property) {
4761 if (!Policy)
4762 return 0;
4763
4764 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4765 switch (Property) {
4766 case CXPrintingPolicy_Indentation:
4767 return P->Indentation;
4768 case CXPrintingPolicy_SuppressSpecifiers:
4769 return P->SuppressSpecifiers;
4770 case CXPrintingPolicy_SuppressTagKeyword:
4771 return P->SuppressTagKeyword;
4772 case CXPrintingPolicy_IncludeTagDefinition:
4773 return P->IncludeTagDefinition;
4774 case CXPrintingPolicy_SuppressScope:
4775 return P->SuppressScope;
4776 case CXPrintingPolicy_SuppressUnwrittenScope:
4777 return P->SuppressUnwrittenScope;
4778 case CXPrintingPolicy_SuppressInitializers:
4779 return P->SuppressInitializers;
4780 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4781 return P->ConstantArraySizeAsWritten;
4782 case CXPrintingPolicy_AnonymousTagLocations:
4783 return P->AnonymousTagLocations;
4784 case CXPrintingPolicy_SuppressStrongLifetime:
4785 return P->SuppressStrongLifetime;
4786 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4787 return P->SuppressLifetimeQualifiers;
4788 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4789 return P->SuppressTemplateArgsInCXXConstructors;
4790 case CXPrintingPolicy_Bool:
4791 return P->Bool;
4792 case CXPrintingPolicy_Restrict:
4793 return P->Restrict;
4794 case CXPrintingPolicy_Alignof:
4795 return P->Alignof;
4796 case CXPrintingPolicy_UnderscoreAlignof:
4797 return P->UnderscoreAlignof;
4798 case CXPrintingPolicy_UseVoidForZeroParams:
4799 return P->UseVoidForZeroParams;
4800 case CXPrintingPolicy_TerseOutput:
4801 return P->TerseOutput;
4802 case CXPrintingPolicy_PolishForDeclaration:
4803 return P->PolishForDeclaration;
4804 case CXPrintingPolicy_Half:
4805 return P->Half;
4806 case CXPrintingPolicy_MSWChar:
4807 return P->MSWChar;
4808 case CXPrintingPolicy_IncludeNewlines:
4809 return P->IncludeNewlines;
4810 case CXPrintingPolicy_MSVCFormatting:
4811 return P->MSVCFormatting;
4812 case CXPrintingPolicy_ConstantsAsWritten:
4813 return P->ConstantsAsWritten;
4814 case CXPrintingPolicy_SuppressImplicitBase:
4815 return P->SuppressImplicitBase;
4816 case CXPrintingPolicy_FullyQualifiedName:
4817 return P->FullyQualifiedName;
4818 }
4819
4820 assert(false && "Invalid CXPrintingPolicyProperty");
4821 return 0;
4822}
4823
4824void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4825 enum CXPrintingPolicyProperty Property,
4826 unsigned Value) {
4827 if (!Policy)
4828 return;
4829
4830 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4831 switch (Property) {
4832 case CXPrintingPolicy_Indentation:
4833 P->Indentation = Value;
4834 return;
4835 case CXPrintingPolicy_SuppressSpecifiers:
4836 P->SuppressSpecifiers = Value;
4837 return;
4838 case CXPrintingPolicy_SuppressTagKeyword:
4839 P->SuppressTagKeyword = Value;
4840 return;
4841 case CXPrintingPolicy_IncludeTagDefinition:
4842 P->IncludeTagDefinition = Value;
4843 return;
4844 case CXPrintingPolicy_SuppressScope:
4845 P->SuppressScope = Value;
4846 return;
4847 case CXPrintingPolicy_SuppressUnwrittenScope:
4848 P->SuppressUnwrittenScope = Value;
4849 return;
4850 case CXPrintingPolicy_SuppressInitializers:
4851 P->SuppressInitializers = Value;
4852 return;
4853 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4854 P->ConstantArraySizeAsWritten = Value;
4855 return;
4856 case CXPrintingPolicy_AnonymousTagLocations:
4857 P->AnonymousTagLocations = Value;
4858 return;
4859 case CXPrintingPolicy_SuppressStrongLifetime:
4860 P->SuppressStrongLifetime = Value;
4861 return;
4862 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4863 P->SuppressLifetimeQualifiers = Value;
4864 return;
4865 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4866 P->SuppressTemplateArgsInCXXConstructors = Value;
4867 return;
4868 case CXPrintingPolicy_Bool:
4869 P->Bool = Value;
4870 return;
4871 case CXPrintingPolicy_Restrict:
4872 P->Restrict = Value;
4873 return;
4874 case CXPrintingPolicy_Alignof:
4875 P->Alignof = Value;
4876 return;
4877 case CXPrintingPolicy_UnderscoreAlignof:
4878 P->UnderscoreAlignof = Value;
4879 return;
4880 case CXPrintingPolicy_UseVoidForZeroParams:
4881 P->UseVoidForZeroParams = Value;
4882 return;
4883 case CXPrintingPolicy_TerseOutput:
4884 P->TerseOutput = Value;
4885 return;
4886 case CXPrintingPolicy_PolishForDeclaration:
4887 P->PolishForDeclaration = Value;
4888 return;
4889 case CXPrintingPolicy_Half:
4890 P->Half = Value;
4891 return;
4892 case CXPrintingPolicy_MSWChar:
4893 P->MSWChar = Value;
4894 return;
4895 case CXPrintingPolicy_IncludeNewlines:
4896 P->IncludeNewlines = Value;
4897 return;
4898 case CXPrintingPolicy_MSVCFormatting:
4899 P->MSVCFormatting = Value;
4900 return;
4901 case CXPrintingPolicy_ConstantsAsWritten:
4902 P->ConstantsAsWritten = Value;
4903 return;
4904 case CXPrintingPolicy_SuppressImplicitBase:
4905 P->SuppressImplicitBase = Value;
4906 return;
4907 case CXPrintingPolicy_FullyQualifiedName:
4908 P->FullyQualifiedName = Value;
4909 return;
4910 }
4911
4912 assert(false && "Invalid CXPrintingPolicyProperty");
4913}
4914
4915CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4916 if (clang_Cursor_isNull(C))
4917 return cxstring::createEmpty();
4918
4919 if (clang_isDeclaration(C.kind)) {
4920 const Decl *D = getCursorDecl(C);
4921 if (!D)
4922 return cxstring::createEmpty();
4923
4924 SmallString<128> Str;
4925 llvm::raw_svector_ostream OS(Str);
4926 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4927 D->print(OS, UserPolicy ? *UserPolicy
4928 : getCursorContext(C).getPrintingPolicy());
4929
4930 return cxstring::createDup(OS.str());
4931 }
4932
4933 return cxstring::createEmpty();
4934}
4935
Guy Benyei11169dd2012-12-18 14:30:41 +00004936CXString clang_getCursorDisplayName(CXCursor C) {
4937 if (!clang_isDeclaration(C.kind))
4938 return clang_getCursorSpelling(C);
4939
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004940 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004941 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004942 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004943
4944 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004945 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004946 D = FunTmpl->getTemplatedDecl();
4947
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004948 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 SmallString<64> Str;
4950 llvm::raw_svector_ostream OS(Str);
4951 OS << *Function;
4952 if (Function->getPrimaryTemplate())
4953 OS << "<>";
4954 OS << "(";
4955 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4956 if (I)
4957 OS << ", ";
4958 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4959 }
4960
4961 if (Function->isVariadic()) {
4962 if (Function->getNumParams())
4963 OS << ", ";
4964 OS << "...";
4965 }
4966 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004967 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004968 }
4969
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004970 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004971 SmallString<64> Str;
4972 llvm::raw_svector_ostream OS(Str);
4973 OS << *ClassTemplate;
4974 OS << "<";
4975 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4976 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4977 if (I)
4978 OS << ", ";
4979
4980 NamedDecl *Param = Params->getParam(I);
4981 if (Param->getIdentifier()) {
4982 OS << Param->getIdentifier()->getName();
4983 continue;
4984 }
4985
4986 // There is no parameter name, which makes this tricky. Try to come up
4987 // with something useful that isn't too long.
4988 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4989 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4990 else if (NonTypeTemplateParmDecl *NTTP
4991 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4992 OS << NTTP->getType().getAsString(Policy);
4993 else
4994 OS << "template<...> class";
4995 }
4996
4997 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004998 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004999 }
5000
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005001 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005002 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5003 // If the type was explicitly written, use that.
5004 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005005 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005006
Benjamin Kramer9170e912013-02-22 15:46:01 +00005007 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005008 llvm::raw_svector_ostream OS(Str);
5009 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005010 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5011 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005012 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 }
5014
5015 return clang_getCursorSpelling(C);
5016}
5017
5018CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5019 switch (Kind) {
5020 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005021 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005023 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005025 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005027 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005029 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005031 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005033 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005035 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005037 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005039 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005041 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005043 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005045 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005047 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005049 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005051 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005053 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005055 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005057 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005059 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005061 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005063 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005065 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005067 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005069 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005071 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005073 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005075 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005077 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005079 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005081 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005083 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005084 case CXCursor_FixedPointLiteral:
5085 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005087 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005089 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005091 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005093 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005097 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005100 case CXCursor_OMPArraySectionExpr:
5101 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005152 case CXCursor_ObjCAvailabilityCheckExpr:
5153 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005154 case CXCursor_ObjCSelfExpr:
5155 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005244 case CXCursor_SEHLeaveStmt:
5245 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005257 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005265 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005274 case CXCursor_PackedAttr:
5275 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005276 case CXCursor_PureAttr:
5277 return cxstring::createRef("attribute(pure)");
5278 case CXCursor_ConstAttr:
5279 return cxstring::createRef("attribute(const)");
5280 case CXCursor_NoDuplicateAttr:
5281 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005282 case CXCursor_CUDAConstantAttr:
5283 return cxstring::createRef("attribute(constant)");
5284 case CXCursor_CUDADeviceAttr:
5285 return cxstring::createRef("attribute(device)");
5286 case CXCursor_CUDAGlobalAttr:
5287 return cxstring::createRef("attribute(global)");
5288 case CXCursor_CUDAHostAttr:
5289 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005290 case CXCursor_CUDASharedAttr:
5291 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005292 case CXCursor_VisibilityAttr:
5293 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005294 case CXCursor_DLLExport:
5295 return cxstring::createRef("attribute(dllexport)");
5296 case CXCursor_DLLImport:
5297 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005298 case CXCursor_NSReturnsRetained:
5299 return cxstring::createRef("attribute(ns_returns_retained)");
5300 case CXCursor_NSReturnsNotRetained:
5301 return cxstring::createRef("attribute(ns_returns_not_retained)");
5302 case CXCursor_NSReturnsAutoreleased:
5303 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5304 case CXCursor_NSConsumesSelf:
5305 return cxstring::createRef("attribute(ns_consumes_self)");
5306 case CXCursor_NSConsumed:
5307 return cxstring::createRef("attribute(ns_consumed)");
5308 case CXCursor_ObjCException:
5309 return cxstring::createRef("attribute(objc_exception)");
5310 case CXCursor_ObjCNSObject:
5311 return cxstring::createRef("attribute(NSObject)");
5312 case CXCursor_ObjCIndependentClass:
5313 return cxstring::createRef("attribute(objc_independent_class)");
5314 case CXCursor_ObjCPreciseLifetime:
5315 return cxstring::createRef("attribute(objc_precise_lifetime)");
5316 case CXCursor_ObjCReturnsInnerPointer:
5317 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5318 case CXCursor_ObjCRequiresSuper:
5319 return cxstring::createRef("attribute(objc_requires_super)");
5320 case CXCursor_ObjCRootClass:
5321 return cxstring::createRef("attribute(objc_root_class)");
5322 case CXCursor_ObjCSubclassingRestricted:
5323 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5324 case CXCursor_ObjCExplicitProtocolImpl:
5325 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5326 case CXCursor_ObjCDesignatedInitializer:
5327 return cxstring::createRef("attribute(objc_designated_initializer)");
5328 case CXCursor_ObjCRuntimeVisible:
5329 return cxstring::createRef("attribute(objc_runtime_visible)");
5330 case CXCursor_ObjCBoxable:
5331 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005332 case CXCursor_FlagEnum:
5333 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005335 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005337 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005338 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005339 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005340 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005341 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005343 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005345 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005347 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005349 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005350 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005351 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005352 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005353 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005355 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005357 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005359 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005360 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005361 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005362 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005363 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005365 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005367 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005369 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005370 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005371 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005372 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005373 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005374 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005375 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005376 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005377 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005378 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005379 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005380 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005381 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005382 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005383 return cxstring::createRef("OMPParallelDirective");
5384 case CXCursor_OMPSimdDirective:
5385 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005386 case CXCursor_OMPForDirective:
5387 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005388 case CXCursor_OMPForSimdDirective:
5389 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005390 case CXCursor_OMPSectionsDirective:
5391 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005392 case CXCursor_OMPSectionDirective:
5393 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005394 case CXCursor_OMPSingleDirective:
5395 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005396 case CXCursor_OMPMasterDirective:
5397 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005398 case CXCursor_OMPCriticalDirective:
5399 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005400 case CXCursor_OMPParallelForDirective:
5401 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005402 case CXCursor_OMPParallelForSimdDirective:
5403 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005404 case CXCursor_OMPParallelSectionsDirective:
5405 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005406 case CXCursor_OMPTaskDirective:
5407 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005408 case CXCursor_OMPTaskyieldDirective:
5409 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005410 case CXCursor_OMPBarrierDirective:
5411 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005412 case CXCursor_OMPTaskwaitDirective:
5413 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005414 case CXCursor_OMPTaskgroupDirective:
5415 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005416 case CXCursor_OMPFlushDirective:
5417 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005418 case CXCursor_OMPOrderedDirective:
5419 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005420 case CXCursor_OMPAtomicDirective:
5421 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005422 case CXCursor_OMPTargetDirective:
5423 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005424 case CXCursor_OMPTargetDataDirective:
5425 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005426 case CXCursor_OMPTargetEnterDataDirective:
5427 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005428 case CXCursor_OMPTargetExitDataDirective:
5429 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005430 case CXCursor_OMPTargetParallelDirective:
5431 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005432 case CXCursor_OMPTargetParallelForDirective:
5433 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005434 case CXCursor_OMPTargetUpdateDirective:
5435 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005436 case CXCursor_OMPTeamsDirective:
5437 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005438 case CXCursor_OMPCancellationPointDirective:
5439 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005440 case CXCursor_OMPCancelDirective:
5441 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005442 case CXCursor_OMPTaskLoopDirective:
5443 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005444 case CXCursor_OMPTaskLoopSimdDirective:
5445 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005446 case CXCursor_OMPDistributeDirective:
5447 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005448 case CXCursor_OMPDistributeParallelForDirective:
5449 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005450 case CXCursor_OMPDistributeParallelForSimdDirective:
5451 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005452 case CXCursor_OMPDistributeSimdDirective:
5453 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005454 case CXCursor_OMPTargetParallelForSimdDirective:
5455 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005456 case CXCursor_OMPTargetSimdDirective:
5457 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005458 case CXCursor_OMPTeamsDistributeDirective:
5459 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005460 case CXCursor_OMPTeamsDistributeSimdDirective:
5461 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005462 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5463 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005464 case CXCursor_OMPTeamsDistributeParallelForDirective:
5465 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005466 case CXCursor_OMPTargetTeamsDirective:
5467 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005468 case CXCursor_OMPTargetTeamsDistributeDirective:
5469 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005470 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5471 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005472 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5473 return cxstring::createRef(
5474 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005475 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5476 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005477 case CXCursor_OverloadCandidate:
5478 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005479 case CXCursor_TypeAliasTemplateDecl:
5480 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005481 case CXCursor_StaticAssert:
5482 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005483 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005484 return cxstring::createRef("FriendDecl");
5485 case CXCursor_ConvergentAttr:
5486 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005487 case CXCursor_WarnUnusedAttr:
5488 return cxstring::createRef("attribute(warn_unused)");
5489 case CXCursor_WarnUnusedResultAttr:
5490 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005491 case CXCursor_AlignedAttr:
5492 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005493 }
5494
5495 llvm_unreachable("Unhandled CXCursorKind");
5496}
5497
5498struct GetCursorData {
5499 SourceLocation TokenBeginLoc;
5500 bool PointsAtMacroArgExpansion;
5501 bool VisitedObjCPropertyImplDecl;
5502 SourceLocation VisitedDeclaratorDeclStartLoc;
5503 CXCursor &BestCursor;
5504
5505 GetCursorData(SourceManager &SM,
5506 SourceLocation tokenBegin, CXCursor &outputCursor)
5507 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5508 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5509 VisitedObjCPropertyImplDecl = false;
5510 }
5511};
5512
5513static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5514 CXCursor parent,
5515 CXClientData client_data) {
5516 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5517 CXCursor *BestCursor = &Data->BestCursor;
5518
5519 // If we point inside a macro argument we should provide info of what the
5520 // token is so use the actual cursor, don't replace it with a macro expansion
5521 // cursor.
5522 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5523 return CXChildVisit_Recurse;
5524
5525 if (clang_isDeclaration(cursor.kind)) {
5526 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005527 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005528 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5529 if (MD->isImplicit())
5530 return CXChildVisit_Break;
5531
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005532 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005533 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5534 // Check that when we have multiple @class references in the same line,
5535 // that later ones do not override the previous ones.
5536 // If we have:
5537 // @class Foo, Bar;
5538 // source ranges for both start at '@', so 'Bar' will end up overriding
5539 // 'Foo' even though the cursor location was at 'Foo'.
5540 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5541 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005542 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005543 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5544 if (PrevID != ID &&
5545 !PrevID->isThisDeclarationADefinition() &&
5546 !ID->isThisDeclarationADefinition())
5547 return CXChildVisit_Break;
5548 }
5549
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005550 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005551 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5552 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5553 // Check that when we have multiple declarators in the same line,
5554 // that later ones do not override the previous ones.
5555 // If we have:
5556 // int Foo, Bar;
5557 // source ranges for both start at 'int', so 'Bar' will end up overriding
5558 // 'Foo' even though the cursor location was at 'Foo'.
5559 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5560 return CXChildVisit_Break;
5561 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5562
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005563 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005564 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5565 (void)PropImp;
5566 // Check that when we have multiple @synthesize in the same line,
5567 // that later ones do not override the previous ones.
5568 // If we have:
5569 // @synthesize Foo, Bar;
5570 // source ranges for both start at '@', so 'Bar' will end up overriding
5571 // 'Foo' even though the cursor location was at 'Foo'.
5572 if (Data->VisitedObjCPropertyImplDecl)
5573 return CXChildVisit_Break;
5574 Data->VisitedObjCPropertyImplDecl = true;
5575 }
5576 }
5577
5578 if (clang_isExpression(cursor.kind) &&
5579 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005580 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005581 // Avoid having the cursor of an expression replace the declaration cursor
5582 // when the expression source range overlaps the declaration range.
5583 // This can happen for C++ constructor expressions whose range generally
5584 // include the variable declaration, e.g.:
5585 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5586 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5587 D->getLocation() == Data->TokenBeginLoc)
5588 return CXChildVisit_Break;
5589 }
5590 }
5591
5592 // If our current best cursor is the construction of a temporary object,
5593 // don't replace that cursor with a type reference, because we want
5594 // clang_getCursor() to point at the constructor.
5595 if (clang_isExpression(BestCursor->kind) &&
5596 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5597 cursor.kind == CXCursor_TypeRef) {
5598 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5599 // as having the actual point on the type reference.
5600 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5601 return CXChildVisit_Recurse;
5602 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005603
5604 // If we already have an Objective-C superclass reference, don't
5605 // update it further.
5606 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5607 return CXChildVisit_Break;
5608
Guy Benyei11169dd2012-12-18 14:30:41 +00005609 *BestCursor = cursor;
5610 return CXChildVisit_Recurse;
5611}
5612
5613CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005614 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005615 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005617 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005618
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005619 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5621
5622 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5623 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5624
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005625 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 CXFile SearchFile;
5627 unsigned SearchLine, SearchColumn;
5628 CXFile ResultFile;
5629 unsigned ResultLine, ResultColumn;
5630 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5631 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5632 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005633
5634 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5635 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005636 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005637 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005638 SearchFileName = clang_getFileName(SearchFile);
5639 ResultFileName = clang_getFileName(ResultFile);
5640 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5641 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005642 *Log << llvm::format("(%s:%d:%d) = %s",
5643 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5644 clang_getCString(KindSpelling))
5645 << llvm::format("(%s:%d:%d):%s%s",
5646 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5647 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005648 clang_disposeString(SearchFileName);
5649 clang_disposeString(ResultFileName);
5650 clang_disposeString(KindSpelling);
5651 clang_disposeString(USR);
5652
5653 CXCursor Definition = clang_getCursorDefinition(Result);
5654 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5655 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5656 CXString DefinitionKindSpelling
5657 = clang_getCursorKindSpelling(Definition.kind);
5658 CXFile DefinitionFile;
5659 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005660 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005661 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005663 *Log << llvm::format(" -> %s(%s:%d:%d)",
5664 clang_getCString(DefinitionKindSpelling),
5665 clang_getCString(DefinitionFileName),
5666 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005667 clang_disposeString(DefinitionFileName);
5668 clang_disposeString(DefinitionKindSpelling);
5669 }
5670 }
5671
5672 return Result;
5673}
5674
5675CXCursor clang_getNullCursor(void) {
5676 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5677}
5678
5679unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005680 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5681 // can't set consistently. For example, when visiting a DeclStmt we will set
5682 // it but we don't set it on the result of clang_getCursorDefinition for
5683 // a reference of the same declaration.
5684 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5685 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5686 // to provide that kind of info.
5687 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005688 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005689 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005690 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005691
Guy Benyei11169dd2012-12-18 14:30:41 +00005692 return X == Y;
5693}
5694
5695unsigned clang_hashCursor(CXCursor C) {
5696 unsigned Index = 0;
5697 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5698 Index = 1;
5699
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005700 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005701 std::make_pair(C.kind, C.data[Index]));
5702}
5703
5704unsigned clang_isInvalid(enum CXCursorKind K) {
5705 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5706}
5707
5708unsigned clang_isDeclaration(enum CXCursorKind K) {
5709 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005710 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5711}
5712
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005713unsigned clang_isInvalidDeclaration(CXCursor C) {
5714 if (clang_isDeclaration(C.kind)) {
5715 if (const Decl *D = getCursorDecl(C))
5716 return D->isInvalidDecl();
5717 }
5718
5719 return 0;
5720}
5721
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005722unsigned clang_isReference(enum CXCursorKind K) {
5723 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5724}
Guy Benyei11169dd2012-12-18 14:30:41 +00005725
5726unsigned clang_isExpression(enum CXCursorKind K) {
5727 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5728}
5729
5730unsigned clang_isStatement(enum CXCursorKind K) {
5731 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5732}
5733
5734unsigned clang_isAttribute(enum CXCursorKind K) {
5735 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5736}
5737
5738unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5739 return K == CXCursor_TranslationUnit;
5740}
5741
5742unsigned clang_isPreprocessing(enum CXCursorKind K) {
5743 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5744}
5745
5746unsigned clang_isUnexposed(enum CXCursorKind K) {
5747 switch (K) {
5748 case CXCursor_UnexposedDecl:
5749 case CXCursor_UnexposedExpr:
5750 case CXCursor_UnexposedStmt:
5751 case CXCursor_UnexposedAttr:
5752 return true;
5753 default:
5754 return false;
5755 }
5756}
5757
5758CXCursorKind clang_getCursorKind(CXCursor C) {
5759 return C.kind;
5760}
5761
5762CXSourceLocation clang_getCursorLocation(CXCursor C) {
5763 if (clang_isReference(C.kind)) {
5764 switch (C.kind) {
5765 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005766 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005767 = getCursorObjCSuperClassRef(C);
5768 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5769 }
5770
5771 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005772 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005773 = getCursorObjCProtocolRef(C);
5774 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5775 }
5776
5777 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005778 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005779 = getCursorObjCClassRef(C);
5780 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5781 }
5782
5783 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005784 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005785 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5786 }
5787
5788 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005789 std::pair<const TemplateDecl *, SourceLocation> P =
5790 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005791 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5792 }
5793
5794 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005795 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005796 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5797 }
5798
5799 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005800 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005801 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5802 }
5803
5804 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005805 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005806 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5807 }
5808
5809 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005810 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005811 if (!BaseSpec)
5812 return clang_getNullLocation();
5813
5814 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5815 return cxloc::translateSourceLocation(getCursorContext(C),
5816 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005817
Guy Benyei11169dd2012-12-18 14:30:41 +00005818 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005819 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005820 }
5821
5822 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005823 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005824 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5825 }
5826
5827 case CXCursor_OverloadedDeclRef:
5828 return cxloc::translateSourceLocation(getCursorContext(C),
5829 getCursorOverloadedDeclRef(C).second);
5830
5831 default:
5832 // FIXME: Need a way to enumerate all non-reference cases.
5833 llvm_unreachable("Missed a reference kind");
5834 }
5835 }
5836
5837 if (clang_isExpression(C.kind))
5838 return cxloc::translateSourceLocation(getCursorContext(C),
5839 getLocationFromExpr(getCursorExpr(C)));
5840
5841 if (clang_isStatement(C.kind))
5842 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005843 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005844
5845 if (C.kind == CXCursor_PreprocessingDirective) {
5846 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5847 return cxloc::translateSourceLocation(getCursorContext(C), L);
5848 }
5849
5850 if (C.kind == CXCursor_MacroExpansion) {
5851 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005852 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005853 return cxloc::translateSourceLocation(getCursorContext(C), L);
5854 }
5855
5856 if (C.kind == CXCursor_MacroDefinition) {
5857 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5858 return cxloc::translateSourceLocation(getCursorContext(C), L);
5859 }
5860
5861 if (C.kind == CXCursor_InclusionDirective) {
5862 SourceLocation L
5863 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5864 return cxloc::translateSourceLocation(getCursorContext(C), L);
5865 }
5866
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005867 if (clang_isAttribute(C.kind)) {
5868 SourceLocation L
5869 = cxcursor::getCursorAttr(C)->getLocation();
5870 return cxloc::translateSourceLocation(getCursorContext(C), L);
5871 }
5872
Guy Benyei11169dd2012-12-18 14:30:41 +00005873 if (!clang_isDeclaration(C.kind))
5874 return clang_getNullLocation();
5875
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005876 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005877 if (!D)
5878 return clang_getNullLocation();
5879
5880 SourceLocation Loc = D->getLocation();
5881 // FIXME: Multiple variables declared in a single declaration
5882 // currently lack the information needed to correctly determine their
5883 // ranges when accounting for the type-specifier. We use context
5884 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5885 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005886 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005887 if (!cxcursor::isFirstInDeclGroup(C))
5888 Loc = VD->getLocation();
5889 }
5890
5891 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005892 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005893 Loc = MD->getSelectorStartLoc();
5894
5895 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5896}
5897
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005898} // end extern "C"
5899
Guy Benyei11169dd2012-12-18 14:30:41 +00005900CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5901 assert(TU);
5902
5903 // Guard against an invalid SourceLocation, or we may assert in one
5904 // of the following calls.
5905 if (SLoc.isInvalid())
5906 return clang_getNullCursor();
5907
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005908 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005909
5910 // Translate the given source location to make it point at the beginning of
5911 // the token under the cursor.
5912 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5913 CXXUnit->getASTContext().getLangOpts());
5914
5915 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5916 if (SLoc.isValid()) {
5917 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5918 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5919 /*VisitPreprocessorLast=*/true,
5920 /*VisitIncludedEntities=*/false,
5921 SourceLocation(SLoc));
5922 CursorVis.visitFileRegion();
5923 }
5924
5925 return Result;
5926}
5927
5928static SourceRange getRawCursorExtent(CXCursor C) {
5929 if (clang_isReference(C.kind)) {
5930 switch (C.kind) {
5931 case CXCursor_ObjCSuperClassRef:
5932 return getCursorObjCSuperClassRef(C).second;
5933
5934 case CXCursor_ObjCProtocolRef:
5935 return getCursorObjCProtocolRef(C).second;
5936
5937 case CXCursor_ObjCClassRef:
5938 return getCursorObjCClassRef(C).second;
5939
5940 case CXCursor_TypeRef:
5941 return getCursorTypeRef(C).second;
5942
5943 case CXCursor_TemplateRef:
5944 return getCursorTemplateRef(C).second;
5945
5946 case CXCursor_NamespaceRef:
5947 return getCursorNamespaceRef(C).second;
5948
5949 case CXCursor_MemberRef:
5950 return getCursorMemberRef(C).second;
5951
5952 case CXCursor_CXXBaseSpecifier:
5953 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5954
5955 case CXCursor_LabelRef:
5956 return getCursorLabelRef(C).second;
5957
5958 case CXCursor_OverloadedDeclRef:
5959 return getCursorOverloadedDeclRef(C).second;
5960
5961 case CXCursor_VariableRef:
5962 return getCursorVariableRef(C).second;
5963
5964 default:
5965 // FIXME: Need a way to enumerate all non-reference cases.
5966 llvm_unreachable("Missed a reference kind");
5967 }
5968 }
5969
5970 if (clang_isExpression(C.kind))
5971 return getCursorExpr(C)->getSourceRange();
5972
5973 if (clang_isStatement(C.kind))
5974 return getCursorStmt(C)->getSourceRange();
5975
5976 if (clang_isAttribute(C.kind))
5977 return getCursorAttr(C)->getRange();
5978
5979 if (C.kind == CXCursor_PreprocessingDirective)
5980 return cxcursor::getCursorPreprocessingDirective(C);
5981
5982 if (C.kind == CXCursor_MacroExpansion) {
5983 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005984 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005985 return TU->mapRangeFromPreamble(Range);
5986 }
5987
5988 if (C.kind == CXCursor_MacroDefinition) {
5989 ASTUnit *TU = getCursorASTUnit(C);
5990 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5991 return TU->mapRangeFromPreamble(Range);
5992 }
5993
5994 if (C.kind == CXCursor_InclusionDirective) {
5995 ASTUnit *TU = getCursorASTUnit(C);
5996 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5997 return TU->mapRangeFromPreamble(Range);
5998 }
5999
6000 if (C.kind == CXCursor_TranslationUnit) {
6001 ASTUnit *TU = getCursorASTUnit(C);
6002 FileID MainID = TU->getSourceManager().getMainFileID();
6003 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6004 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6005 return SourceRange(Start, End);
6006 }
6007
6008 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006009 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006010 if (!D)
6011 return SourceRange();
6012
6013 SourceRange R = D->getSourceRange();
6014 // FIXME: Multiple variables declared in a single declaration
6015 // currently lack the information needed to correctly determine their
6016 // ranges when accounting for the type-specifier. We use context
6017 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6018 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006019 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006020 if (!cxcursor::isFirstInDeclGroup(C))
6021 R.setBegin(VD->getLocation());
6022 }
6023 return R;
6024 }
6025 return SourceRange();
6026}
6027
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006028/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006029/// the decl-specifier-seq for declarations.
6030static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6031 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006032 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006033 if (!D)
6034 return SourceRange();
6035
6036 SourceRange R = D->getSourceRange();
6037
6038 // Adjust the start of the location for declarations preceded by
6039 // declaration specifiers.
6040 SourceLocation StartLoc;
6041 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6042 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006043 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006044 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006045 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006046 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 }
6048
6049 if (StartLoc.isValid() && R.getBegin().isValid() &&
6050 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6051 R.setBegin(StartLoc);
6052
6053 // FIXME: Multiple variables declared in a single declaration
6054 // currently lack the information needed to correctly determine their
6055 // ranges when accounting for the type-specifier. We use context
6056 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6057 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006058 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 if (!cxcursor::isFirstInDeclGroup(C))
6060 R.setBegin(VD->getLocation());
6061 }
6062
6063 return R;
6064 }
6065
6066 return getRawCursorExtent(C);
6067}
6068
Guy Benyei11169dd2012-12-18 14:30:41 +00006069CXSourceRange clang_getCursorExtent(CXCursor C) {
6070 SourceRange R = getRawCursorExtent(C);
6071 if (R.isInvalid())
6072 return clang_getNullRange();
6073
6074 return cxloc::translateSourceRange(getCursorContext(C), R);
6075}
6076
6077CXCursor clang_getCursorReferenced(CXCursor C) {
6078 if (clang_isInvalid(C.kind))
6079 return clang_getNullCursor();
6080
6081 CXTranslationUnit tu = getCursorTU(C);
6082 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006083 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006084 if (!D)
6085 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006086 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006088 if (const ObjCPropertyImplDecl *PropImpl =
6089 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006090 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6091 return MakeCXCursor(Property, tu);
6092
6093 return C;
6094 }
6095
6096 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006097 const Expr *E = getCursorExpr(C);
6098 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006099 if (D) {
6100 CXCursor declCursor = MakeCXCursor(D, tu);
6101 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6102 declCursor);
6103 return declCursor;
6104 }
6105
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006106 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006107 return MakeCursorOverloadedDeclRef(Ovl, tu);
6108
6109 return clang_getNullCursor();
6110 }
6111
6112 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006113 const Stmt *S = getCursorStmt(C);
6114 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006115 if (LabelDecl *label = Goto->getLabel())
6116 if (LabelStmt *labelS = label->getStmt())
6117 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6118
6119 return clang_getNullCursor();
6120 }
Richard Smith66a81862015-05-04 02:25:31 +00006121
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006123 if (const MacroDefinitionRecord *Def =
6124 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006125 return MakeMacroDefinitionCursor(Def, tu);
6126 }
6127
6128 if (!clang_isReference(C.kind))
6129 return clang_getNullCursor();
6130
6131 switch (C.kind) {
6132 case CXCursor_ObjCSuperClassRef:
6133 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6134
6135 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006136 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6137 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006138 return MakeCXCursor(Def, tu);
6139
6140 return MakeCXCursor(Prot, tu);
6141 }
6142
6143 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006144 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6145 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006146 return MakeCXCursor(Def, tu);
6147
6148 return MakeCXCursor(Class, tu);
6149 }
6150
6151 case CXCursor_TypeRef:
6152 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6153
6154 case CXCursor_TemplateRef:
6155 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6156
6157 case CXCursor_NamespaceRef:
6158 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6159
6160 case CXCursor_MemberRef:
6161 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6162
6163 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006164 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6166 tu ));
6167 }
6168
6169 case CXCursor_LabelRef:
6170 // FIXME: We end up faking the "parent" declaration here because we
6171 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006172 return MakeCXCursor(getCursorLabelRef(C).first,
6173 cxtu::getASTUnit(tu)->getASTContext()
6174 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 tu);
6176
6177 case CXCursor_OverloadedDeclRef:
6178 return C;
6179
6180 case CXCursor_VariableRef:
6181 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6182
6183 default:
6184 // We would prefer to enumerate all non-reference cursor kinds here.
6185 llvm_unreachable("Unhandled reference cursor kind");
6186 }
6187}
6188
6189CXCursor clang_getCursorDefinition(CXCursor C) {
6190 if (clang_isInvalid(C.kind))
6191 return clang_getNullCursor();
6192
6193 CXTranslationUnit TU = getCursorTU(C);
6194
6195 bool WasReference = false;
6196 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6197 C = clang_getCursorReferenced(C);
6198 WasReference = true;
6199 }
6200
6201 if (C.kind == CXCursor_MacroExpansion)
6202 return clang_getCursorReferenced(C);
6203
6204 if (!clang_isDeclaration(C.kind))
6205 return clang_getNullCursor();
6206
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006207 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006208 if (!D)
6209 return clang_getNullCursor();
6210
6211 switch (D->getKind()) {
6212 // Declaration kinds that don't really separate the notions of
6213 // declaration and definition.
6214 case Decl::Namespace:
6215 case Decl::Typedef:
6216 case Decl::TypeAlias:
6217 case Decl::TypeAliasTemplate:
6218 case Decl::TemplateTypeParm:
6219 case Decl::EnumConstant:
6220 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006221 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006222 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006223 case Decl::IndirectField:
6224 case Decl::ObjCIvar:
6225 case Decl::ObjCAtDefsField:
6226 case Decl::ImplicitParam:
6227 case Decl::ParmVar:
6228 case Decl::NonTypeTemplateParm:
6229 case Decl::TemplateTemplateParm:
6230 case Decl::ObjCCategoryImpl:
6231 case Decl::ObjCImplementation:
6232 case Decl::AccessSpec:
6233 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006234 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 case Decl::ObjCPropertyImpl:
6236 case Decl::FileScopeAsm:
6237 case Decl::StaticAssert:
6238 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006239 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006240 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006241 case Decl::Label: // FIXME: Is this right??
6242 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006243 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006244 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006245 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006246 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006247 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006248 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006249 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006250 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006251 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006252 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006253 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006254 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006255 return C;
6256
6257 // Declaration kinds that don't make any sense here, but are
6258 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006259 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006260 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006261 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006262 break;
6263
6264 // Declaration kinds for which the definition is not resolvable.
6265 case Decl::UnresolvedUsingTypename:
6266 case Decl::UnresolvedUsingValue:
6267 break;
6268
6269 case Decl::UsingDirective:
6270 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6271 TU);
6272
6273 case Decl::NamespaceAlias:
6274 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6275
6276 case Decl::Enum:
6277 case Decl::Record:
6278 case Decl::CXXRecord:
6279 case Decl::ClassTemplateSpecialization:
6280 case Decl::ClassTemplatePartialSpecialization:
6281 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6282 return MakeCXCursor(Def, TU);
6283 return clang_getNullCursor();
6284
6285 case Decl::Function:
6286 case Decl::CXXMethod:
6287 case Decl::CXXConstructor:
6288 case Decl::CXXDestructor:
6289 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006290 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006291 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006292 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006293 return clang_getNullCursor();
6294 }
6295
Larisse Voufo39a1e502013-08-06 01:03:05 +00006296 case Decl::Var:
6297 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006298 case Decl::VarTemplatePartialSpecialization:
6299 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006300 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006301 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006302 return MakeCXCursor(Def, TU);
6303 return clang_getNullCursor();
6304 }
6305
6306 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006307 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006308 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6309 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6310 return clang_getNullCursor();
6311 }
6312
6313 case Decl::ClassTemplate: {
6314 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6315 ->getDefinition())
6316 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6317 TU);
6318 return clang_getNullCursor();
6319 }
6320
Larisse Voufo39a1e502013-08-06 01:03:05 +00006321 case Decl::VarTemplate: {
6322 if (VarDecl *Def =
6323 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6324 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6325 return clang_getNullCursor();
6326 }
6327
Guy Benyei11169dd2012-12-18 14:30:41 +00006328 case Decl::Using:
6329 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6330 D->getLocation(), TU);
6331
6332 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006333 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006334 return clang_getCursorDefinition(
6335 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6336 TU));
6337
6338 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006339 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 if (Method->isThisDeclarationADefinition())
6341 return C;
6342
6343 // Dig out the method definition in the associated
6344 // @implementation, if we have it.
6345 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006346 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6348 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6349 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6350 Method->isInstanceMethod()))
6351 if (Def->isThisDeclarationADefinition())
6352 return MakeCXCursor(Def, TU);
6353
6354 return clang_getNullCursor();
6355 }
6356
6357 case Decl::ObjCCategory:
6358 if (ObjCCategoryImplDecl *Impl
6359 = cast<ObjCCategoryDecl>(D)->getImplementation())
6360 return MakeCXCursor(Impl, TU);
6361 return clang_getNullCursor();
6362
6363 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006364 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006365 return MakeCXCursor(Def, TU);
6366 return clang_getNullCursor();
6367
6368 case Decl::ObjCInterface: {
6369 // There are two notions of a "definition" for an Objective-C
6370 // class: the interface and its implementation. When we resolved a
6371 // reference to an Objective-C class, produce the @interface as
6372 // the definition; when we were provided with the interface,
6373 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006374 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006376 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 return MakeCXCursor(Def, TU);
6378 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6379 return MakeCXCursor(Impl, TU);
6380 return clang_getNullCursor();
6381 }
6382
6383 case Decl::ObjCProperty:
6384 // FIXME: We don't really know where to find the
6385 // ObjCPropertyImplDecls that implement this property.
6386 return clang_getNullCursor();
6387
6388 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006389 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006391 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006392 return MakeCXCursor(Def, TU);
6393
6394 return clang_getNullCursor();
6395
6396 case Decl::Friend:
6397 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6398 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6399 return clang_getNullCursor();
6400
6401 case Decl::FriendTemplate:
6402 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6403 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6404 return clang_getNullCursor();
6405 }
6406
6407 return clang_getNullCursor();
6408}
6409
6410unsigned clang_isCursorDefinition(CXCursor C) {
6411 if (!clang_isDeclaration(C.kind))
6412 return 0;
6413
6414 return clang_getCursorDefinition(C) == C;
6415}
6416
6417CXCursor clang_getCanonicalCursor(CXCursor C) {
6418 if (!clang_isDeclaration(C.kind))
6419 return C;
6420
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006421 if (const Decl *D = getCursorDecl(C)) {
6422 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006423 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6424 return MakeCXCursor(CatD, getCursorTU(C));
6425
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006426 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6427 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006428 return MakeCXCursor(IFD, getCursorTU(C));
6429
6430 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6431 }
6432
6433 return C;
6434}
6435
6436int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6437 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6438}
6439
6440unsigned clang_getNumOverloadedDecls(CXCursor C) {
6441 if (C.kind != CXCursor_OverloadedDeclRef)
6442 return 0;
6443
6444 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006445 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006446 return E->getNumDecls();
6447
6448 if (OverloadedTemplateStorage *S
6449 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6450 return S->size();
6451
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006452 const Decl *D = Storage.get<const Decl *>();
6453 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006454 return Using->shadow_size();
6455
6456 return 0;
6457}
6458
6459CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6460 if (cursor.kind != CXCursor_OverloadedDeclRef)
6461 return clang_getNullCursor();
6462
6463 if (index >= clang_getNumOverloadedDecls(cursor))
6464 return clang_getNullCursor();
6465
6466 CXTranslationUnit TU = getCursorTU(cursor);
6467 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006468 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006469 return MakeCXCursor(E->decls_begin()[index], TU);
6470
6471 if (OverloadedTemplateStorage *S
6472 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6473 return MakeCXCursor(S->begin()[index], TU);
6474
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006475 const Decl *D = Storage.get<const Decl *>();
6476 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006477 // FIXME: This is, unfortunately, linear time.
6478 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6479 std::advance(Pos, index);
6480 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6481 }
6482
6483 return clang_getNullCursor();
6484}
6485
6486void clang_getDefinitionSpellingAndExtent(CXCursor C,
6487 const char **startBuf,
6488 const char **endBuf,
6489 unsigned *startLine,
6490 unsigned *startColumn,
6491 unsigned *endLine,
6492 unsigned *endColumn) {
6493 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006494 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006495 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6496
6497 SourceManager &SM = FD->getASTContext().getSourceManager();
6498 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6499 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6500 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6501 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6502 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6503 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6504}
6505
6506
6507CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6508 unsigned PieceIndex) {
6509 RefNamePieces Pieces;
6510
6511 switch (C.kind) {
6512 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006513 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006514 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6515 E->getQualifierLoc().getSourceRange());
6516 break;
6517
6518 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006519 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6520 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6521 Pieces =
6522 buildPieces(NameFlags, false, E->getNameInfo(),
6523 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6524 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006525 break;
6526
6527 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006528 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006529 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006530 const Expr *Callee = OCE->getCallee();
6531 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 Callee = ICE->getSubExpr();
6533
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006534 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6536 DRE->getQualifierLoc().getSourceRange());
6537 }
6538 break;
6539
6540 default:
6541 break;
6542 }
6543
6544 if (Pieces.empty()) {
6545 if (PieceIndex == 0)
6546 return clang_getCursorExtent(C);
6547 } else if (PieceIndex < Pieces.size()) {
6548 SourceRange R = Pieces[PieceIndex];
6549 if (R.isValid())
6550 return cxloc::translateSourceRange(getCursorContext(C), R);
6551 }
6552
6553 return clang_getNullRange();
6554}
6555
6556void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006557 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6558 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006559}
6560
6561void clang_executeOnThread(void (*fn)(void*), void *user_data,
6562 unsigned stack_size) {
6563 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6564}
6565
Guy Benyei11169dd2012-12-18 14:30:41 +00006566//===----------------------------------------------------------------------===//
6567// Token-based Operations.
6568//===----------------------------------------------------------------------===//
6569
6570/* CXToken layout:
6571 * int_data[0]: a CXTokenKind
6572 * int_data[1]: starting token location
6573 * int_data[2]: token length
6574 * int_data[3]: reserved
6575 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6576 * otherwise unused.
6577 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006578CXTokenKind clang_getTokenKind(CXToken CXTok) {
6579 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6580}
6581
6582CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6583 switch (clang_getTokenKind(CXTok)) {
6584 case CXToken_Identifier:
6585 case CXToken_Keyword:
6586 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006587 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006588 ->getNameStart());
6589
6590 case CXToken_Literal: {
6591 // We have stashed the starting pointer in the ptr_data field. Use it.
6592 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006593 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 }
6595
6596 case CXToken_Punctuation:
6597 case CXToken_Comment:
6598 break;
6599 }
6600
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006601 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006602 LOG_BAD_TU(TU);
6603 return cxstring::createEmpty();
6604 }
6605
Guy Benyei11169dd2012-12-18 14:30:41 +00006606 // We have to find the starting buffer pointer the hard way, by
6607 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006608 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006609 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006610 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006611
6612 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6613 std::pair<FileID, unsigned> LocInfo
6614 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6615 bool Invalid = false;
6616 StringRef Buffer
6617 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6618 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006619 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006620
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006621 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006622}
6623
6624CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006625 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006626 LOG_BAD_TU(TU);
6627 return clang_getNullLocation();
6628 }
6629
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006630 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006631 if (!CXXUnit)
6632 return clang_getNullLocation();
6633
6634 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6635 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6636}
6637
6638CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006639 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006640 LOG_BAD_TU(TU);
6641 return clang_getNullRange();
6642 }
6643
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006644 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006645 if (!CXXUnit)
6646 return clang_getNullRange();
6647
6648 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6649 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6650}
6651
6652static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6653 SmallVectorImpl<CXToken> &CXTokens) {
6654 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6655 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006656 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006657 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006658 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006659
6660 // Cannot tokenize across files.
6661 if (BeginLocInfo.first != EndLocInfo.first)
6662 return;
6663
6664 // Create a lexer
6665 bool Invalid = false;
6666 StringRef Buffer
6667 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6668 if (Invalid)
6669 return;
6670
6671 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6672 CXXUnit->getASTContext().getLangOpts(),
6673 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6674 Lex.SetCommentRetentionState(true);
6675
6676 // Lex tokens until we hit the end of the range.
6677 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6678 Token Tok;
6679 bool previousWasAt = false;
6680 do {
6681 // Lex the next token
6682 Lex.LexFromRawLexer(Tok);
6683 if (Tok.is(tok::eof))
6684 break;
6685
6686 // Initialize the CXToken.
6687 CXToken CXTok;
6688
6689 // - Common fields
6690 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6691 CXTok.int_data[2] = Tok.getLength();
6692 CXTok.int_data[3] = 0;
6693
6694 // - Kind-specific fields
6695 if (Tok.isLiteral()) {
6696 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006697 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006698 } else if (Tok.is(tok::raw_identifier)) {
6699 // Lookup the identifier to determine whether we have a keyword.
6700 IdentifierInfo *II
6701 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6702
6703 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6704 CXTok.int_data[0] = CXToken_Keyword;
6705 }
6706 else {
6707 CXTok.int_data[0] = Tok.is(tok::identifier)
6708 ? CXToken_Identifier
6709 : CXToken_Keyword;
6710 }
6711 CXTok.ptr_data = II;
6712 } else if (Tok.is(tok::comment)) {
6713 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006714 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006715 } else {
6716 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006717 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006718 }
6719 CXTokens.push_back(CXTok);
6720 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006721 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006722}
6723
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006724CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6725 LOG_FUNC_SECTION {
6726 *Log << TU << ' ' << Location;
6727 }
6728
6729 if (isNotUsableTU(TU)) {
6730 LOG_BAD_TU(TU);
6731 return NULL;
6732 }
6733
6734 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6735 if (!CXXUnit)
6736 return NULL;
6737
6738 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6739 if (Begin.isInvalid())
6740 return NULL;
6741 SourceManager &SM = CXXUnit->getSourceManager();
6742 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6743 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6744
6745 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6746
6747 SmallVector<CXToken, 32> CXTokens;
6748 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6749
6750 if (CXTokens.empty())
6751 return NULL;
6752
6753 CXTokens.resize(1);
6754 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6755
6756 memmove(Token, CXTokens.data(), sizeof(CXToken));
6757 return Token;
6758}
6759
Guy Benyei11169dd2012-12-18 14:30:41 +00006760void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6761 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006762 LOG_FUNC_SECTION {
6763 *Log << TU << ' ' << Range;
6764 }
6765
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006767 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006768 if (NumTokens)
6769 *NumTokens = 0;
6770
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006771 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006772 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006773 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006774 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006775
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006776 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 if (!CXXUnit || !Tokens || !NumTokens)
6778 return;
6779
6780 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6781
6782 SourceRange R = cxloc::translateCXSourceRange(Range);
6783 if (R.isInvalid())
6784 return;
6785
6786 SmallVector<CXToken, 32> CXTokens;
6787 getTokens(CXXUnit, R, CXTokens);
6788
6789 if (CXTokens.empty())
6790 return;
6791
Serge Pavlov52525732018-02-21 02:02:39 +00006792 *Tokens = static_cast<CXToken *>(
6793 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006794 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6795 *NumTokens = CXTokens.size();
6796}
6797
6798void clang_disposeTokens(CXTranslationUnit TU,
6799 CXToken *Tokens, unsigned NumTokens) {
6800 free(Tokens);
6801}
6802
Guy Benyei11169dd2012-12-18 14:30:41 +00006803//===----------------------------------------------------------------------===//
6804// Token annotation APIs.
6805//===----------------------------------------------------------------------===//
6806
Guy Benyei11169dd2012-12-18 14:30:41 +00006807static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6808 CXCursor parent,
6809 CXClientData client_data);
6810static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6811 CXClientData client_data);
6812
6813namespace {
6814class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006815 CXToken *Tokens;
6816 CXCursor *Cursors;
6817 unsigned NumTokens;
6818 unsigned TokIdx;
6819 unsigned PreprocessingTokIdx;
6820 CursorVisitor AnnotateVis;
6821 SourceManager &SrcMgr;
6822 bool HasContextSensitiveKeywords;
6823
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006824 struct PostChildrenAction {
6825 CXCursor cursor;
6826 enum Action { Invalid, Ignore, Postpone } action;
6827 };
6828 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6829
Guy Benyei11169dd2012-12-18 14:30:41 +00006830 struct PostChildrenInfo {
6831 CXCursor Cursor;
6832 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006833 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006834 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006835 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006836 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006837 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006838
6839 CXToken &getTok(unsigned Idx) {
6840 assert(Idx < NumTokens);
6841 return Tokens[Idx];
6842 }
6843 const CXToken &getTok(unsigned Idx) const {
6844 assert(Idx < NumTokens);
6845 return Tokens[Idx];
6846 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006847 bool MoreTokens() const { return TokIdx < NumTokens; }
6848 unsigned NextToken() const { return TokIdx; }
6849 void AdvanceToken() { ++TokIdx; }
6850 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006851 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006852 }
6853 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006854 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 }
6856 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006857 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006858 }
6859
6860 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006861 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006862 SourceRange);
6863
6864public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006865 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006866 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006867 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006868 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006869 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006870 AnnotateTokensVisitor, this,
6871 /*VisitPreprocessorLast=*/true,
6872 /*VisitIncludedEntities=*/false,
6873 RegionOfInterest,
6874 /*VisitDeclsOnly=*/false,
6875 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006876 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006877 HasContextSensitiveKeywords(false) { }
6878
6879 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6880 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006881 bool IsIgnoredChildCursor(CXCursor cursor) const;
6882 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6883
Guy Benyei11169dd2012-12-18 14:30:41 +00006884 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006885 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6886 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6887
Guy Benyei11169dd2012-12-18 14:30:41 +00006888 void AnnotateTokens();
6889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006890 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 /// context-sensitive keywords.
6892 bool hasContextSensitiveKeywords() const {
6893 return HasContextSensitiveKeywords;
6894 }
6895
6896 ~AnnotateTokensWorker() {
6897 assert(PostChildrenInfos.empty());
6898 }
6899};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006900}
Guy Benyei11169dd2012-12-18 14:30:41 +00006901
6902void AnnotateTokensWorker::AnnotateTokens() {
6903 // Walk the AST within the region of interest, annotating tokens
6904 // along the way.
6905 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006906}
Guy Benyei11169dd2012-12-18 14:30:41 +00006907
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006908bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6909 if (PostChildrenInfos.empty())
6910 return false;
6911
6912 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6913 if (ChildAction.cursor == cursor &&
6914 ChildAction.action == PostChildrenAction::Ignore) {
6915 return true;
6916 }
6917 }
6918
6919 return false;
6920}
6921
6922const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6923 if (!clang_isExpression(Cursor.kind))
6924 return nullptr;
6925
6926 const Expr *E = getCursorExpr(Cursor);
6927 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6928 const OverloadedOperatorKind Kind = OCE->getOperator();
6929 if (Kind == OO_Call || Kind == OO_Subscript)
6930 return OCE;
6931 }
6932
6933 return nullptr;
6934}
6935
6936AnnotateTokensWorker::PostChildrenActions
6937AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6938 PostChildrenActions actions;
6939
6940 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6941 // visited before the arguments to the operator call. For the Call and
6942 // Subscript operator the range of this DeclRefExpr includes the whole call
6943 // expression, so that all tokens in that range would be mapped to the
6944 // operator function, including the tokens of the arguments. To avoid that,
6945 // ensure to visit this DeclRefExpr as last node.
6946 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6947 const Expr *Callee = OCE->getCallee();
6948 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6949 const Expr *SubExpr = ICE->getSubExpr();
6950 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00006951 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006952 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6953
6954 // Visit the DeclRefExpr as last.
6955 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6956 actions.push_back({cxChild, PostChildrenAction::Postpone});
6957
6958 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6959 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6960 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6961 actions.push_back({cxChild, PostChildrenAction::Ignore});
6962 }
6963 }
6964 }
6965
6966 return actions;
6967}
6968
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006969static inline void updateCursorAnnotation(CXCursor &Cursor,
6970 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006971 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006972 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006973 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006974}
6975
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006976/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006977//// between the cursor location and the source range is the same as
6978/// \arg compResult.
6979///
6980/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6981/// Pass RangeOverlap to annotate tokens inside a range.
6982void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6983 RangeComparisonResult compResult,
6984 SourceRange range) {
6985 while (MoreTokens()) {
6986 const unsigned I = NextToken();
6987 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006988 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6989 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006990
6991 SourceLocation TokLoc = GetTokenLoc(I);
6992 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006993 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006994 AdvanceToken();
6995 continue;
6996 }
6997 break;
6998 }
6999}
7000
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007001/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007002/// \returns true if it advanced beyond all macro tokens, false otherwise.
7003bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007004 CXCursor updateC,
7005 RangeComparisonResult compResult,
7006 SourceRange range) {
7007 assert(MoreTokens());
7008 assert(isFunctionMacroToken(NextToken()) &&
7009 "Should be called only for macro arg tokens");
7010
7011 // This works differently than annotateAndAdvanceTokens; because expanded
7012 // macro arguments can have arbitrary translation-unit source order, we do not
7013 // advance the token index one by one until a token fails the range test.
7014 // We only advance once past all of the macro arg tokens if all of them
7015 // pass the range test. If one of them fails we keep the token index pointing
7016 // at the start of the macro arg tokens so that the failing token will be
7017 // annotated by a subsequent annotation try.
7018
7019 bool atLeastOneCompFail = false;
7020
7021 unsigned I = NextToken();
7022 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7023 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7024 if (TokLoc.isFileID())
7025 continue; // not macro arg token, it's parens or comma.
7026 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7027 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7028 Cursors[I] = updateC;
7029 } else
7030 atLeastOneCompFail = true;
7031 }
7032
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007033 if (atLeastOneCompFail)
7034 return false;
7035
7036 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7037 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007038}
7039
7040enum CXChildVisitResult
7041AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007042 SourceRange cursorRange = getRawCursorExtent(cursor);
7043 if (cursorRange.isInvalid())
7044 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007045
7046 if (IsIgnoredChildCursor(cursor))
7047 return CXChildVisit_Continue;
7048
Guy Benyei11169dd2012-12-18 14:30:41 +00007049 if (!HasContextSensitiveKeywords) {
7050 // Objective-C properties can have context-sensitive keywords.
7051 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007052 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007053 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7054 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7055 }
7056 // Objective-C methods can have context-sensitive keywords.
7057 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7058 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007059 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007060 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7061 if (Method->getObjCDeclQualifier())
7062 HasContextSensitiveKeywords = true;
7063 else {
David Majnemer59f77922016-06-24 04:05:48 +00007064 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007065 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 HasContextSensitiveKeywords = true;
7067 break;
7068 }
7069 }
7070 }
7071 }
7072 }
7073 // C++ methods can have context-sensitive keywords.
7074 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007075 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007076 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7077 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7078 HasContextSensitiveKeywords = true;
7079 }
7080 }
7081 // C++ classes can have context-sensitive keywords.
7082 else if (cursor.kind == CXCursor_StructDecl ||
7083 cursor.kind == CXCursor_ClassDecl ||
7084 cursor.kind == CXCursor_ClassTemplate ||
7085 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007086 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007087 if (D->hasAttr<FinalAttr>())
7088 HasContextSensitiveKeywords = true;
7089 }
7090 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007091
7092 // Don't override a property annotation with its getter/setter method.
7093 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7094 parent.kind == CXCursor_ObjCPropertyDecl)
7095 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007096
7097 if (clang_isPreprocessing(cursor.kind)) {
7098 // Items in the preprocessing record are kept separate from items in
7099 // declarations, so we keep a separate token index.
7100 unsigned SavedTokIdx = TokIdx;
7101 TokIdx = PreprocessingTokIdx;
7102
7103 // Skip tokens up until we catch up to the beginning of the preprocessing
7104 // entry.
7105 while (MoreTokens()) {
7106 const unsigned I = NextToken();
7107 SourceLocation TokLoc = GetTokenLoc(I);
7108 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7109 case RangeBefore:
7110 AdvanceToken();
7111 continue;
7112 case RangeAfter:
7113 case RangeOverlap:
7114 break;
7115 }
7116 break;
7117 }
7118
7119 // Look at all of the tokens within this range.
7120 while (MoreTokens()) {
7121 const unsigned I = NextToken();
7122 SourceLocation TokLoc = GetTokenLoc(I);
7123 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7124 case RangeBefore:
7125 llvm_unreachable("Infeasible");
7126 case RangeAfter:
7127 break;
7128 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007129 // For macro expansions, just note where the beginning of the macro
7130 // expansion occurs.
7131 if (cursor.kind == CXCursor_MacroExpansion) {
7132 if (TokLoc == cursorRange.getBegin())
7133 Cursors[I] = cursor;
7134 AdvanceToken();
7135 break;
7136 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007137 // We may have already annotated macro names inside macro definitions.
7138 if (Cursors[I].kind != CXCursor_MacroExpansion)
7139 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007140 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007141 continue;
7142 }
7143 break;
7144 }
7145
7146 // Save the preprocessing token index; restore the non-preprocessing
7147 // token index.
7148 PreprocessingTokIdx = TokIdx;
7149 TokIdx = SavedTokIdx;
7150 return CXChildVisit_Recurse;
7151 }
7152
7153 if (cursorRange.isInvalid())
7154 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007155
7156 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007158 const enum CXCursorKind K = clang_getCursorKind(parent);
7159 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007160 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7161 // Attributes are annotated out-of-order, skip tokens until we reach it.
7162 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 ? clang_getNullCursor() : parent;
7164
7165 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7166
7167 // Avoid having the cursor of an expression "overwrite" the annotation of the
7168 // variable declaration that it belongs to.
7169 // This can happen for C++ constructor expressions whose range generally
7170 // include the variable declaration, e.g.:
7171 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007172 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007173 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007174 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007175 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007176 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7177 E->getBeginLoc() == D->getLocation() &&
7178 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007179 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007180 AdvanceToken();
7181 }
7182 }
7183 }
7184
7185 // Before recursing into the children keep some state that we are going
7186 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7187 // extra work after the child nodes are visited.
7188 // Note that we don't call VisitChildren here to avoid traversing statements
7189 // code-recursively which can blow the stack.
7190
7191 PostChildrenInfo Info;
7192 Info.Cursor = cursor;
7193 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007194 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007195 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007196 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007197 PostChildrenInfos.push_back(Info);
7198
7199 return CXChildVisit_Recurse;
7200}
7201
7202bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7203 if (PostChildrenInfos.empty())
7204 return false;
7205 const PostChildrenInfo &Info = PostChildrenInfos.back();
7206 if (!clang_equalCursors(Info.Cursor, cursor))
7207 return false;
7208
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007209 HandlePostPonedChildCursors(Info);
7210
Guy Benyei11169dd2012-12-18 14:30:41 +00007211 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7212 const unsigned AfterChildren = NextToken();
7213 SourceRange cursorRange = Info.CursorRange;
7214
7215 // Scan the tokens that are at the end of the cursor, but are not captured
7216 // but the child cursors.
7217 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7218
7219 // Scan the tokens that are at the beginning of the cursor, but are not
7220 // capture by the child cursors.
7221 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7222 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7223 break;
7224
7225 Cursors[I] = cursor;
7226 }
7227
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007228 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7229 // encountered the attribute cursor.
7230 if (clang_isAttribute(cursor.kind))
7231 TokIdx = Info.BeforeReachingCursorIdx;
7232
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 PostChildrenInfos.pop_back();
7234 return false;
7235}
7236
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007237void AnnotateTokensWorker::HandlePostPonedChildCursors(
7238 const PostChildrenInfo &Info) {
7239 for (const auto &ChildAction : Info.ChildActions) {
7240 if (ChildAction.action == PostChildrenAction::Postpone) {
7241 HandlePostPonedChildCursor(ChildAction.cursor,
7242 Info.BeforeChildrenTokenIdx);
7243 }
7244 }
7245}
7246
7247void AnnotateTokensWorker::HandlePostPonedChildCursor(
7248 CXCursor Cursor, unsigned StartTokenIndex) {
7249 const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier;
7250 unsigned I = StartTokenIndex;
7251
7252 // The bracket tokens of a Call or Subscript operator are mapped to
7253 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7254 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7255 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
7256 const CXSourceRange CXRefNameRange =
7257 clang_getCursorReferenceNameRange(Cursor, flags, RefNameRangeNr);
7258 if (clang_Range_isNull(CXRefNameRange))
7259 break; // All ranges handled.
7260
7261 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7262 while (I < NumTokens) {
7263 const SourceLocation TokenLocation = GetTokenLoc(I);
7264 if (!TokenLocation.isValid())
7265 break;
7266
7267 // Adapt the end range, because LocationCompare() reports
7268 // RangeOverlap even for the not-inclusive end location.
7269 const SourceLocation fixedEnd =
7270 RefNameRange.getEnd().getLocWithOffset(-1);
7271 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7272
7273 const RangeComparisonResult ComparisonResult =
7274 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7275
7276 if (ComparisonResult == RangeOverlap) {
7277 Cursors[I++] = Cursor;
7278 } else if (ComparisonResult == RangeBefore) {
7279 ++I; // Not relevant token, check next one.
7280 } else if (ComparisonResult == RangeAfter) {
7281 break; // All tokens updated for current range, check next.
7282 }
7283 }
7284 }
7285}
7286
Guy Benyei11169dd2012-12-18 14:30:41 +00007287static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7288 CXCursor parent,
7289 CXClientData client_data) {
7290 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7291}
7292
7293static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7294 CXClientData client_data) {
7295 return static_cast<AnnotateTokensWorker*>(client_data)->
7296 postVisitChildren(cursor);
7297}
7298
7299namespace {
7300
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007301/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007302/// and mark tokens that are macro arguments. This info is used by the
7303/// AnnotateTokensWorker.
7304class MarkMacroArgTokensVisitor {
7305 SourceManager &SM;
7306 CXToken *Tokens;
7307 unsigned NumTokens;
7308 unsigned CurIdx;
7309
7310public:
7311 MarkMacroArgTokensVisitor(SourceManager &SM,
7312 CXToken *tokens, unsigned numTokens)
7313 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7314
7315 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7316 if (cursor.kind != CXCursor_MacroExpansion)
7317 return CXChildVisit_Continue;
7318
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007319 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007320 if (macroRange.getBegin() == macroRange.getEnd())
7321 return CXChildVisit_Continue; // it's not a function macro.
7322
7323 for (; CurIdx < NumTokens; ++CurIdx) {
7324 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7325 macroRange.getBegin()))
7326 break;
7327 }
7328
7329 if (CurIdx == NumTokens)
7330 return CXChildVisit_Break;
7331
7332 for (; CurIdx < NumTokens; ++CurIdx) {
7333 SourceLocation tokLoc = getTokenLoc(CurIdx);
7334 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7335 break;
7336
7337 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7338 }
7339
7340 if (CurIdx == NumTokens)
7341 return CXChildVisit_Break;
7342
7343 return CXChildVisit_Continue;
7344 }
7345
7346private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007347 CXToken &getTok(unsigned Idx) {
7348 assert(Idx < NumTokens);
7349 return Tokens[Idx];
7350 }
7351 const CXToken &getTok(unsigned Idx) const {
7352 assert(Idx < NumTokens);
7353 return Tokens[Idx];
7354 }
7355
Guy Benyei11169dd2012-12-18 14:30:41 +00007356 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007357 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007358 }
7359
7360 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7361 // The third field is reserved and currently not used. Use it here
7362 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007363 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007364 }
7365};
7366
7367} // end anonymous namespace
7368
7369static CXChildVisitResult
7370MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7371 CXClientData client_data) {
7372 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7373 parent);
7374}
7375
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007376/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007377/// \returns true if lexing was finished, false otherwise.
7378static bool lexNext(Lexer &Lex, Token &Tok,
7379 unsigned &NextIdx, unsigned NumTokens) {
7380 if (NextIdx >= NumTokens)
7381 return true;
7382
7383 ++NextIdx;
7384 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007385 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007386}
7387
Guy Benyei11169dd2012-12-18 14:30:41 +00007388static void annotatePreprocessorTokens(CXTranslationUnit TU,
7389 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007390 CXCursor *Cursors,
7391 CXToken *Tokens,
7392 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007393 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007394
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007395 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007396 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7397 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007398 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007399 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007400 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007401
7402 if (BeginLocInfo.first != EndLocInfo.first)
7403 return;
7404
7405 StringRef Buffer;
7406 bool Invalid = false;
7407 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7408 if (Buffer.empty() || Invalid)
7409 return;
7410
7411 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7412 CXXUnit->getASTContext().getLangOpts(),
7413 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7414 Buffer.end());
7415 Lex.SetCommentRetentionState(true);
7416
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007417 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 // Lex tokens in raw mode until we hit the end of the range, to avoid
7419 // entering #includes or expanding macros.
7420 while (true) {
7421 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007422 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7423 break;
7424 unsigned TokIdx = NextIdx-1;
7425 assert(Tok.getLocation() ==
7426 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007427
7428 reprocess:
7429 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007430 // We have found a preprocessing directive. Annotate the tokens
7431 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007432 //
7433 // FIXME: Some simple tests here could identify macro definitions and
7434 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007435
7436 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007437 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7438 break;
7439
Craig Topper69186e72014-06-08 08:38:04 +00007440 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007441 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007442 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7443 break;
7444
7445 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007446 IdentifierInfo &II =
7447 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007448 SourceLocation MappedTokLoc =
7449 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7450 MI = getMacroInfo(II, MappedTokLoc, TU);
7451 }
7452 }
7453
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007454 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007455 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007456 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7457 finished = true;
7458 break;
7459 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007460 // If we are in a macro definition, check if the token was ever a
7461 // macro name and annotate it if that's the case.
7462 if (MI) {
7463 SourceLocation SaveLoc = Tok.getLocation();
7464 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007465 MacroDefinitionRecord *MacroDef =
7466 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007467 Tok.setLocation(SaveLoc);
7468 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007469 Cursors[NextIdx - 1] =
7470 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007471 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007472 } while (!Tok.isAtStartOfLine());
7473
7474 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7475 assert(TokIdx <= LastIdx);
7476 SourceLocation EndLoc =
7477 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7478 CXCursor Cursor =
7479 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7480
7481 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007482 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007483
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007484 if (finished)
7485 break;
7486 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007488 }
7489}
7490
7491// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007492static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7493 CXToken *Tokens, unsigned NumTokens,
7494 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007495 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007496 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7497 setThreadBackgroundPriority();
7498
7499 // Determine the region of interest, which contains all of the tokens.
7500 SourceRange RegionOfInterest;
7501 RegionOfInterest.setBegin(
7502 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7503 RegionOfInterest.setEnd(
7504 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7505 Tokens[NumTokens-1])));
7506
Guy Benyei11169dd2012-12-18 14:30:41 +00007507 // Relex the tokens within the source range to look for preprocessing
7508 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007509 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007510
7511 // If begin location points inside a macro argument, set it to the expansion
7512 // location so we can have the full context when annotating semantically.
7513 {
7514 SourceManager &SM = CXXUnit->getSourceManager();
7515 SourceLocation Loc =
7516 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7517 if (Loc.isMacroID())
7518 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7519 }
7520
Guy Benyei11169dd2012-12-18 14:30:41 +00007521 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7522 // Search and mark tokens that are macro argument expansions.
7523 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7524 Tokens, NumTokens);
7525 CursorVisitor MacroArgMarker(TU,
7526 MarkMacroArgTokensVisitorDelegate, &Visitor,
7527 /*VisitPreprocessorLast=*/true,
7528 /*VisitIncludedEntities=*/false,
7529 RegionOfInterest);
7530 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7531 }
7532
7533 // Annotate all of the source locations in the region of interest that map to
7534 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007535 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007536
7537 // FIXME: We use a ridiculous stack size here because the data-recursion
7538 // algorithm uses a large stack frame than the non-data recursive version,
7539 // and AnnotationTokensWorker currently transforms the data-recursion
7540 // algorithm back into a traditional recursion by explicitly calling
7541 // VisitChildren(). We will need to remove this explicit recursive call.
7542 W.AnnotateTokens();
7543
7544 // If we ran into any entities that involve context-sensitive keywords,
7545 // take another pass through the tokens to mark them as such.
7546 if (W.hasContextSensitiveKeywords()) {
7547 for (unsigned I = 0; I != NumTokens; ++I) {
7548 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7549 continue;
7550
7551 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7552 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007553 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007554 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7555 if (Property->getPropertyAttributesAsWritten() != 0 &&
7556 llvm::StringSwitch<bool>(II->getName())
7557 .Case("readonly", true)
7558 .Case("assign", true)
7559 .Case("unsafe_unretained", true)
7560 .Case("readwrite", true)
7561 .Case("retain", true)
7562 .Case("copy", true)
7563 .Case("nonatomic", true)
7564 .Case("atomic", true)
7565 .Case("getter", true)
7566 .Case("setter", true)
7567 .Case("strong", true)
7568 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007569 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007570 .Default(false))
7571 Tokens[I].int_data[0] = CXToken_Keyword;
7572 }
7573 continue;
7574 }
7575
7576 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7577 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7578 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7579 if (llvm::StringSwitch<bool>(II->getName())
7580 .Case("in", true)
7581 .Case("out", true)
7582 .Case("inout", true)
7583 .Case("oneway", true)
7584 .Case("bycopy", true)
7585 .Case("byref", true)
7586 .Default(false))
7587 Tokens[I].int_data[0] = CXToken_Keyword;
7588 continue;
7589 }
7590
7591 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7592 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7593 Tokens[I].int_data[0] = CXToken_Keyword;
7594 continue;
7595 }
7596 }
7597 }
7598}
7599
Guy Benyei11169dd2012-12-18 14:30:41 +00007600void clang_annotateTokens(CXTranslationUnit TU,
7601 CXToken *Tokens, unsigned NumTokens,
7602 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007603 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007604 LOG_BAD_TU(TU);
7605 return;
7606 }
7607 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007608 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007609 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007610 }
7611
7612 LOG_FUNC_SECTION {
7613 *Log << TU << ' ';
7614 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7615 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7616 *Log << clang_getRange(bloc, eloc);
7617 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007618
7619 // Any token we don't specifically annotate will have a NULL cursor.
7620 CXCursor C = clang_getNullCursor();
7621 for (unsigned I = 0; I != NumTokens; ++I)
7622 Cursors[I] = C;
7623
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007624 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007625 if (!CXXUnit)
7626 return;
7627
7628 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007629
7630 auto AnnotateTokensImpl = [=]() {
7631 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7632 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007633 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007634 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007635 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7636 }
7637}
7638
Guy Benyei11169dd2012-12-18 14:30:41 +00007639//===----------------------------------------------------------------------===//
7640// Operations for querying linkage of a cursor.
7641//===----------------------------------------------------------------------===//
7642
Guy Benyei11169dd2012-12-18 14:30:41 +00007643CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7644 if (!clang_isDeclaration(cursor.kind))
7645 return CXLinkage_Invalid;
7646
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007647 const Decl *D = cxcursor::getCursorDecl(cursor);
7648 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007649 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007650 case NoLinkage:
7651 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007652 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007653 case InternalLinkage: return CXLinkage_Internal;
7654 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007655 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007656 case ExternalLinkage: return CXLinkage_External;
7657 };
7658
7659 return CXLinkage_Invalid;
7660}
Guy Benyei11169dd2012-12-18 14:30:41 +00007661
7662//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007663// Operations for querying visibility of a cursor.
7664//===----------------------------------------------------------------------===//
7665
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007666CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7667 if (!clang_isDeclaration(cursor.kind))
7668 return CXVisibility_Invalid;
7669
7670 const Decl *D = cxcursor::getCursorDecl(cursor);
7671 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7672 switch (ND->getVisibility()) {
7673 case HiddenVisibility: return CXVisibility_Hidden;
7674 case ProtectedVisibility: return CXVisibility_Protected;
7675 case DefaultVisibility: return CXVisibility_Default;
7676 };
7677
7678 return CXVisibility_Invalid;
7679}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007680
7681//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007682// Operations for querying language of a cursor.
7683//===----------------------------------------------------------------------===//
7684
7685static CXLanguageKind getDeclLanguage(const Decl *D) {
7686 if (!D)
7687 return CXLanguage_C;
7688
7689 switch (D->getKind()) {
7690 default:
7691 break;
7692 case Decl::ImplicitParam:
7693 case Decl::ObjCAtDefsField:
7694 case Decl::ObjCCategory:
7695 case Decl::ObjCCategoryImpl:
7696 case Decl::ObjCCompatibleAlias:
7697 case Decl::ObjCImplementation:
7698 case Decl::ObjCInterface:
7699 case Decl::ObjCIvar:
7700 case Decl::ObjCMethod:
7701 case Decl::ObjCProperty:
7702 case Decl::ObjCPropertyImpl:
7703 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007704 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007705 return CXLanguage_ObjC;
7706 case Decl::CXXConstructor:
7707 case Decl::CXXConversion:
7708 case Decl::CXXDestructor:
7709 case Decl::CXXMethod:
7710 case Decl::CXXRecord:
7711 case Decl::ClassTemplate:
7712 case Decl::ClassTemplatePartialSpecialization:
7713 case Decl::ClassTemplateSpecialization:
7714 case Decl::Friend:
7715 case Decl::FriendTemplate:
7716 case Decl::FunctionTemplate:
7717 case Decl::LinkageSpec:
7718 case Decl::Namespace:
7719 case Decl::NamespaceAlias:
7720 case Decl::NonTypeTemplateParm:
7721 case Decl::StaticAssert:
7722 case Decl::TemplateTemplateParm:
7723 case Decl::TemplateTypeParm:
7724 case Decl::UnresolvedUsingTypename:
7725 case Decl::UnresolvedUsingValue:
7726 case Decl::Using:
7727 case Decl::UsingDirective:
7728 case Decl::UsingShadow:
7729 return CXLanguage_CPlusPlus;
7730 }
7731
7732 return CXLanguage_C;
7733}
7734
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007735static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7736 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007737 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007738
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007739 switch (D->getAvailability()) {
7740 case AR_Available:
7741 case AR_NotYetIntroduced:
7742 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007743 return getCursorAvailabilityForDecl(
7744 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007745 return CXAvailability_Available;
7746
7747 case AR_Deprecated:
7748 return CXAvailability_Deprecated;
7749
7750 case AR_Unavailable:
7751 return CXAvailability_NotAvailable;
7752 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007753
7754 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007755}
7756
Guy Benyei11169dd2012-12-18 14:30:41 +00007757enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7758 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007759 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7760 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007761
7762 return CXAvailability_Available;
7763}
7764
7765static CXVersion convertVersion(VersionTuple In) {
7766 CXVersion Out = { -1, -1, -1 };
7767 if (In.empty())
7768 return Out;
7769
7770 Out.Major = In.getMajor();
7771
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007772 Optional<unsigned> Minor = In.getMinor();
7773 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007774 Out.Minor = *Minor;
7775 else
7776 return Out;
7777
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007778 Optional<unsigned> Subminor = In.getSubminor();
7779 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007780 Out.Subminor = *Subminor;
7781
7782 return Out;
7783}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007784
Alex Lorenz1345ea22017-06-12 19:06:30 +00007785static void getCursorPlatformAvailabilityForDecl(
7786 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7787 int *always_unavailable, CXString *unavailable_message,
7788 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007789 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007790 for (auto A : D->attrs()) {
7791 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007792 HadAvailAttr = true;
7793 if (always_deprecated)
7794 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007795 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007796 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007797 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007798 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007799 continue;
7800 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007801
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007802 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007803 HadAvailAttr = true;
7804 if (always_unavailable)
7805 *always_unavailable = 1;
7806 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007807 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007808 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7809 }
7810 continue;
7811 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007812
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007813 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007814 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007815 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007816 }
7817 }
7818
7819 if (!HadAvailAttr)
7820 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7821 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007822 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7823 deprecated_message, always_unavailable, unavailable_message,
7824 AvailabilityAttrs);
7825
7826 if (AvailabilityAttrs.empty())
7827 return;
7828
Fangrui Song55fab262018-09-26 22:16:28 +00007829 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007830 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7831 return LHS->getPlatform()->getName() <
7832 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007833 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007834 ASTContext &Ctx = D->getASTContext();
7835 auto It = std::unique(
7836 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7837 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7838 if (LHS->getPlatform() != RHS->getPlatform())
7839 return false;
7840
7841 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7842 LHS->getDeprecated() == RHS->getDeprecated() &&
7843 LHS->getObsoleted() == RHS->getObsoleted() &&
7844 LHS->getMessage() == RHS->getMessage() &&
7845 LHS->getReplacement() == RHS->getReplacement())
7846 return true;
7847
7848 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7849 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7850 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7851 return false;
7852
7853 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7854 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7855
7856 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7857 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7858 if (LHS->getMessage().empty())
7859 LHS->setMessage(Ctx, RHS->getMessage());
7860 if (LHS->getReplacement().empty())
7861 LHS->setReplacement(Ctx, RHS->getReplacement());
7862 }
7863
7864 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7865 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7866 if (LHS->getMessage().empty())
7867 LHS->setMessage(Ctx, RHS->getMessage());
7868 if (LHS->getReplacement().empty())
7869 LHS->setReplacement(Ctx, RHS->getReplacement());
7870 }
7871
7872 return true;
7873 });
7874 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007875}
7876
Alex Lorenz1345ea22017-06-12 19:06:30 +00007877int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007878 CXString *deprecated_message,
7879 int *always_unavailable,
7880 CXString *unavailable_message,
7881 CXPlatformAvailability *availability,
7882 int availability_size) {
7883 if (always_deprecated)
7884 *always_deprecated = 0;
7885 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007886 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007887 if (always_unavailable)
7888 *always_unavailable = 0;
7889 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007890 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007891
Guy Benyei11169dd2012-12-18 14:30:41 +00007892 if (!clang_isDeclaration(cursor.kind))
7893 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007894
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007895 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007896 if (!D)
7897 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007898
Alex Lorenz1345ea22017-06-12 19:06:30 +00007899 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7900 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7901 always_unavailable, unavailable_message,
7902 AvailabilityAttrs);
7903 for (const auto &Avail :
7904 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7905 .take_front(availability_size))) {
7906 availability[Avail.index()].Platform =
7907 cxstring::createDup(Avail.value()->getPlatform()->getName());
7908 availability[Avail.index()].Introduced =
7909 convertVersion(Avail.value()->getIntroduced());
7910 availability[Avail.index()].Deprecated =
7911 convertVersion(Avail.value()->getDeprecated());
7912 availability[Avail.index()].Obsoleted =
7913 convertVersion(Avail.value()->getObsoleted());
7914 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7915 availability[Avail.index()].Message =
7916 cxstring::createDup(Avail.value()->getMessage());
7917 }
7918
7919 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007920}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007921
Guy Benyei11169dd2012-12-18 14:30:41 +00007922void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7923 clang_disposeString(availability->Platform);
7924 clang_disposeString(availability->Message);
7925}
7926
7927CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7928 if (clang_isDeclaration(cursor.kind))
7929 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7930
7931 return CXLanguage_Invalid;
7932}
7933
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007934CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7935 const Decl *D = cxcursor::getCursorDecl(cursor);
7936 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7937 switch (VD->getTLSKind()) {
7938 case VarDecl::TLS_None:
7939 return CXTLS_None;
7940 case VarDecl::TLS_Dynamic:
7941 return CXTLS_Dynamic;
7942 case VarDecl::TLS_Static:
7943 return CXTLS_Static;
7944 }
7945 }
7946
7947 return CXTLS_None;
7948}
7949
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007950 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007951 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007952 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007953static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007954 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007955 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007956
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007957 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007958 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7959 return FunTmpl;
7960
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007961 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007962 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7963 return ClassTmpl;
7964
7965 return D;
7966}
7967
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007968
7969enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7970 StorageClass sc = SC_None;
7971 const Decl *D = getCursorDecl(C);
7972 if (D) {
7973 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7974 sc = FD->getStorageClass();
7975 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7976 sc = VD->getStorageClass();
7977 } else {
7978 return CX_SC_Invalid;
7979 }
7980 } else {
7981 return CX_SC_Invalid;
7982 }
7983 switch (sc) {
7984 case SC_None:
7985 return CX_SC_None;
7986 case SC_Extern:
7987 return CX_SC_Extern;
7988 case SC_Static:
7989 return CX_SC_Static;
7990 case SC_PrivateExtern:
7991 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007992 case SC_Auto:
7993 return CX_SC_Auto;
7994 case SC_Register:
7995 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007996 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007997 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007998}
7999
Guy Benyei11169dd2012-12-18 14:30:41 +00008000CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8001 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008002 if (const Decl *D = getCursorDecl(cursor)) {
8003 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008004 if (!DC)
8005 return clang_getNullCursor();
8006
8007 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8008 getCursorTU(cursor));
8009 }
8010 }
8011
8012 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008013 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008014 return MakeCXCursor(D, getCursorTU(cursor));
8015 }
8016
8017 return clang_getNullCursor();
8018}
8019
8020CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8021 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008022 if (const Decl *D = getCursorDecl(cursor)) {
8023 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008024 if (!DC)
8025 return clang_getNullCursor();
8026
8027 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8028 getCursorTU(cursor));
8029 }
8030 }
8031
8032 // FIXME: Note that we can't easily compute the lexical context of a
8033 // statement or expression, so we return nothing.
8034 return clang_getNullCursor();
8035}
8036
8037CXFile clang_getIncludedFile(CXCursor cursor) {
8038 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008039 return nullptr;
8040
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008041 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008042 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008043}
8044
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008045unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8046 if (C.kind != CXCursor_ObjCPropertyDecl)
8047 return CXObjCPropertyAttr_noattr;
8048
8049 unsigned Result = CXObjCPropertyAttr_noattr;
8050 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8051 ObjCPropertyDecl::PropertyAttributeKind Attr =
8052 PD->getPropertyAttributesAsWritten();
8053
8054#define SET_CXOBJCPROP_ATTR(A) \
8055 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8056 Result |= CXObjCPropertyAttr_##A
8057 SET_CXOBJCPROP_ATTR(readonly);
8058 SET_CXOBJCPROP_ATTR(getter);
8059 SET_CXOBJCPROP_ATTR(assign);
8060 SET_CXOBJCPROP_ATTR(readwrite);
8061 SET_CXOBJCPROP_ATTR(retain);
8062 SET_CXOBJCPROP_ATTR(copy);
8063 SET_CXOBJCPROP_ATTR(nonatomic);
8064 SET_CXOBJCPROP_ATTR(setter);
8065 SET_CXOBJCPROP_ATTR(atomic);
8066 SET_CXOBJCPROP_ATTR(weak);
8067 SET_CXOBJCPROP_ATTR(strong);
8068 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008069 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008070#undef SET_CXOBJCPROP_ATTR
8071
8072 return Result;
8073}
8074
Michael Wu6e88f532018-08-03 05:38:29 +00008075CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8076 if (C.kind != CXCursor_ObjCPropertyDecl)
8077 return cxstring::createNull();
8078
8079 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8080 Selector sel = PD->getGetterName();
8081 if (sel.isNull())
8082 return cxstring::createNull();
8083
8084 return cxstring::createDup(sel.getAsString());
8085}
8086
8087CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8088 if (C.kind != CXCursor_ObjCPropertyDecl)
8089 return cxstring::createNull();
8090
8091 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8092 Selector sel = PD->getSetterName();
8093 if (sel.isNull())
8094 return cxstring::createNull();
8095
8096 return cxstring::createDup(sel.getAsString());
8097}
8098
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008099unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8100 if (!clang_isDeclaration(C.kind))
8101 return CXObjCDeclQualifier_None;
8102
8103 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8104 const Decl *D = getCursorDecl(C);
8105 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8106 QT = MD->getObjCDeclQualifier();
8107 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8108 QT = PD->getObjCDeclQualifier();
8109 if (QT == Decl::OBJC_TQ_None)
8110 return CXObjCDeclQualifier_None;
8111
8112 unsigned Result = CXObjCDeclQualifier_None;
8113 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8114 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8115 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8116 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8117 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8118 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8119
8120 return Result;
8121}
8122
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008123unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8124 if (!clang_isDeclaration(C.kind))
8125 return 0;
8126
8127 const Decl *D = getCursorDecl(C);
8128 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8129 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8130 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8131 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8132
8133 return 0;
8134}
8135
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008136unsigned clang_Cursor_isVariadic(CXCursor C) {
8137 if (!clang_isDeclaration(C.kind))
8138 return 0;
8139
8140 const Decl *D = getCursorDecl(C);
8141 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8142 return FD->isVariadic();
8143 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8144 return MD->isVariadic();
8145
8146 return 0;
8147}
8148
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008149unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8150 CXString *language, CXString *definedIn,
8151 unsigned *isGenerated) {
8152 if (!clang_isDeclaration(C.kind))
8153 return 0;
8154
8155 const Decl *D = getCursorDecl(C);
8156
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008157 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008158 if (language)
8159 *language = cxstring::createDup(attr->getLanguage());
8160 if (definedIn)
8161 *definedIn = cxstring::createDup(attr->getDefinedIn());
8162 if (isGenerated)
8163 *isGenerated = attr->getGeneratedDeclaration();
8164 return 1;
8165 }
8166 return 0;
8167}
8168
Guy Benyei11169dd2012-12-18 14:30:41 +00008169CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8170 if (!clang_isDeclaration(C.kind))
8171 return clang_getNullRange();
8172
8173 const Decl *D = getCursorDecl(C);
8174 ASTContext &Context = getCursorContext(C);
8175 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8176 if (!RC)
8177 return clang_getNullRange();
8178
8179 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8180}
8181
8182CXString clang_Cursor_getRawCommentText(CXCursor C) {
8183 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008184 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008185
8186 const Decl *D = getCursorDecl(C);
8187 ASTContext &Context = getCursorContext(C);
8188 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8189 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8190 StringRef();
8191
8192 // Don't duplicate the string because RawText points directly into source
8193 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008194 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008195}
8196
8197CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8198 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008199 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008200
8201 const Decl *D = getCursorDecl(C);
8202 const ASTContext &Context = getCursorContext(C);
8203 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8204
8205 if (RC) {
8206 StringRef BriefText = RC->getBriefText(Context);
8207
8208 // Don't duplicate the string because RawComment ensures that this memory
8209 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008210 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 }
8212
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008213 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008214}
8215
Guy Benyei11169dd2012-12-18 14:30:41 +00008216CXModule clang_Cursor_getModule(CXCursor C) {
8217 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008218 if (const ImportDecl *ImportD =
8219 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 return ImportD->getImportedModule();
8221 }
8222
Craig Topper69186e72014-06-08 08:38:04 +00008223 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008224}
8225
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008226CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8227 if (isNotUsableTU(TU)) {
8228 LOG_BAD_TU(TU);
8229 return nullptr;
8230 }
8231 if (!File)
8232 return nullptr;
8233 FileEntry *FE = static_cast<FileEntry *>(File);
8234
8235 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8236 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8237 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8238
Richard Smithfeb54b62014-10-23 02:01:19 +00008239 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008240}
8241
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008242CXFile clang_Module_getASTFile(CXModule CXMod) {
8243 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008244 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008245 Module *Mod = static_cast<Module*>(CXMod);
8246 return const_cast<FileEntry *>(Mod->getASTFile());
8247}
8248
Guy Benyei11169dd2012-12-18 14:30:41 +00008249CXModule clang_Module_getParent(CXModule CXMod) {
8250 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008251 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008252 Module *Mod = static_cast<Module*>(CXMod);
8253 return Mod->Parent;
8254}
8255
8256CXString clang_Module_getName(CXModule CXMod) {
8257 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008258 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008259 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008260 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008261}
8262
8263CXString clang_Module_getFullName(CXModule CXMod) {
8264 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008265 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008266 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008267 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008268}
8269
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008270int clang_Module_isSystem(CXModule CXMod) {
8271 if (!CXMod)
8272 return 0;
8273 Module *Mod = static_cast<Module*>(CXMod);
8274 return Mod->IsSystem;
8275}
8276
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008277unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8278 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008279 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008280 LOG_BAD_TU(TU);
8281 return 0;
8282 }
8283 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008284 return 0;
8285 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008286 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8287 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8288 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008289}
8290
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008291CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8292 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008293 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008294 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008295 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008296 }
8297 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008298 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008300 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008301
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008302 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8303 if (Index < TopHeaders.size())
8304 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008305
Craig Topper69186e72014-06-08 08:38:04 +00008306 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008307}
8308
Guy Benyei11169dd2012-12-18 14:30:41 +00008309//===----------------------------------------------------------------------===//
8310// C++ AST instrospection.
8311//===----------------------------------------------------------------------===//
8312
Jonathan Coe29565352016-04-27 12:48:25 +00008313unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8314 if (!clang_isDeclaration(C.kind))
8315 return 0;
8316
8317 const Decl *D = cxcursor::getCursorDecl(C);
8318 const CXXConstructorDecl *Constructor =
8319 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8320 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8321}
8322
8323unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8324 if (!clang_isDeclaration(C.kind))
8325 return 0;
8326
8327 const Decl *D = cxcursor::getCursorDecl(C);
8328 const CXXConstructorDecl *Constructor =
8329 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8330 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8331}
8332
8333unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8334 if (!clang_isDeclaration(C.kind))
8335 return 0;
8336
8337 const Decl *D = cxcursor::getCursorDecl(C);
8338 const CXXConstructorDecl *Constructor =
8339 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8340 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8341}
8342
8343unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8344 if (!clang_isDeclaration(C.kind))
8345 return 0;
8346
8347 const Decl *D = cxcursor::getCursorDecl(C);
8348 const CXXConstructorDecl *Constructor =
8349 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8350 // Passing 'false' excludes constructors marked 'explicit'.
8351 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8352}
8353
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008354unsigned clang_CXXField_isMutable(CXCursor C) {
8355 if (!clang_isDeclaration(C.kind))
8356 return 0;
8357
8358 if (const auto D = cxcursor::getCursorDecl(C))
8359 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8360 return FD->isMutable() ? 1 : 0;
8361 return 0;
8362}
8363
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008364unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8365 if (!clang_isDeclaration(C.kind))
8366 return 0;
8367
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008368 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008369 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008370 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008371 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8372}
8373
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008374unsigned clang_CXXMethod_isConst(CXCursor C) {
8375 if (!clang_isDeclaration(C.kind))
8376 return 0;
8377
8378 const Decl *D = cxcursor::getCursorDecl(C);
8379 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008380 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008381 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008382}
8383
Jonathan Coe29565352016-04-27 12:48:25 +00008384unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8385 if (!clang_isDeclaration(C.kind))
8386 return 0;
8387
8388 const Decl *D = cxcursor::getCursorDecl(C);
8389 const CXXMethodDecl *Method =
8390 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8391 return (Method && Method->isDefaulted()) ? 1 : 0;
8392}
8393
Guy Benyei11169dd2012-12-18 14:30:41 +00008394unsigned clang_CXXMethod_isStatic(CXCursor C) {
8395 if (!clang_isDeclaration(C.kind))
8396 return 0;
8397
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008398 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008399 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008400 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008401 return (Method && Method->isStatic()) ? 1 : 0;
8402}
8403
8404unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8405 if (!clang_isDeclaration(C.kind))
8406 return 0;
8407
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008408 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008409 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008410 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008411 return (Method && Method->isVirtual()) ? 1 : 0;
8412}
Guy Benyei11169dd2012-12-18 14:30:41 +00008413
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008414unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8415 if (!clang_isDeclaration(C.kind))
8416 return 0;
8417
8418 const auto *D = cxcursor::getCursorDecl(C);
8419 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8420 if (RD)
8421 RD = RD->getDefinition();
8422 return (RD && RD->isAbstract()) ? 1 : 0;
8423}
8424
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008425unsigned clang_EnumDecl_isScoped(CXCursor C) {
8426 if (!clang_isDeclaration(C.kind))
8427 return 0;
8428
8429 const Decl *D = cxcursor::getCursorDecl(C);
8430 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8431 return (Enum && Enum->isScoped()) ? 1 : 0;
8432}
8433
Guy Benyei11169dd2012-12-18 14:30:41 +00008434//===----------------------------------------------------------------------===//
8435// Attribute introspection.
8436//===----------------------------------------------------------------------===//
8437
Guy Benyei11169dd2012-12-18 14:30:41 +00008438CXType clang_getIBOutletCollectionType(CXCursor C) {
8439 if (C.kind != CXCursor_IBOutletCollectionAttr)
8440 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8441
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008442 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008443 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8444
8445 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8446}
Guy Benyei11169dd2012-12-18 14:30:41 +00008447
8448//===----------------------------------------------------------------------===//
8449// Inspecting memory usage.
8450//===----------------------------------------------------------------------===//
8451
8452typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8453
8454static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8455 enum CXTUResourceUsageKind k,
8456 unsigned long amount) {
8457 CXTUResourceUsageEntry entry = { k, amount };
8458 entries.push_back(entry);
8459}
8460
Guy Benyei11169dd2012-12-18 14:30:41 +00008461const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8462 const char *str = "";
8463 switch (kind) {
8464 case CXTUResourceUsage_AST:
8465 str = "ASTContext: expressions, declarations, and types";
8466 break;
8467 case CXTUResourceUsage_Identifiers:
8468 str = "ASTContext: identifiers";
8469 break;
8470 case CXTUResourceUsage_Selectors:
8471 str = "ASTContext: selectors";
8472 break;
8473 case CXTUResourceUsage_GlobalCompletionResults:
8474 str = "Code completion: cached global results";
8475 break;
8476 case CXTUResourceUsage_SourceManagerContentCache:
8477 str = "SourceManager: content cache allocator";
8478 break;
8479 case CXTUResourceUsage_AST_SideTables:
8480 str = "ASTContext: side tables";
8481 break;
8482 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8483 str = "SourceManager: malloc'ed memory buffers";
8484 break;
8485 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8486 str = "SourceManager: mmap'ed memory buffers";
8487 break;
8488 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8489 str = "ExternalASTSource: malloc'ed memory buffers";
8490 break;
8491 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8492 str = "ExternalASTSource: mmap'ed memory buffers";
8493 break;
8494 case CXTUResourceUsage_Preprocessor:
8495 str = "Preprocessor: malloc'ed memory";
8496 break;
8497 case CXTUResourceUsage_PreprocessingRecord:
8498 str = "Preprocessor: PreprocessingRecord";
8499 break;
8500 case CXTUResourceUsage_SourceManager_DataStructures:
8501 str = "SourceManager: data structures and tables";
8502 break;
8503 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8504 str = "Preprocessor: header search tables";
8505 break;
8506 }
8507 return str;
8508}
8509
8510CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008511 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008512 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008513 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008514 return usage;
8515 }
8516
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008517 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008518 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008519 ASTContext &astContext = astUnit->getASTContext();
8520
8521 // How much memory is used by AST nodes and types?
8522 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8523 (unsigned long) astContext.getASTAllocatedMemory());
8524
8525 // How much memory is used by identifiers?
8526 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8527 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8528
8529 // How much memory is used for selectors?
8530 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8531 (unsigned long) astContext.Selectors.getTotalMemory());
8532
8533 // How much memory is used by ASTContext's side tables?
8534 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8535 (unsigned long) astContext.getSideTableAllocatedMemory());
8536
8537 // How much memory is used for caching global code completion results?
8538 unsigned long completionBytes = 0;
8539 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008540 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008541 completionBytes = completionAllocator->getTotalMemory();
8542 }
8543 createCXTUResourceUsageEntry(*entries,
8544 CXTUResourceUsage_GlobalCompletionResults,
8545 completionBytes);
8546
8547 // How much memory is being used by SourceManager's content cache?
8548 createCXTUResourceUsageEntry(*entries,
8549 CXTUResourceUsage_SourceManagerContentCache,
8550 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8551
8552 // How much memory is being used by the MemoryBuffer's in SourceManager?
8553 const SourceManager::MemoryBufferSizes &srcBufs =
8554 astUnit->getSourceManager().getMemoryBufferSizes();
8555
8556 createCXTUResourceUsageEntry(*entries,
8557 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8558 (unsigned long) srcBufs.malloc_bytes);
8559 createCXTUResourceUsageEntry(*entries,
8560 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8561 (unsigned long) srcBufs.mmap_bytes);
8562 createCXTUResourceUsageEntry(*entries,
8563 CXTUResourceUsage_SourceManager_DataStructures,
8564 (unsigned long) astContext.getSourceManager()
8565 .getDataStructureSizes());
8566
8567 // How much memory is being used by the ExternalASTSource?
8568 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8569 const ExternalASTSource::MemoryBufferSizes &sizes =
8570 esrc->getMemoryBufferSizes();
8571
8572 createCXTUResourceUsageEntry(*entries,
8573 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8574 (unsigned long) sizes.malloc_bytes);
8575 createCXTUResourceUsageEntry(*entries,
8576 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8577 (unsigned long) sizes.mmap_bytes);
8578 }
8579
8580 // How much memory is being used by the Preprocessor?
8581 Preprocessor &pp = astUnit->getPreprocessor();
8582 createCXTUResourceUsageEntry(*entries,
8583 CXTUResourceUsage_Preprocessor,
8584 pp.getTotalMemory());
8585
8586 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8587 createCXTUResourceUsageEntry(*entries,
8588 CXTUResourceUsage_PreprocessingRecord,
8589 pRec->getTotalMemory());
8590 }
8591
8592 createCXTUResourceUsageEntry(*entries,
8593 CXTUResourceUsage_Preprocessor_HeaderSearch,
8594 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008595
Guy Benyei11169dd2012-12-18 14:30:41 +00008596 CXTUResourceUsage usage = { (void*) entries.get(),
8597 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008598 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008599 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008600 return usage;
8601}
8602
8603void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8604 if (usage.data)
8605 delete (MemUsageEntries*) usage.data;
8606}
8607
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008608CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8609 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008610 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008611 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008612
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008613 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008614 LOG_BAD_TU(TU);
8615 return skipped;
8616 }
8617
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008618 if (!file)
8619 return skipped;
8620
8621 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8622 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8623 if (!ppRec)
8624 return skipped;
8625
8626 ASTContext &Ctx = astUnit->getASTContext();
8627 SourceManager &sm = Ctx.getSourceManager();
8628 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8629 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008630 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008631
8632 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8633 std::vector<SourceRange> wantedRanges;
8634 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8635 i != ei; ++i) {
8636 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8637 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008638 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8639 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008640 }
8641
8642 skipped->count = wantedRanges.size();
8643 skipped->ranges = new CXSourceRange[skipped->count];
8644 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8645 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8646
8647 return skipped;
8648}
8649
Cameron Desrochersd8091282016-08-18 15:43:55 +00008650CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8651 CXSourceRangeList *skipped = new CXSourceRangeList;
8652 skipped->count = 0;
8653 skipped->ranges = nullptr;
8654
8655 if (isNotUsableTU(TU)) {
8656 LOG_BAD_TU(TU);
8657 return skipped;
8658 }
8659
8660 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8661 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8662 if (!ppRec)
8663 return skipped;
8664
8665 ASTContext &Ctx = astUnit->getASTContext();
8666
8667 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8668
8669 skipped->count = SkippedRanges.size();
8670 skipped->ranges = new CXSourceRange[skipped->count];
8671 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8672 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8673
8674 return skipped;
8675}
8676
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008677void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8678 if (ranges) {
8679 delete[] ranges->ranges;
8680 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008681 }
8682}
8683
Guy Benyei11169dd2012-12-18 14:30:41 +00008684void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8685 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8686 for (unsigned I = 0; I != Usage.numEntries; ++I)
8687 fprintf(stderr, " %s: %lu\n",
8688 clang_getTUResourceUsageName(Usage.entries[I].kind),
8689 Usage.entries[I].amount);
8690
8691 clang_disposeCXTUResourceUsage(Usage);
8692}
8693
8694//===----------------------------------------------------------------------===//
8695// Misc. utility functions.
8696//===----------------------------------------------------------------------===//
8697
Richard Smith0a7b2972018-07-03 21:34:13 +00008698/// Default to using our desired 8 MB stack size on "safety" threads.
8699static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008700
8701namespace clang {
8702
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008703bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008704 unsigned Size) {
8705 if (!Size)
8706 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008707 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008708 return CRC.RunSafelyOnThread(Fn, Size);
8709 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008710}
8711
8712unsigned GetSafetyThreadStackSize() {
8713 return SafetyStackThreadSize;
8714}
8715
8716void SetSafetyThreadStackSize(unsigned Value) {
8717 SafetyStackThreadSize = Value;
8718}
8719
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008720}
Guy Benyei11169dd2012-12-18 14:30:41 +00008721
8722void clang::setThreadBackgroundPriority() {
8723 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8724 return;
8725
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008726 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Guy Benyei11169dd2012-12-18 14:30:41 +00008727}
8728
8729void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8730 if (!Unit)
8731 return;
8732
8733 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8734 DEnd = Unit->stored_diag_end();
8735 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008736 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008737 CXString Msg = clang_formatDiagnostic(&Diag,
8738 clang_defaultDiagnosticDisplayOptions());
8739 fprintf(stderr, "%s\n", clang_getCString(Msg));
8740 clang_disposeString(Msg);
8741 }
Nico Weber1865df42018-04-27 19:11:14 +00008742#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008743 // On Windows, force a flush, since there may be multiple copies of
8744 // stderr and stdout in the file system, all with different buffers
8745 // but writing to the same device.
8746 fflush(stderr);
8747#endif
8748}
8749
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008750MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8751 SourceLocation MacroDefLoc,
8752 CXTranslationUnit TU){
8753 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008754 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008755 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008756 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008757
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008758 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008759 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008760 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008761 if (MD) {
8762 for (MacroDirective::DefInfo
8763 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8764 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8765 return Def.getMacroInfo();
8766 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008767 }
8768
Craig Topper69186e72014-06-08 08:38:04 +00008769 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008770}
8771
Richard Smith66a81862015-05-04 02:25:31 +00008772const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008773 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008774 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008775 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008776 const IdentifierInfo *II = MacroDef->getName();
8777 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008778 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008779
8780 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8781}
8782
Richard Smith66a81862015-05-04 02:25:31 +00008783MacroDefinitionRecord *
8784cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8785 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008786 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008787 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008788 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008789 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008790
8791 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008792 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008793 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8794 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008795 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008796
8797 // Check that the token is inside the definition and not its argument list.
8798 SourceManager &SM = Unit->getSourceManager();
8799 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008800 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008801 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008802 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008803
8804 Preprocessor &PP = Unit->getPreprocessor();
8805 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8806 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008807 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008808
Alp Toker2d57cea2014-05-17 04:53:25 +00008809 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008810 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008811 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008812
8813 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008814 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008815 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008816
Richard Smith20e883e2015-04-29 23:20:19 +00008817 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008818 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008819 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008820
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008821 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008822}
8823
Richard Smith66a81862015-05-04 02:25:31 +00008824MacroDefinitionRecord *
8825cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8826 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008827 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008828 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008829
8830 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008831 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008832 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008833 Preprocessor &PP = Unit->getPreprocessor();
8834 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008835 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008836 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8837 Token Tok;
8838 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008839 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008840
8841 return checkForMacroInMacroDefinition(MI, Tok, TU);
8842}
8843
Guy Benyei11169dd2012-12-18 14:30:41 +00008844CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008845 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008846}
8847
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008848Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8849 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008850 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008851 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008852 if (Unit->isMainFileAST())
8853 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008854 return *this;
8855 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008856 } else {
8857 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008858 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008859 return *this;
8860}
8861
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008862Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8863 *this << FE->getName();
8864 return *this;
8865}
8866
8867Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8868 CXString cursorName = clang_getCursorDisplayName(cursor);
8869 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8870 clang_disposeString(cursorName);
8871 return *this;
8872}
8873
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008874Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8875 CXFile File;
8876 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008877 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008878 CXString FileName = clang_getFileName(File);
8879 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8880 clang_disposeString(FileName);
8881 return *this;
8882}
8883
8884Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8885 CXSourceLocation BLoc = clang_getRangeStart(range);
8886 CXSourceLocation ELoc = clang_getRangeEnd(range);
8887
8888 CXFile BFile;
8889 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008890 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008891
8892 CXFile EFile;
8893 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008894 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008895
8896 CXString BFileName = clang_getFileName(BFile);
8897 if (BFile == EFile) {
8898 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8899 BLine, BColumn, ELine, EColumn);
8900 } else {
8901 CXString EFileName = clang_getFileName(EFile);
8902 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8903 BLine, BColumn)
8904 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8905 ELine, EColumn);
8906 clang_disposeString(EFileName);
8907 }
8908 clang_disposeString(BFileName);
8909 return *this;
8910}
8911
8912Logger &cxindex::Logger::operator<<(CXString Str) {
8913 *this << clang_getCString(Str);
8914 return *this;
8915}
8916
8917Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8918 LogOS << Fmt;
8919 return *this;
8920}
8921
Chandler Carruth37ad2582014-06-27 15:14:39 +00008922static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8923
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008924cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008925 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008926
8927 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8928
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008929 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008930 OS << "[libclang:" << Name << ':';
8931
Alp Toker1a86ad22014-07-06 06:24:00 +00008932#ifdef USE_DARWIN_THREADS
8933 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008934 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8935 OS << tid << ':';
8936#endif
8937
8938 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8939 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008940 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008941
8942 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008943 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008944 OS << "--------------------------------------------------\n";
8945 }
8946}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00008947
8948#ifdef CLANG_TOOL_EXTRA_BUILD
8949// This anchor is used to force the linker to link the clang-tidy plugin.
8950extern volatile int ClangTidyPluginAnchorSource;
8951static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8952 ClangTidyPluginAnchorSource;
8953
8954// This anchor is used to force the linker to link the clang-include-fixer
8955// plugin.
8956extern volatile int ClangIncludeFixerPluginAnchorSource;
8957static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8958 ClangIncludeFixerPluginAnchorSource;
8959#endif