blob: 5ea2d5e4a8cdf495b33cbd34fbefa83172dcff90 [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"
Jan Korous7e36ecd2019-09-05 20:33:52 +000024#include "clang/AST/Mangle.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000029#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000030#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000031#include "clang/Basic/Version.h"
32#include "clang/Frontend/ASTUnit.h"
33#include "clang/Frontend/CompilerInstance.h"
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"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/Program.h"
49#include "llvm/Support/SaveAndRestore.h"
50#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000051#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000052#include "llvm/Support/Threading.h"
53#include "llvm/Support/Timer.h"
54#include "llvm/Support/raw_ostream.h"
Benjamin Kramer762bc332019-08-07 14:44:40 +000055#include <mutex>
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
Guy Benyei11169dd2012-12-18 14:30:41 +0000174RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
175 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
176}
177
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000178/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000179/// its children.
180///
181/// \param Cursor the cursor to visit.
182///
183/// \param CheckedRegionOfInterest if true, then the caller already checked
184/// that this cursor is within the region of interest.
185///
186/// \returns true if the visitation should be aborted, false if it
187/// should continue.
188bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
189 if (clang_isInvalid(Cursor.kind))
190 return false;
191
192 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000193 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000194 if (!D) {
195 assert(0 && "Invalid declaration cursor");
196 return true; // abort.
197 }
198
199 // Ignore implicit declarations, unless it's an objc method because
200 // currently we should report implicit methods for properties when indexing.
201 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
202 return false;
203 }
204
205 // If we have a range of interest, and this cursor doesn't intersect with it,
206 // we're done.
207 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
208 SourceRange Range = getRawCursorExtent(Cursor);
209 if (Range.isInvalid() || CompareRegionOfInterest(Range))
210 return false;
211 }
212
213 switch (Visitor(Cursor, Parent, ClientData)) {
214 case CXChildVisit_Break:
215 return true;
216
217 case CXChildVisit_Continue:
218 return false;
219
220 case CXChildVisit_Recurse: {
221 bool ret = VisitChildren(Cursor);
222 if (PostChildrenVisitor)
223 if (PostChildrenVisitor(Cursor, ClientData))
224 return true;
225 return ret;
226 }
227 }
228
229 llvm_unreachable("Invalid CXChildVisitResult!");
230}
231
232static bool visitPreprocessedEntitiesInRange(SourceRange R,
233 PreprocessingRecord &PPRec,
234 CursorVisitor &Visitor) {
235 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
236 FileID FID;
237
238 if (!Visitor.shouldVisitIncludedEntities()) {
239 // If the begin/end of the range lie in the same FileID, do the optimization
240 // where we skip preprocessed entities that do not come from the same FileID.
241 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
242 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
243 FID = FileID();
244 }
245
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000246 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
247 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000248 PPRec, FID);
249}
250
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000251bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000252 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000253 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000254
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000255 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000256 SourceManager &SM = Unit->getSourceManager();
257
258 std::pair<FileID, unsigned>
259 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
260 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
261
262 if (End.first != Begin.first) {
263 // If the end does not reside in the same file, try to recover by
264 // picking the end of the file of begin location.
265 End.first = Begin.first;
266 End.second = SM.getFileIDSize(Begin.first);
267 }
268
269 assert(Begin.first == End.first);
270 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000271 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000272
273 FileID File = Begin.first;
274 unsigned Offset = Begin.second;
275 unsigned Length = End.second - Begin.second;
276
277 if (!VisitDeclsOnly && !VisitPreprocessorLast)
278 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000279 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000280
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000281 if (visitDeclsFromFileRegion(File, Offset, Length))
282 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000283
284 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000285 return visitPreprocessedEntitiesInRegion();
286
287 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000288}
289
290static bool isInLexicalContext(Decl *D, DeclContext *DC) {
291 if (!DC)
292 return false;
293
294 for (DeclContext *DeclDC = D->getLexicalDeclContext();
295 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
296 if (DeclDC == DC)
297 return true;
298 }
299 return false;
300}
301
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000302bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000303 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000304 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000305 SourceManager &SM = Unit->getSourceManager();
306 SourceRange Range = RegionOfInterest;
307
308 SmallVector<Decl *, 16> Decls;
309 Unit->findFileRegionDecls(File, Offset, Length, Decls);
310
311 // If we didn't find any file level decls for the file, try looking at the
312 // file that it was included from.
313 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
314 bool Invalid = false;
315 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
316 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000317 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000318
319 SourceLocation Outer;
320 if (SLEntry.isFile())
321 Outer = SLEntry.getFile().getIncludeLoc();
322 else
323 Outer = SLEntry.getExpansion().getExpansionLocStart();
324 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000325 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000326
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000327 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000328 Length = 0;
329 Unit->findFileRegionDecls(File, Offset, Length, Decls);
330 }
331
332 assert(!Decls.empty());
333
334 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000335 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000336 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
337 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000338 Decl *D = *DIt;
339 if (D->getSourceRange().isInvalid())
340 continue;
341
342 if (isInLexicalContext(D, CurDC))
343 continue;
344
345 CurDC = dyn_cast<DeclContext>(D);
346
347 if (TagDecl *TD = dyn_cast<TagDecl>(D))
348 if (!TD->isFreeStanding())
349 continue;
350
351 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
352 if (CompRes == RangeBefore)
353 continue;
354 if (CompRes == RangeAfter)
355 break;
356
357 assert(CompRes == RangeOverlap);
358 VisitedAtLeastOnce = true;
359
360 if (isa<ObjCContainerDecl>(D)) {
361 FileDI_current = &DIt;
362 FileDE_current = DE;
363 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000364 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000365 }
366
367 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000368 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000369 }
370
371 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000372 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000373
374 // No Decls overlapped with the range. Move up the lexical context until there
375 // is a context that contains the range or we reach the translation unit
376 // level.
377 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
378 : (*(DIt-1))->getLexicalDeclContext();
379
380 while (DC && !DC->isTranslationUnit()) {
381 Decl *D = cast<Decl>(DC);
382 SourceRange CurDeclRange = D->getSourceRange();
383 if (CurDeclRange.isInvalid())
384 break;
385
386 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000387 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
388 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000389 }
390
391 DC = D->getLexicalDeclContext();
392 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000393
394 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000395}
396
397bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
398 if (!AU->getPreprocessor().getPreprocessingRecord())
399 return false;
400
401 PreprocessingRecord &PPRec
402 = *AU->getPreprocessor().getPreprocessingRecord();
403 SourceManager &SM = AU->getSourceManager();
404
405 if (RegionOfInterest.isValid()) {
406 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
407 SourceLocation B = MappedRange.getBegin();
408 SourceLocation E = MappedRange.getEnd();
409
410 if (AU->isInPreambleFileID(B)) {
411 if (SM.isLoadedSourceLocation(E))
412 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
413 PPRec, *this);
414
415 // Beginning of range lies in the preamble but it also extends beyond
416 // it into the main file. Split the range into 2 parts, one covering
417 // the preamble and another covering the main file. This allows subsequent
418 // calls to visitPreprocessedEntitiesInRange to accept a source range that
419 // lies in the same FileID, allowing it to skip preprocessed entities that
420 // do not come from the same FileID.
421 bool breaked =
422 visitPreprocessedEntitiesInRange(
423 SourceRange(B, AU->getEndOfPreambleFileID()),
424 PPRec, *this);
425 if (breaked) return true;
426 return visitPreprocessedEntitiesInRange(
427 SourceRange(AU->getStartOfMainFileID(), E),
428 PPRec, *this);
429 }
430
431 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
432 }
433
434 bool OnlyLocalDecls
435 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
436
437 if (OnlyLocalDecls)
438 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
439 PPRec);
440
441 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
442}
443
444template<typename InputIterator>
445bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
446 InputIterator Last,
447 PreprocessingRecord &PPRec,
448 FileID FID) {
449 for (; First != Last; ++First) {
450 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
451 continue;
452
453 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000454 if (!PPE)
455 continue;
456
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
458 if (Visit(MakeMacroExpansionCursor(ME, TU)))
459 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000460
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 continue;
462 }
Richard Smith66a81862015-05-04 02:25:31 +0000463
464 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000465 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
466 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000467
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 continue;
469 }
470
471 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
472 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
473 return true;
474
475 continue;
476 }
477 }
478
479 return false;
480}
481
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000482/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000483///
484/// \returns true if the visitation should be aborted, false if it
485/// should continue.
486bool CursorVisitor::VisitChildren(CXCursor Cursor) {
487 if (clang_isReference(Cursor.kind) &&
488 Cursor.kind != CXCursor_CXXBaseSpecifier) {
489 // By definition, references have no children.
490 return false;
491 }
492
493 // Set the Parent field to Cursor, then back to its old value once we're
494 // done.
495 SetParentRAII SetParent(Parent, StmtParent, Cursor);
496
497 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000498 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000499 if (!D)
500 return false;
501
502 return VisitAttributes(D) || Visit(D);
503 }
504
505 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000506 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000507 return Visit(S);
508
509 return false;
510 }
511
512 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000513 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000514 return Visit(E);
515
516 return false;
517 }
518
519 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000520 CXTranslationUnit TU = getCursorTU(Cursor);
521 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000522
523 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
524 for (unsigned I = 0; I != 2; ++I) {
525 if (VisitOrder[I]) {
526 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
527 RegionOfInterest.isInvalid()) {
528 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
529 TLEnd = CXXUnit->top_level_end();
530 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000531 const Optional<bool> V = handleDeclForVisitation(*TL);
532 if (!V.hasValue())
533 continue;
534 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000535 }
536 } else if (VisitDeclContext(
537 CXXUnit->getASTContext().getTranslationUnitDecl()))
538 return true;
539 continue;
540 }
541
542 // Walk the preprocessing record.
543 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
544 visitPreprocessedEntitiesInRegion();
545 }
546
547 return false;
548 }
549
550 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000551 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000552 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
553 return Visit(BaseTSInfo->getTypeLoc());
554 }
555 }
556 }
557
558 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000559 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000560 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000561 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000562 return Visit(cxcursor::MakeCursorObjCClassRef(
563 ObjT->getInterface(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000564 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000565 }
566
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000567 // If pointing inside a macro definition, check if the token is an identifier
568 // that was ever defined as a macro. In such a case, create a "pseudo" macro
569 // expansion cursor for that token.
570 SourceLocation BeginLoc = RegionOfInterest.getBegin();
571 if (Cursor.kind == CXCursor_MacroDefinition &&
572 BeginLoc == RegionOfInterest.getEnd()) {
573 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000574 const MacroInfo *MI =
575 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000576 if (MacroDefinitionRecord *MacroDef =
577 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000578 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
579 }
580
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 // Nothing to visit at the moment.
582 return false;
583}
584
585bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
586 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
587 if (Visit(TSInfo->getTypeLoc()))
588 return true;
589
590 if (Stmt *Body = B->getBody())
591 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
592
593 return false;
594}
595
Ted Kremenek03325582013-02-21 01:29:01 +0000596Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000597 if (RegionOfInterest.isValid()) {
598 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
599 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000600 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000601
602 switch (CompareRegionOfInterest(Range)) {
603 case RangeBefore:
604 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000605 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000606
607 case RangeAfter:
608 // This declaration comes after the region of interest; we're done.
609 return false;
610
611 case RangeOverlap:
612 // This declaration overlaps the region of interest; visit it.
613 break;
614 }
615 }
616 return true;
617}
618
619bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
620 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
621
622 // FIXME: Eventually remove. This part of a hack to support proper
623 // iteration over all Decls contained lexically within an ObjC container.
624 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
625 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
626
627 for ( ; I != E; ++I) {
628 Decl *D = *I;
629 if (D->getLexicalDeclContext() != DC)
630 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000631 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000632 if (!V.hasValue())
633 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000634 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000635 }
636 return false;
637}
638
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000639Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
640 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
641
642 // Ignore synthesized ivars here, otherwise if we have something like:
643 // @synthesize prop = _prop;
644 // and '_prop' is not declared, we will encounter a '_prop' ivar before
645 // encountering the 'prop' synthesize declaration and we will think that
646 // we passed the region-of-interest.
647 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
648 if (ivarD->getSynthesize())
649 return None;
650 }
651
652 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
653 // declarations is a mismatch with the compiler semantics.
654 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
655 auto *ID = cast<ObjCInterfaceDecl>(D);
656 if (!ID->isThisDeclarationADefinition())
657 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
658
659 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
660 auto *PD = cast<ObjCProtocolDecl>(D);
661 if (!PD->isThisDeclarationADefinition())
662 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
663 }
664
665 const Optional<bool> V = shouldVisitCursor(Cursor);
666 if (!V.hasValue())
667 return None;
668 if (!V.getValue())
669 return false;
670 if (Visit(Cursor, true))
671 return true;
672 return None;
673}
674
Guy Benyei11169dd2012-12-18 14:30:41 +0000675bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
676 llvm_unreachable("Translation units are visited directly by Visit()");
677}
678
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000679bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
680 if (VisitTemplateParameters(D->getTemplateParameters()))
681 return true;
682
683 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
684}
685
Guy Benyei11169dd2012-12-18 14:30:41 +0000686bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
687 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
688 return Visit(TSInfo->getTypeLoc());
689
690 return false;
691}
692
693bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
694 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
695 return Visit(TSInfo->getTypeLoc());
696
697 return false;
698}
699
700bool CursorVisitor::VisitTagDecl(TagDecl *D) {
701 return VisitDeclContext(D);
702}
703
704bool CursorVisitor::VisitClassTemplateSpecializationDecl(
705 ClassTemplateSpecializationDecl *D) {
706 bool ShouldVisitBody = false;
707 switch (D->getSpecializationKind()) {
708 case TSK_Undeclared:
709 case TSK_ImplicitInstantiation:
710 // Nothing to visit
711 return false;
712
713 case TSK_ExplicitInstantiationDeclaration:
714 case TSK_ExplicitInstantiationDefinition:
715 break;
716
717 case TSK_ExplicitSpecialization:
718 ShouldVisitBody = true;
719 break;
720 }
721
722 // Visit the template arguments used in the specialization.
723 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
724 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000725 if (TemplateSpecializationTypeLoc TSTLoc =
726 TL.getAs<TemplateSpecializationTypeLoc>()) {
727 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
728 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000729 return true;
730 }
731 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000732
733 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000734}
735
736bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
737 ClassTemplatePartialSpecializationDecl *D) {
738 // FIXME: Visit the "outer" template parameter lists on the TagDecl
739 // before visiting these template parameters.
740 if (VisitTemplateParameters(D->getTemplateParameters()))
741 return true;
742
743 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000744 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
745 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
746 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
748 return true;
749
750 return VisitCXXRecordDecl(D);
751}
752
753bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
754 // Visit the default argument.
755 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
756 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
757 if (Visit(DefArg->getTypeLoc()))
758 return true;
759
760 return false;
761}
762
763bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
764 if (Expr *Init = D->getInitExpr())
765 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
766 return false;
767}
768
769bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000770 unsigned NumParamList = DD->getNumTemplateParameterLists();
771 for (unsigned i = 0; i < NumParamList; i++) {
772 TemplateParameterList* Params = DD->getTemplateParameterList(i);
773 if (VisitTemplateParameters(Params))
774 return true;
775 }
776
Guy Benyei11169dd2012-12-18 14:30:41 +0000777 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
778 if (Visit(TSInfo->getTypeLoc()))
779 return true;
780
781 // Visit the nested-name-specifier, if present.
782 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
783 if (VisitNestedNameSpecifierLoc(QualifierLoc))
784 return true;
785
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000786 return false;
787}
788
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000789static bool HasTrailingReturnType(FunctionDecl *ND) {
790 const QualType Ty = ND->getType();
791 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
792 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
793 return FT->hasTrailingReturn();
794 }
795
796 return false;
797}
798
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000799/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000800static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
801 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000802 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
803}
804
Guy Benyei11169dd2012-12-18 14:30:41 +0000805bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000806 unsigned NumParamList = ND->getNumTemplateParameterLists();
807 for (unsigned i = 0; i < NumParamList; i++) {
808 TemplateParameterList* Params = ND->getTemplateParameterList(i);
809 if (VisitTemplateParameters(Params))
810 return true;
811 }
812
Guy Benyei11169dd2012-12-18 14:30:41 +0000813 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
814 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000815 // written. This requires a bit of work.
816 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
817 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000818 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000819
820 // If we have a function declared directly (without the use of a typedef),
821 // visit just the return type. Otherwise, just visit the function's type
822 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000823 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
824 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000825 (!FTL && Visit(TL)))
826 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000827
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000828 // Visit the nested-name-specifier, if present.
829 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
830 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000831 return true;
832
833 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000834 if (!isa<CXXDestructorDecl>(ND))
835 if (VisitDeclarationNameInfo(ND->getNameInfo()))
836 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000837
838 // FIXME: Visit explicitly-specified template arguments!
839
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000840 // Visit the function parameters, if we have a function type.
841 if (FTL && VisitFunctionTypeLoc(FTL, true))
842 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000843
844 // Visit the function's trailing return type.
845 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
846 return true;
847
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000848 // FIXME: Attributes?
849 }
850
Guy Benyei11169dd2012-12-18 14:30:41 +0000851 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
852 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
853 // Find the initializers that were written in the source.
854 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000855 for (auto *I : Constructor->inits()) {
856 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000857 continue;
858
Aaron Ballman0ad78302014-03-13 17:34:31 +0000859 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000860 }
861
862 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000863 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
864 &CompareCXXCtorInitializers);
865
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 // Visit the initializers in source order
867 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
868 CXXCtorInitializer *Init = WrittenInits[I];
869 if (Init->isAnyMemberInitializer()) {
870 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
871 Init->getMemberLocation(), TU)))
872 return true;
873 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
874 if (Visit(TInfo->getTypeLoc()))
875 return true;
876 }
877
878 // Visit the initializer value.
879 if (Expr *Initializer = Init->getInit())
880 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
881 return true;
882 }
883 }
884
885 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
886 return true;
887 }
888
889 return false;
890}
891
892bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
893 if (VisitDeclaratorDecl(D))
894 return true;
895
896 if (Expr *BitWidth = D->getBitWidth())
897 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
898
Benjamin Kramer99f97592017-11-15 12:20:41 +0000899 if (Expr *Init = D->getInClassInitializer())
900 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
901
Guy Benyei11169dd2012-12-18 14:30:41 +0000902 return false;
903}
904
905bool CursorVisitor::VisitVarDecl(VarDecl *D) {
906 if (VisitDeclaratorDecl(D))
907 return true;
908
909 if (Expr *Init = D->getInit())
910 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
911
912 return false;
913}
914
915bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
916 if (VisitDeclaratorDecl(D))
917 return true;
918
919 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
920 if (Expr *DefArg = D->getDefaultArgument())
921 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
922
923 return false;
924}
925
926bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
927 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
928 // before visiting these template parameters.
929 if (VisitTemplateParameters(D->getTemplateParameters()))
930 return true;
931
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000932 auto* FD = D->getTemplatedDecl();
933 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000934}
935
936bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
937 // FIXME: Visit the "outer" template parameter lists on the TagDecl
938 // before visiting these template parameters.
939 if (VisitTemplateParameters(D->getTemplateParameters()))
940 return true;
941
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000942 auto* CD = D->getTemplatedDecl();
943 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000944}
945
946bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
947 if (VisitTemplateParameters(D->getTemplateParameters()))
948 return true;
949
950 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
951 VisitTemplateArgumentLoc(D->getDefaultArgument()))
952 return true;
953
954 return false;
955}
956
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000957bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
958 // Visit the bound, if it's explicit.
959 if (D->hasExplicitBound()) {
960 if (auto TInfo = D->getTypeSourceInfo()) {
961 if (Visit(TInfo->getTypeLoc()))
962 return true;
963 }
964 }
965
966 return false;
967}
968
Guy Benyei11169dd2012-12-18 14:30:41 +0000969bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000970 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 if (Visit(TSInfo->getTypeLoc()))
972 return true;
973
David Majnemer59f77922016-06-24 04:05:48 +0000974 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000975 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 return true;
977 }
978
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000979 return ND->isThisDeclarationADefinition() &&
980 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000981}
982
983template <typename DeclIt>
984static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
985 SourceManager &SM, SourceLocation EndLoc,
986 SmallVectorImpl<Decl *> &Decls) {
987 DeclIt next = *DI_current;
988 while (++next != DE_current) {
989 Decl *D_next = *next;
990 if (!D_next)
991 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000992 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 if (!L.isValid())
994 break;
995 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
996 *DI_current = next;
997 Decls.push_back(D_next);
998 continue;
999 }
1000 break;
1001 }
1002}
1003
Guy Benyei11169dd2012-12-18 14:30:41 +00001004bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1005 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1006 // an @implementation can lexically contain Decls that are not properly
1007 // nested in the AST. When we identify such cases, we need to retrofit
1008 // this nesting here.
1009 if (!DI_current && !FileDI_current)
1010 return VisitDeclContext(D);
1011
1012 // Scan the Decls that immediately come after the container
1013 // in the current DeclContext. If any fall within the
1014 // container's lexical region, stash them into a vector
1015 // for later processing.
1016 SmallVector<Decl *, 24> DeclsInContainer;
1017 SourceLocation EndLoc = D->getSourceRange().getEnd();
1018 SourceManager &SM = AU->getSourceManager();
1019 if (EndLoc.isValid()) {
1020 if (DI_current) {
1021 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1022 DeclsInContainer);
1023 } else {
1024 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1025 DeclsInContainer);
1026 }
1027 }
1028
1029 // The common case.
1030 if (DeclsInContainer.empty())
1031 return VisitDeclContext(D);
1032
1033 // Get all the Decls in the DeclContext, and sort them with the
1034 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001035 for (auto *SubDecl : D->decls()) {
1036 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001037 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001038 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001039 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001040 }
1041
1042 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001043 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001044 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001045 SourceLocation L_A = A->getBeginLoc();
1046 SourceLocation L_B = B->getBeginLoc();
1047 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001048 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1049 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001050 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001051
1052 // Now visit the decls.
1053 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1054 E = DeclsInContainer.end(); I != E; ++I) {
1055 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001056 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001057 if (!V.hasValue())
1058 continue;
1059 if (!V.getValue())
1060 return false;
1061 if (Visit(Cursor, true))
1062 return true;
1063 }
1064 return false;
1065}
1066
1067bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1068 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1069 TU)))
1070 return true;
1071
Douglas Gregore9d95f12015-07-07 03:57:35 +00001072 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1073 return true;
1074
Guy Benyei11169dd2012-12-18 14:30:41 +00001075 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1076 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1077 E = ND->protocol_end(); I != E; ++I, ++PL)
1078 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1079 return true;
1080
1081 return VisitObjCContainerDecl(ND);
1082}
1083
1084bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1085 if (!PID->isThisDeclarationADefinition())
1086 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1087
1088 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1089 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1090 E = PID->protocol_end(); I != E; ++I, ++PL)
1091 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1092 return true;
1093
1094 return VisitObjCContainerDecl(PID);
1095}
1096
1097bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1098 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1099 return true;
1100
1101 // FIXME: This implements a workaround with @property declarations also being
1102 // installed in the DeclContext for the @interface. Eventually this code
1103 // should be removed.
1104 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1105 if (!CDecl || !CDecl->IsClassExtension())
1106 return false;
1107
1108 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1109 if (!ID)
1110 return false;
1111
1112 IdentifierInfo *PropertyId = PD->getIdentifier();
1113 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001114 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1115 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001116
1117 if (!prevDecl)
1118 return false;
1119
1120 // Visit synthesized methods since they will be skipped when visiting
1121 // the @interface.
1122 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1123 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1124 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1125 return true;
1126
1127 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1128 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1129 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1130 return true;
1131
1132 return false;
1133}
1134
Douglas Gregore9d95f12015-07-07 03:57:35 +00001135bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1136 if (!typeParamList)
1137 return false;
1138
1139 for (auto *typeParam : *typeParamList) {
1140 // Visit the type parameter.
1141 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1142 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001143 }
1144
1145 return false;
1146}
1147
Guy Benyei11169dd2012-12-18 14:30:41 +00001148bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1149 if (!D->isThisDeclarationADefinition()) {
1150 // Forward declaration is treated like a reference.
1151 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1152 }
1153
Douglas Gregore9d95f12015-07-07 03:57:35 +00001154 // Objective-C type parameters.
1155 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1156 return true;
1157
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 // Issue callbacks for super class.
1159 if (D->getSuperClass() &&
1160 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1161 D->getSuperClassLoc(),
1162 TU)))
1163 return true;
1164
Douglas Gregore9d95f12015-07-07 03:57:35 +00001165 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1166 if (Visit(SuperClassTInfo->getTypeLoc()))
1167 return true;
1168
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1170 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1171 E = D->protocol_end(); I != E; ++I, ++PL)
1172 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1173 return true;
1174
1175 return VisitObjCContainerDecl(D);
1176}
1177
1178bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1179 return VisitObjCContainerDecl(D);
1180}
1181
1182bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1183 // 'ID' could be null when dealing with invalid code.
1184 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1185 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1186 return true;
1187
1188 return VisitObjCImplDecl(D);
1189}
1190
1191bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1192#if 0
1193 // Issue callbacks for super class.
1194 // FIXME: No source location information!
1195 if (D->getSuperClass() &&
1196 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1197 D->getSuperClassLoc(),
1198 TU)))
1199 return true;
1200#endif
1201
1202 return VisitObjCImplDecl(D);
1203}
1204
1205bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1206 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1207 if (PD->isIvarNameSpecified())
1208 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1209
1210 return false;
1211}
1212
1213bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1214 return VisitDeclContext(D);
1215}
1216
1217bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1218 // Visit nested-name-specifier.
1219 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1220 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1221 return true;
1222
1223 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1224 D->getTargetNameLoc(), TU));
1225}
1226
1227bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1228 // Visit nested-name-specifier.
1229 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1230 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1231 return true;
1232 }
1233
1234 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1235 return true;
1236
1237 return VisitDeclarationNameInfo(D->getNameInfo());
1238}
1239
1240bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1241 // Visit nested-name-specifier.
1242 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1243 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1244 return true;
1245
1246 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1247 D->getIdentLocation(), TU));
1248}
1249
1250bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1251 // Visit nested-name-specifier.
1252 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1253 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1254 return true;
1255 }
1256
1257 return VisitDeclarationNameInfo(D->getNameInfo());
1258}
1259
1260bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1261 UnresolvedUsingTypenameDecl *D) {
1262 // Visit nested-name-specifier.
1263 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1264 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1265 return true;
1266
1267 return false;
1268}
1269
Olivier Goffart81978012016-06-09 16:15:55 +00001270bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1271 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1272 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001273 if (StringLiteral *Message = D->getMessage())
1274 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1275 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001276 return false;
1277}
1278
Olivier Goffartd211c642016-11-04 06:29:27 +00001279bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1280 if (NamedDecl *FriendD = D->getFriendDecl()) {
1281 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1282 return true;
1283 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1284 if (Visit(TI->getTypeLoc()))
1285 return true;
1286 }
1287 return false;
1288}
1289
Guy Benyei11169dd2012-12-18 14:30:41 +00001290bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1291 switch (Name.getName().getNameKind()) {
1292 case clang::DeclarationName::Identifier:
1293 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001294 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 case clang::DeclarationName::CXXOperatorName:
1296 case clang::DeclarationName::CXXUsingDirective:
1297 return false;
Richard Smith35845152017-02-07 01:37:30 +00001298
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 case clang::DeclarationName::CXXConstructorName:
1300 case clang::DeclarationName::CXXDestructorName:
1301 case clang::DeclarationName::CXXConversionFunctionName:
1302 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1303 return Visit(TSInfo->getTypeLoc());
1304 return false;
1305
1306 case clang::DeclarationName::ObjCZeroArgSelector:
1307 case clang::DeclarationName::ObjCOneArgSelector:
1308 case clang::DeclarationName::ObjCMultiArgSelector:
1309 // FIXME: Per-identifier location info?
1310 return false;
1311 }
1312
1313 llvm_unreachable("Invalid DeclarationName::Kind!");
1314}
1315
1316bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1317 SourceRange Range) {
1318 // FIXME: This whole routine is a hack to work around the lack of proper
1319 // source information in nested-name-specifiers (PR5791). Since we do have
1320 // a beginning source location, we can visit the first component of the
1321 // nested-name-specifier, if it's a single-token component.
1322 if (!NNS)
1323 return false;
1324
1325 // Get the first component in the nested-name-specifier.
1326 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1327 NNS = Prefix;
1328
1329 switch (NNS->getKind()) {
1330 case NestedNameSpecifier::Namespace:
1331 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1332 TU));
1333
1334 case NestedNameSpecifier::NamespaceAlias:
1335 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1336 Range.getBegin(), TU));
1337
1338 case NestedNameSpecifier::TypeSpec: {
1339 // If the type has a form where we know that the beginning of the source
1340 // range matches up with a reference cursor. Visit the appropriate reference
1341 // cursor.
1342 const Type *T = NNS->getAsType();
1343 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1344 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1345 if (const TagType *Tag = dyn_cast<TagType>(T))
1346 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1347 if (const TemplateSpecializationType *TST
1348 = dyn_cast<TemplateSpecializationType>(T))
1349 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1350 break;
1351 }
1352
1353 case NestedNameSpecifier::TypeSpecWithTemplate:
1354 case NestedNameSpecifier::Global:
1355 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001356 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001357 break;
1358 }
1359
1360 return false;
1361}
1362
1363bool
1364CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1365 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1366 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1367 Qualifiers.push_back(Qualifier);
1368
1369 while (!Qualifiers.empty()) {
1370 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1371 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1372 switch (NNS->getKind()) {
1373 case NestedNameSpecifier::Namespace:
1374 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1375 Q.getLocalBeginLoc(),
1376 TU)))
1377 return true;
1378
1379 break;
1380
1381 case NestedNameSpecifier::NamespaceAlias:
1382 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1383 Q.getLocalBeginLoc(),
1384 TU)))
1385 return true;
1386
1387 break;
1388
1389 case NestedNameSpecifier::TypeSpec:
1390 case NestedNameSpecifier::TypeSpecWithTemplate:
1391 if (Visit(Q.getTypeLoc()))
1392 return true;
1393
1394 break;
1395
1396 case NestedNameSpecifier::Global:
1397 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001398 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 break;
1400 }
1401 }
1402
1403 return false;
1404}
1405
1406bool CursorVisitor::VisitTemplateParameters(
1407 const TemplateParameterList *Params) {
1408 if (!Params)
1409 return false;
1410
1411 for (TemplateParameterList::const_iterator P = Params->begin(),
1412 PEnd = Params->end();
1413 P != PEnd; ++P) {
1414 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1415 return true;
1416 }
1417
1418 return false;
1419}
1420
1421bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1422 switch (Name.getKind()) {
1423 case TemplateName::Template:
1424 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1425
1426 case TemplateName::OverloadedTemplate:
1427 // Visit the overloaded template set.
1428 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1429 return true;
1430
1431 return false;
1432
Richard Smithb23c5e82019-05-09 03:31:27 +00001433 case TemplateName::AssumedTemplate:
1434 // FIXME: Visit DeclarationName?
1435 return false;
1436
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 case TemplateName::DependentTemplate:
1438 // FIXME: Visit nested-name-specifier.
1439 return false;
1440
1441 case TemplateName::QualifiedTemplate:
1442 // FIXME: Visit nested-name-specifier.
1443 return Visit(MakeCursorTemplateRef(
1444 Name.getAsQualifiedTemplateName()->getDecl(),
1445 Loc, TU));
1446
1447 case TemplateName::SubstTemplateTemplateParm:
1448 return Visit(MakeCursorTemplateRef(
1449 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1450 Loc, TU));
1451
1452 case TemplateName::SubstTemplateTemplateParmPack:
1453 return Visit(MakeCursorTemplateRef(
1454 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1455 Loc, TU));
1456 }
1457
1458 llvm_unreachable("Invalid TemplateName::Kind!");
1459}
1460
1461bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1462 switch (TAL.getArgument().getKind()) {
1463 case TemplateArgument::Null:
1464 case TemplateArgument::Integral:
1465 case TemplateArgument::Pack:
1466 return false;
1467
1468 case TemplateArgument::Type:
1469 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1470 return Visit(TSInfo->getTypeLoc());
1471 return false;
1472
1473 case TemplateArgument::Declaration:
1474 if (Expr *E = TAL.getSourceDeclExpression())
1475 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1476 return false;
1477
1478 case TemplateArgument::NullPtr:
1479 if (Expr *E = TAL.getSourceNullPtrExpression())
1480 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1481 return false;
1482
1483 case TemplateArgument::Expression:
1484 if (Expr *E = TAL.getSourceExpression())
1485 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1486 return false;
1487
1488 case TemplateArgument::Template:
1489 case TemplateArgument::TemplateExpansion:
1490 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1491 return true;
1492
1493 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1494 TAL.getTemplateNameLoc());
1495 }
1496
1497 llvm_unreachable("Invalid TemplateArgument::Kind!");
1498}
1499
1500bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1501 return VisitDeclContext(D);
1502}
1503
1504bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1505 return Visit(TL.getUnqualifiedLoc());
1506}
1507
1508bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1509 ASTContext &Context = AU->getASTContext();
1510
1511 // Some builtin types (such as Objective-C's "id", "sel", and
1512 // "Class") have associated declarations. Create cursors for those.
1513 QualType VisitType;
1514 switch (TL.getTypePtr()->getKind()) {
1515
1516 case BuiltinType::Void:
1517 case BuiltinType::NullPtr:
1518 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001519#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1520 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001521#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001522#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1523 case BuiltinType::Id:
1524#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001525 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001526 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001527 case BuiltinType::OCLClkEvent:
1528 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001529 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001530#define SVE_TYPE(Name, Id, SingletonId) \
1531 case BuiltinType::Id:
1532#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00001533#define BUILTIN_TYPE(Id, SingletonId)
1534#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1535#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1536#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1537#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1538#include "clang/AST/BuiltinTypes.def"
1539 break;
1540
1541 case BuiltinType::ObjCId:
1542 VisitType = Context.getObjCIdType();
1543 break;
1544
1545 case BuiltinType::ObjCClass:
1546 VisitType = Context.getObjCClassType();
1547 break;
1548
1549 case BuiltinType::ObjCSel:
1550 VisitType = Context.getObjCSelType();
1551 break;
1552 }
1553
1554 if (!VisitType.isNull()) {
1555 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1556 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1557 TU));
1558 }
1559
1560 return false;
1561}
1562
1563bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1564 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1565}
1566
1567bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1568 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1569}
1570
1571bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1572 if (TL.isDefinition())
1573 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1574
1575 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1576}
1577
1578bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1579 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1580}
1581
1582bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001583 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001584}
1585
Manman Rene6be26c2016-09-13 17:25:08 +00001586bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001587 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001588 return true;
1589 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1590 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1591 TU)))
1592 return true;
1593 }
1594
1595 return false;
1596}
1597
Guy Benyei11169dd2012-12-18 14:30:41 +00001598bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1599 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1600 return true;
1601
Douglas Gregore9d95f12015-07-07 03:57:35 +00001602 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1603 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1604 return true;
1605 }
1606
Guy Benyei11169dd2012-12-18 14:30:41 +00001607 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1608 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1609 TU)))
1610 return true;
1611 }
1612
1613 return false;
1614}
1615
1616bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1617 return Visit(TL.getPointeeLoc());
1618}
1619
1620bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1621 return Visit(TL.getInnerLoc());
1622}
1623
Leonard Chanc72aaf62019-05-07 03:20:17 +00001624bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1625 return Visit(TL.getInnerLoc());
1626}
1627
Guy Benyei11169dd2012-12-18 14:30:41 +00001628bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1629 return Visit(TL.getPointeeLoc());
1630}
1631
1632bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1633 return Visit(TL.getPointeeLoc());
1634}
1635
1636bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1637 return Visit(TL.getPointeeLoc());
1638}
1639
1640bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1641 return Visit(TL.getPointeeLoc());
1642}
1643
1644bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1645 return Visit(TL.getPointeeLoc());
1646}
1647
1648bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1649 return Visit(TL.getModifiedLoc());
1650}
1651
1652bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1653 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001654 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 return true;
1656
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001657 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1658 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1660 return true;
1661
1662 return false;
1663}
1664
1665bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1666 if (Visit(TL.getElementLoc()))
1667 return true;
1668
1669 if (Expr *Size = TL.getSizeExpr())
1670 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1671
1672 return false;
1673}
1674
Reid Kleckner8a365022013-06-24 17:51:48 +00001675bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1676 return Visit(TL.getOriginalLoc());
1677}
1678
Reid Kleckner0503a872013-12-05 01:23:43 +00001679bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1680 return Visit(TL.getOriginalLoc());
1681}
1682
Richard Smith600b5262017-01-26 20:40:47 +00001683bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1684 DeducedTemplateSpecializationTypeLoc TL) {
1685 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1686 TL.getTemplateNameLoc()))
1687 return true;
1688
1689 return false;
1690}
1691
Guy Benyei11169dd2012-12-18 14:30:41 +00001692bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1693 TemplateSpecializationTypeLoc TL) {
1694 // Visit the template name.
1695 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1696 TL.getTemplateNameLoc()))
1697 return true;
1698
1699 // Visit the template arguments.
1700 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1701 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1702 return true;
1703
1704 return false;
1705}
1706
1707bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1708 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1709}
1710
1711bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1712 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1713 return Visit(TSInfo->getTypeLoc());
1714
1715 return false;
1716}
1717
1718bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1719 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1720 return Visit(TSInfo->getTypeLoc());
1721
1722 return false;
1723}
1724
1725bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001726 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001727}
1728
1729bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1730 DependentTemplateSpecializationTypeLoc TL) {
1731 // Visit the nested-name-specifier, if there is one.
1732 if (TL.getQualifierLoc() &&
1733 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1734 return true;
1735
1736 // Visit the template arguments.
1737 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1738 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1739 return true;
1740
1741 return false;
1742}
1743
1744bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1745 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1746 return true;
1747
1748 return Visit(TL.getNamedTypeLoc());
1749}
1750
1751bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1752 return Visit(TL.getPatternLoc());
1753}
1754
1755bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1756 if (Expr *E = TL.getUnderlyingExpr())
1757 return Visit(MakeCXCursor(E, StmtParent, TU));
1758
1759 return false;
1760}
1761
1762bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1763 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1764}
1765
1766bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1767 return Visit(TL.getValueLoc());
1768}
1769
Xiuli Pan9c14e282016-01-09 12:53:17 +00001770bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1771 return Visit(TL.getValueLoc());
1772}
1773
Guy Benyei11169dd2012-12-18 14:30:41 +00001774#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1775bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1776 return Visit##PARENT##Loc(TL); \
1777}
1778
1779DEFAULT_TYPELOC_IMPL(Complex, Type)
1780DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1781DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1782DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1783DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001784DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001785DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001786DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1787DEFAULT_TYPELOC_IMPL(Vector, Type)
1788DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1789DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1790DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1791DEFAULT_TYPELOC_IMPL(Record, TagType)
1792DEFAULT_TYPELOC_IMPL(Enum, TagType)
1793DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1794DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1795DEFAULT_TYPELOC_IMPL(Auto, Type)
1796
1797bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1798 // Visit the nested-name-specifier, if present.
1799 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1800 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1801 return true;
1802
1803 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001804 for (const auto &I : D->bases()) {
1805 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001806 return true;
1807 }
1808 }
1809
1810 return VisitTagDecl(D);
1811}
1812
1813bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001814 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001815 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1816 !I->isImplicit()) &&
1817 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001818 return true;
1819
1820 return false;
1821}
1822
1823//===----------------------------------------------------------------------===//
1824// Data-recursive visitor methods.
1825//===----------------------------------------------------------------------===//
1826
1827namespace {
1828#define DEF_JOB(NAME, DATA, KIND)\
1829class NAME : public VisitorJob {\
1830public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001831 NAME(const DATA *d, CXCursor parent) : \
1832 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001834 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001835};
1836
1837DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1838DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1839DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1840DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001841DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1842DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1843DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1844#undef DEF_JOB
1845
James Y Knight04ec5bf2015-12-24 02:59:37 +00001846class ExplicitTemplateArgsVisit : public VisitorJob {
1847public:
1848 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1849 const TemplateArgumentLoc *End, CXCursor parent)
1850 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1851 End) {}
1852 static bool classof(const VisitorJob *VJ) {
1853 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1854 }
1855 const TemplateArgumentLoc *begin() const {
1856 return static_cast<const TemplateArgumentLoc *>(data[0]);
1857 }
1858 const TemplateArgumentLoc *end() {
1859 return static_cast<const TemplateArgumentLoc *>(data[1]);
1860 }
1861};
Guy Benyei11169dd2012-12-18 14:30:41 +00001862class DeclVisit : public VisitorJob {
1863public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001864 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001865 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001866 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 static bool classof(const VisitorJob *VJ) {
1868 return VJ->getKind() == DeclVisitKind;
1869 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001870 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001871 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001872};
1873class TypeLocVisit : public VisitorJob {
1874public:
1875 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1876 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1877 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1878
1879 static bool classof(const VisitorJob *VJ) {
1880 return VJ->getKind() == TypeLocVisitKind;
1881 }
1882
1883 TypeLoc get() const {
1884 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001885 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 }
1887};
1888
1889class LabelRefVisit : public VisitorJob {
1890public:
1891 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1892 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1893 labelLoc.getPtrEncoding()) {}
1894
1895 static bool classof(const VisitorJob *VJ) {
1896 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1897 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001898 const LabelDecl *get() const {
1899 return static_cast<const LabelDecl *>(data[0]);
1900 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001901 SourceLocation getLoc() const {
1902 return SourceLocation::getFromPtrEncoding(data[1]); }
1903};
1904
1905class NestedNameSpecifierLocVisit : public VisitorJob {
1906public:
1907 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1908 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1909 Qualifier.getNestedNameSpecifier(),
1910 Qualifier.getOpaqueData()) { }
1911
1912 static bool classof(const VisitorJob *VJ) {
1913 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1914 }
1915
1916 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001917 return NestedNameSpecifierLoc(
1918 const_cast<NestedNameSpecifier *>(
1919 static_cast<const NestedNameSpecifier *>(data[0])),
1920 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 }
1922};
1923
1924class DeclarationNameInfoVisit : public VisitorJob {
1925public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001926 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001927 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001928 static bool classof(const VisitorJob *VJ) {
1929 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1930 }
1931 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001932 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001933 switch (S->getStmtClass()) {
1934 default:
1935 llvm_unreachable("Unhandled Stmt");
1936 case clang::Stmt::MSDependentExistsStmtClass:
1937 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1938 case Stmt::CXXDependentScopeMemberExprClass:
1939 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1940 case Stmt::DependentScopeDeclRefExprClass:
1941 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001942 case Stmt::OMPCriticalDirectiveClass:
1943 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001944 }
1945 }
1946};
1947class MemberRefVisit : public VisitorJob {
1948public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001949 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001950 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1951 L.getPtrEncoding()) {}
1952 static bool classof(const VisitorJob *VJ) {
1953 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1954 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001955 const FieldDecl *get() const {
1956 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001957 }
1958 SourceLocation getLoc() const {
1959 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1960 }
1961};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001962class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001963 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001964 VisitorWorkList &WL;
1965 CXCursor Parent;
1966public:
1967 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1968 : WL(wl), Parent(parent) {}
1969
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001970 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1971 void VisitBlockExpr(const BlockExpr *B);
1972 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1973 void VisitCompoundStmt(const CompoundStmt *S);
1974 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1975 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1976 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1977 void VisitCXXNewExpr(const CXXNewExpr *E);
1978 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1979 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1980 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1981 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1982 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1983 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1984 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1985 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001986 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001987 void VisitDeclRefExpr(const DeclRefExpr *D);
1988 void VisitDeclStmt(const DeclStmt *S);
1989 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1990 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1991 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1992 void VisitForStmt(const ForStmt *FS);
1993 void VisitGotoStmt(const GotoStmt *GS);
1994 void VisitIfStmt(const IfStmt *If);
1995 void VisitInitListExpr(const InitListExpr *IE);
1996 void VisitMemberExpr(const MemberExpr *M);
1997 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1998 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1999 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
2000 void VisitOverloadExpr(const OverloadExpr *E);
2001 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2002 void VisitStmt(const Stmt *S);
2003 void VisitSwitchStmt(const SwitchStmt *S);
2004 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002005 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2006 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2007 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2008 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2009 void VisitVAArgExpr(const VAArgExpr *E);
2010 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2011 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2012 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2013 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002014 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002015 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002016 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002017 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002018 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002019 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002020 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002021 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002022 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002023 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002024 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002025 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002026 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002027 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002028 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002029 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002030 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002031 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002032 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002033 void
2034 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002035 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002036 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002037 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002038 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002039 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002040 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002041 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002042 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002043 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002044 void
2045 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002046 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002047 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002048 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002049 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002050 void VisitOMPDistributeParallelForDirective(
2051 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002052 void VisitOMPDistributeParallelForSimdDirective(
2053 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002054 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002055 void VisitOMPTargetParallelForSimdDirective(
2056 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002057 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002058 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002059 void VisitOMPTeamsDistributeSimdDirective(
2060 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002061 void VisitOMPTeamsDistributeParallelForSimdDirective(
2062 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002063 void VisitOMPTeamsDistributeParallelForDirective(
2064 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002065 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002066 void VisitOMPTargetTeamsDistributeDirective(
2067 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002068 void VisitOMPTargetTeamsDistributeParallelForDirective(
2069 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002070 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2071 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002072 void VisitOMPTargetTeamsDistributeSimdDirective(
2073 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002074
Guy Benyei11169dd2012-12-18 14:30:41 +00002075private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002076 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002077 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002078 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2079 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002080 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2081 void AddStmt(const Stmt *S);
2082 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002083 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002084 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002085 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002086};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002087} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002088
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002089void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002090 // 'S' should always be non-null, since it comes from the
2091 // statement we are visiting.
2092 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2093}
2094
2095void
2096EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2097 if (Qualifier)
2098 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2099}
2100
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002101void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002102 if (S)
2103 WL.push_back(StmtVisit(S, Parent));
2104}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002105void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002106 if (D)
2107 WL.push_back(DeclVisit(D, Parent, isFirst));
2108}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002109void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2110 unsigned NumTemplateArgs) {
2111 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002112}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002113void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 if (D)
2115 WL.push_back(MemberRefVisit(D, L, Parent));
2116}
2117void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2118 if (TI)
2119 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2120 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002121void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002122 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002123 for (const Stmt *SubStmt : S->children()) {
2124 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002125 }
2126 if (size == WL.size())
2127 return;
2128 // Now reverse the entries we just added. This will match the DFS
2129 // ordering performed by the worklist.
2130 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2131 std::reverse(I, E);
2132}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002133namespace {
2134class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2135 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002136 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002137 template <typename T>
2138 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002139public:
2140 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2141#define OPENMP_CLAUSE(Name, Class) \
2142 void Visit##Class(const Class *C);
2143#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002144 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002145 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002146};
2147
Alexey Bataev3392d762016-02-16 11:18:12 +00002148void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2149 const OMPClauseWithPreInit *C) {
2150 Visitor->AddStmt(C->getPreInitStmt());
2151}
2152
Alexey Bataev005248a2016-02-25 05:25:57 +00002153void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2154 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002155 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002156 Visitor->AddStmt(C->getPostUpdateExpr());
2157}
2158
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002159void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002160 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002161 Visitor->AddStmt(C->getCondition());
2162}
2163
Alexey Bataev3778b602014-07-17 07:32:53 +00002164void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2165 Visitor->AddStmt(C->getCondition());
2166}
2167
Alexey Bataev568a8332014-03-06 06:15:19 +00002168void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002169 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002170 Visitor->AddStmt(C->getNumThreads());
2171}
2172
Alexey Bataev62c87d22014-03-21 04:51:18 +00002173void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2174 Visitor->AddStmt(C->getSafelen());
2175}
2176
Alexey Bataev66b15b52015-08-21 11:14:16 +00002177void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2178 Visitor->AddStmt(C->getSimdlen());
2179}
2180
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002181void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2182 Visitor->AddStmt(C->getAllocator());
2183}
2184
Alexander Musman8bd31e62014-05-27 15:12:19 +00002185void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2186 Visitor->AddStmt(C->getNumForLoops());
2187}
2188
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002189void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002190
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002191void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2192
Alexey Bataev56dafe82014-06-20 07:16:17 +00002193void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002194 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002195 Visitor->AddStmt(C->getChunkSize());
2196}
2197
Alexey Bataev10e775f2015-07-30 11:36:16 +00002198void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2199 Visitor->AddStmt(C->getNumForLoops());
2200}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002201
Alexey Bataev236070f2014-06-20 11:19:47 +00002202void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2203
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002204void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2205
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002206void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2207
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002208void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2209
Alexey Bataevdea47612014-07-23 07:46:59 +00002210void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2211
Alexey Bataev67a4f222014-07-23 10:25:33 +00002212void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2213
Alexey Bataev459dec02014-07-24 06:46:57 +00002214void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2215
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002216void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2217
Alexey Bataev346265e2015-09-25 10:37:12 +00002218void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2219
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002220void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2221
Alexey Bataevb825de12015-12-07 10:51:44 +00002222void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2223
Kelvin Li1408f912018-09-26 04:28:39 +00002224void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2225 const OMPUnifiedAddressClause *) {}
2226
Patrick Lyster4a370b92018-10-01 13:47:43 +00002227void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2228 const OMPUnifiedSharedMemoryClause *) {}
2229
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002230void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2231 const OMPReverseOffloadClause *) {}
2232
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002233void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2234 const OMPDynamicAllocatorsClause *) {}
2235
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002236void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2237 const OMPAtomicDefaultMemOrderClause *) {}
2238
Michael Wonge710d542015-08-07 16:16:36 +00002239void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2240 Visitor->AddStmt(C->getDevice());
2241}
2242
Kelvin Li099bb8c2015-11-24 20:50:12 +00002243void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002244 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002245 Visitor->AddStmt(C->getNumTeams());
2246}
2247
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002248void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002249 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002250 Visitor->AddStmt(C->getThreadLimit());
2251}
2252
Alexey Bataeva0569352015-12-01 10:17:31 +00002253void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2254 Visitor->AddStmt(C->getPriority());
2255}
2256
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002257void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2258 Visitor->AddStmt(C->getGrainsize());
2259}
2260
Alexey Bataev382967a2015-12-08 12:06:20 +00002261void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2262 Visitor->AddStmt(C->getNumTasks());
2263}
2264
Alexey Bataev28c75412015-12-15 08:19:24 +00002265void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2266 Visitor->AddStmt(C->getHint());
2267}
2268
Alexey Bataev756c1962013-09-24 03:17:45 +00002269template<typename T>
2270void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002271 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002272 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002273 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002274}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002275
Alexey Bataeve04483e2019-03-27 14:14:31 +00002276void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2277 VisitOMPClauseList(C);
2278 Visitor->AddStmt(C->getAllocator());
2279}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002280void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002281 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002282 for (const auto *E : C->private_copies()) {
2283 Visitor->AddStmt(E);
2284 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002285}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002286void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2287 const OMPFirstprivateClause *C) {
2288 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002289 VisitOMPClauseWithPreInit(C);
2290 for (const auto *E : C->private_copies()) {
2291 Visitor->AddStmt(E);
2292 }
2293 for (const auto *E : C->inits()) {
2294 Visitor->AddStmt(E);
2295 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002296}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002297void OMPClauseEnqueue::VisitOMPLastprivateClause(
2298 const OMPLastprivateClause *C) {
2299 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002300 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002301 for (auto *E : C->private_copies()) {
2302 Visitor->AddStmt(E);
2303 }
2304 for (auto *E : C->source_exprs()) {
2305 Visitor->AddStmt(E);
2306 }
2307 for (auto *E : C->destination_exprs()) {
2308 Visitor->AddStmt(E);
2309 }
2310 for (auto *E : C->assignment_ops()) {
2311 Visitor->AddStmt(E);
2312 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002313}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002314void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002315 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002316}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002317void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2318 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002319 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002320 for (auto *E : C->privates()) {
2321 Visitor->AddStmt(E);
2322 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002323 for (auto *E : C->lhs_exprs()) {
2324 Visitor->AddStmt(E);
2325 }
2326 for (auto *E : C->rhs_exprs()) {
2327 Visitor->AddStmt(E);
2328 }
2329 for (auto *E : C->reduction_ops()) {
2330 Visitor->AddStmt(E);
2331 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002332}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002333void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2334 const OMPTaskReductionClause *C) {
2335 VisitOMPClauseList(C);
2336 VisitOMPClauseWithPostUpdate(C);
2337 for (auto *E : C->privates()) {
2338 Visitor->AddStmt(E);
2339 }
2340 for (auto *E : C->lhs_exprs()) {
2341 Visitor->AddStmt(E);
2342 }
2343 for (auto *E : C->rhs_exprs()) {
2344 Visitor->AddStmt(E);
2345 }
2346 for (auto *E : C->reduction_ops()) {
2347 Visitor->AddStmt(E);
2348 }
2349}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002350void OMPClauseEnqueue::VisitOMPInReductionClause(
2351 const OMPInReductionClause *C) {
2352 VisitOMPClauseList(C);
2353 VisitOMPClauseWithPostUpdate(C);
2354 for (auto *E : C->privates()) {
2355 Visitor->AddStmt(E);
2356 }
2357 for (auto *E : C->lhs_exprs()) {
2358 Visitor->AddStmt(E);
2359 }
2360 for (auto *E : C->rhs_exprs()) {
2361 Visitor->AddStmt(E);
2362 }
2363 for (auto *E : C->reduction_ops()) {
2364 Visitor->AddStmt(E);
2365 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002366 for (auto *E : C->taskgroup_descriptors())
2367 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002368}
Alexander Musman8dba6642014-04-22 13:09:42 +00002369void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2370 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002371 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002372 for (const auto *E : C->privates()) {
2373 Visitor->AddStmt(E);
2374 }
Alexander Musman3276a272015-03-21 10:12:56 +00002375 for (const auto *E : C->inits()) {
2376 Visitor->AddStmt(E);
2377 }
2378 for (const auto *E : C->updates()) {
2379 Visitor->AddStmt(E);
2380 }
2381 for (const auto *E : C->finals()) {
2382 Visitor->AddStmt(E);
2383 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002384 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002385 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002386}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002387void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2388 VisitOMPClauseList(C);
2389 Visitor->AddStmt(C->getAlignment());
2390}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002391void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2392 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002393 for (auto *E : C->source_exprs()) {
2394 Visitor->AddStmt(E);
2395 }
2396 for (auto *E : C->destination_exprs()) {
2397 Visitor->AddStmt(E);
2398 }
2399 for (auto *E : C->assignment_ops()) {
2400 Visitor->AddStmt(E);
2401 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002402}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002403void
2404OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2405 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002406 for (auto *E : C->source_exprs()) {
2407 Visitor->AddStmt(E);
2408 }
2409 for (auto *E : C->destination_exprs()) {
2410 Visitor->AddStmt(E);
2411 }
2412 for (auto *E : C->assignment_ops()) {
2413 Visitor->AddStmt(E);
2414 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002415}
Alexey Bataev6125da92014-07-21 11:26:11 +00002416void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2417 VisitOMPClauseList(C);
2418}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002419void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2420 VisitOMPClauseList(C);
2421}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002422void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2423 VisitOMPClauseList(C);
2424}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002425void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2426 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002427 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002428 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002429}
Alexey Bataev3392d762016-02-16 11:18:12 +00002430void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2431 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002432void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2433 VisitOMPClauseList(C);
2434}
Samuel Antaoec172c62016-05-26 17:49:04 +00002435void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2436 VisitOMPClauseList(C);
2437}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002438void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2439 VisitOMPClauseList(C);
2440}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002441void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2442 VisitOMPClauseList(C);
2443}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002444}
Alexey Bataev756c1962013-09-24 03:17:45 +00002445
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002446void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2447 unsigned size = WL.size();
2448 OMPClauseEnqueue Visitor(this);
2449 Visitor.Visit(S);
2450 if (size == WL.size())
2451 return;
2452 // Now reverse the entries we just added. This will match the DFS
2453 // ordering performed by the worklist.
2454 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2455 std::reverse(I, E);
2456}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002457void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2459}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002460void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002461 AddDecl(B->getBlockDecl());
2462}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002463void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 EnqueueChildren(E);
2465 AddTypeLoc(E->getTypeSourceInfo());
2466}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002467void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002468 for (auto &I : llvm::reverse(S->body()))
2469 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002470}
2471void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002472VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 AddStmt(S->getSubStmt());
2474 AddDeclarationNameInfo(S);
2475 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2476 AddNestedNameSpecifierLoc(QualifierLoc);
2477}
2478
2479void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002480VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002481 if (E->hasExplicitTemplateArgs())
2482 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 AddDeclarationNameInfo(E);
2484 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2485 AddNestedNameSpecifierLoc(QualifierLoc);
2486 if (!E->isImplicitAccess())
2487 AddStmt(E->getBase());
2488}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002489void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 // Enqueue the initializer , if any.
2491 AddStmt(E->getInitializer());
2492 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002493 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 // Enqueue the allocated type.
2495 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2496 // Enqueue the placement arguments.
2497 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2498 AddStmt(E->getPlacementArg(I-1));
2499}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002500void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2502 AddStmt(CE->getArg(I-1));
2503 AddStmt(CE->getCallee());
2504 AddStmt(CE->getArg(0));
2505}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002506void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2507 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 // Visit the name of the type being destroyed.
2509 AddTypeLoc(E->getDestroyedTypeInfo());
2510 // Visit the scope type that looks disturbingly like the nested-name-specifier
2511 // but isn't.
2512 AddTypeLoc(E->getScopeTypeInfo());
2513 // Visit the nested-name-specifier.
2514 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2515 AddNestedNameSpecifierLoc(QualifierLoc);
2516 // Visit base expression.
2517 AddStmt(E->getBase());
2518}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002519void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2520 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 AddTypeLoc(E->getTypeSourceInfo());
2522}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002523void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2524 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 EnqueueChildren(E);
2526 AddTypeLoc(E->getTypeSourceInfo());
2527}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002528void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 EnqueueChildren(E);
2530 if (E->isTypeOperand())
2531 AddTypeLoc(E->getTypeOperandSourceInfo());
2532}
2533
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2535 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 EnqueueChildren(E);
2537 AddTypeLoc(E->getTypeSourceInfo());
2538}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002539void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 EnqueueChildren(E);
2541 if (E->isTypeOperand())
2542 AddTypeLoc(E->getTypeOperandSourceInfo());
2543}
2544
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002545void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 EnqueueChildren(S);
2547 AddDecl(S->getExceptionDecl());
2548}
2549
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002550void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002551 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002552 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002553 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002554}
2555
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002556void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002557 if (DR->hasExplicitTemplateArgs())
2558 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 WL.push_back(DeclRefExprParts(DR, Parent));
2560}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002561void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2562 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002563 if (E->hasExplicitTemplateArgs())
2564 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 AddDeclarationNameInfo(E);
2566 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2567}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002568void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 unsigned size = WL.size();
2570 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002571 for (const auto *D : S->decls()) {
2572 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 isFirst = false;
2574 }
2575 if (size == WL.size())
2576 return;
2577 // Now reverse the entries we just added. This will match the DFS
2578 // ordering performed by the worklist.
2579 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2580 std::reverse(I, E);
2581}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002582void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002584 for (const DesignatedInitExpr::Designator &D :
2585 llvm::reverse(E->designators())) {
2586 if (D.isFieldDesignator()) {
2587 if (FieldDecl *Field = D.getField())
2588 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 continue;
2590 }
David Majnemerf7e36092016-06-23 00:15:04 +00002591 if (D.isArrayDesignator()) {
2592 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002593 continue;
2594 }
David Majnemerf7e36092016-06-23 00:15:04 +00002595 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2596 AddStmt(E->getArrayRangeEnd(D));
2597 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 }
2599}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002600void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 EnqueueChildren(E);
2602 AddTypeLoc(E->getTypeInfoAsWritten());
2603}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002604void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 AddStmt(FS->getBody());
2606 AddStmt(FS->getInc());
2607 AddStmt(FS->getCond());
2608 AddDecl(FS->getConditionVariable());
2609 AddStmt(FS->getInit());
2610}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002611void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2613}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002614void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 AddStmt(If->getElse());
2616 AddStmt(If->getThen());
2617 AddStmt(If->getCond());
2618 AddDecl(If->getConditionVariable());
2619}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002620void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 // We care about the syntactic form of the initializer list, only.
2622 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2623 IE = Syntactic;
2624 EnqueueChildren(IE);
2625}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002626void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 WL.push_back(MemberExprParts(M, Parent));
2628
2629 // If the base of the member access expression is an implicit 'this', don't
2630 // visit it.
2631 // FIXME: If we ever want to show these implicit accesses, this will be
2632 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002633 if (M->isImplicitAccess())
2634 return;
2635
2636 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002637 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002638 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2639 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2640 if (FD->isAnonymousStructOrUnion()) {
2641 AddStmt(SubME->getBase());
2642 return;
2643 }
2644 }
2645 }
2646
2647 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002648}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002649void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 AddTypeLoc(E->getEncodedTypeSourceInfo());
2651}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002652void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 EnqueueChildren(M);
2654 AddTypeLoc(M->getClassReceiverTypeInfo());
2655}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002656void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 // Visit the components of the offsetof expression.
2658 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 const OffsetOfNode &Node = E->getComponent(I-1);
2660 switch (Node.getKind()) {
2661 case OffsetOfNode::Array:
2662 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2663 break;
2664 case OffsetOfNode::Field:
2665 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2666 break;
2667 case OffsetOfNode::Identifier:
2668 case OffsetOfNode::Base:
2669 continue;
2670 }
2671 }
2672 // Visit the type into which we're computing the offset.
2673 AddTypeLoc(E->getTypeSourceInfo());
2674}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002675void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002676 if (E->hasExplicitTemplateArgs())
2677 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 WL.push_back(OverloadExprParts(E, Parent));
2679}
2680void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002681 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 EnqueueChildren(E);
2683 if (E->isArgumentType())
2684 AddTypeLoc(E->getArgumentTypeInfo());
2685}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002686void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 EnqueueChildren(S);
2688}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002689void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 AddStmt(S->getBody());
2691 AddStmt(S->getCond());
2692 AddDecl(S->getConditionVariable());
2693}
2694
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002695void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 AddStmt(W->getBody());
2697 AddStmt(W->getCond());
2698 AddDecl(W->getConditionVariable());
2699}
2700
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002701void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 for (unsigned I = E->getNumArgs(); I > 0; --I)
2703 AddTypeLoc(E->getArg(I-1));
2704}
2705
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002706void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 AddTypeLoc(E->getQueriedTypeSourceInfo());
2708}
2709
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002710void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 EnqueueChildren(E);
2712}
2713
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002714void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 VisitOverloadExpr(U);
2716 if (!U->isImplicitAccess())
2717 AddStmt(U->getBase());
2718}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002719void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 AddStmt(E->getSubExpr());
2721 AddTypeLoc(E->getWrittenTypeInfo());
2722}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002723void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 WL.push_back(SizeOfPackExprParts(E, Parent));
2725}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002726void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 // If the opaque value has a source expression, just transparently
2728 // visit that. This is useful for (e.g.) pseudo-object expressions.
2729 if (Expr *SourceExpr = E->getSourceExpr())
2730 return Visit(SourceExpr);
2731}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002732void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 AddStmt(E->getBody());
2734 WL.push_back(LambdaExprParts(E, Parent));
2735}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002736void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 // Treat the expression like its syntactic form.
2738 Visit(E->getSyntacticForm());
2739}
2740
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002741void EnqueueVisitor::VisitOMPExecutableDirective(
2742 const OMPExecutableDirective *D) {
2743 EnqueueChildren(D);
2744 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2745 E = D->clauses().end();
2746 I != E; ++I)
2747 EnqueueChildren(*I);
2748}
2749
Alexander Musman3aaab662014-08-19 11:27:13 +00002750void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2751 VisitOMPExecutableDirective(D);
2752}
2753
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002754void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2755 VisitOMPExecutableDirective(D);
2756}
2757
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002758void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002759 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002760}
2761
Alexey Bataevf29276e2014-06-18 04:14:57 +00002762void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002763 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002764}
2765
Alexander Musmanf82886e2014-09-18 05:12:34 +00002766void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2767 VisitOMPLoopDirective(D);
2768}
2769
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002770void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2771 VisitOMPExecutableDirective(D);
2772}
2773
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002774void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2775 VisitOMPExecutableDirective(D);
2776}
2777
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002778void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2779 VisitOMPExecutableDirective(D);
2780}
2781
Alexander Musman80c22892014-07-17 08:54:58 +00002782void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2783 VisitOMPExecutableDirective(D);
2784}
2785
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002786void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2787 VisitOMPExecutableDirective(D);
2788 AddDeclarationNameInfo(D);
2789}
2790
Alexey Bataev4acb8592014-07-07 13:01:15 +00002791void
2792EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002793 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002794}
2795
Alexander Musmane4e893b2014-09-23 09:33:00 +00002796void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2797 const OMPParallelForSimdDirective *D) {
2798 VisitOMPLoopDirective(D);
2799}
2800
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002801void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2802 const OMPParallelSectionsDirective *D) {
2803 VisitOMPExecutableDirective(D);
2804}
2805
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002806void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2807 VisitOMPExecutableDirective(D);
2808}
2809
Alexey Bataev68446b72014-07-18 07:47:19 +00002810void
2811EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2812 VisitOMPExecutableDirective(D);
2813}
2814
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002815void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2816 VisitOMPExecutableDirective(D);
2817}
2818
Alexey Bataev2df347a2014-07-18 10:17:07 +00002819void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2820 VisitOMPExecutableDirective(D);
2821}
2822
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002823void EnqueueVisitor::VisitOMPTaskgroupDirective(
2824 const OMPTaskgroupDirective *D) {
2825 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002826 if (const Expr *E = D->getReductionRef())
2827 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002828}
2829
Alexey Bataev6125da92014-07-21 11:26:11 +00002830void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2831 VisitOMPExecutableDirective(D);
2832}
2833
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002834void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2835 VisitOMPExecutableDirective(D);
2836}
2837
Alexey Bataev0162e452014-07-22 10:10:35 +00002838void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2839 VisitOMPExecutableDirective(D);
2840}
2841
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002842void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2843 VisitOMPExecutableDirective(D);
2844}
2845
Michael Wong65f367f2015-07-21 13:44:28 +00002846void EnqueueVisitor::VisitOMPTargetDataDirective(const
2847 OMPTargetDataDirective *D) {
2848 VisitOMPExecutableDirective(D);
2849}
2850
Samuel Antaodf67fc42016-01-19 19:15:56 +00002851void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2852 const OMPTargetEnterDataDirective *D) {
2853 VisitOMPExecutableDirective(D);
2854}
2855
Samuel Antao72590762016-01-19 20:04:50 +00002856void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2857 const OMPTargetExitDataDirective *D) {
2858 VisitOMPExecutableDirective(D);
2859}
2860
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002861void EnqueueVisitor::VisitOMPTargetParallelDirective(
2862 const OMPTargetParallelDirective *D) {
2863 VisitOMPExecutableDirective(D);
2864}
2865
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002866void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2867 const OMPTargetParallelForDirective *D) {
2868 VisitOMPLoopDirective(D);
2869}
2870
Alexey Bataev13314bf2014-10-09 04:18:56 +00002871void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2872 VisitOMPExecutableDirective(D);
2873}
2874
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002875void EnqueueVisitor::VisitOMPCancellationPointDirective(
2876 const OMPCancellationPointDirective *D) {
2877 VisitOMPExecutableDirective(D);
2878}
2879
Alexey Bataev80909872015-07-02 11:25:17 +00002880void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2881 VisitOMPExecutableDirective(D);
2882}
2883
Alexey Bataev49f6e782015-12-01 04:18:41 +00002884void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2885 VisitOMPLoopDirective(D);
2886}
2887
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002888void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2889 const OMPTaskLoopSimdDirective *D) {
2890 VisitOMPLoopDirective(D);
2891}
2892
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002893void EnqueueVisitor::VisitOMPDistributeDirective(
2894 const OMPDistributeDirective *D) {
2895 VisitOMPLoopDirective(D);
2896}
2897
Carlo Bertolli9925f152016-06-27 14:55:37 +00002898void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2899 const OMPDistributeParallelForDirective *D) {
2900 VisitOMPLoopDirective(D);
2901}
2902
Kelvin Li4a39add2016-07-05 05:00:15 +00002903void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2904 const OMPDistributeParallelForSimdDirective *D) {
2905 VisitOMPLoopDirective(D);
2906}
2907
Kelvin Li787f3fc2016-07-06 04:45:38 +00002908void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2909 const OMPDistributeSimdDirective *D) {
2910 VisitOMPLoopDirective(D);
2911}
2912
Kelvin Lia579b912016-07-14 02:54:56 +00002913void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2914 const OMPTargetParallelForSimdDirective *D) {
2915 VisitOMPLoopDirective(D);
2916}
2917
Kelvin Li986330c2016-07-20 22:57:10 +00002918void EnqueueVisitor::VisitOMPTargetSimdDirective(
2919 const OMPTargetSimdDirective *D) {
2920 VisitOMPLoopDirective(D);
2921}
2922
Kelvin Li02532872016-08-05 14:37:37 +00002923void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2924 const OMPTeamsDistributeDirective *D) {
2925 VisitOMPLoopDirective(D);
2926}
2927
Kelvin Li4e325f72016-10-25 12:50:55 +00002928void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2929 const OMPTeamsDistributeSimdDirective *D) {
2930 VisitOMPLoopDirective(D);
2931}
2932
Kelvin Li579e41c2016-11-30 23:51:03 +00002933void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2934 const OMPTeamsDistributeParallelForSimdDirective *D) {
2935 VisitOMPLoopDirective(D);
2936}
2937
Kelvin Li7ade93f2016-12-09 03:24:30 +00002938void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2939 const OMPTeamsDistributeParallelForDirective *D) {
2940 VisitOMPLoopDirective(D);
2941}
2942
Kelvin Libf594a52016-12-17 05:48:59 +00002943void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2944 const OMPTargetTeamsDirective *D) {
2945 VisitOMPExecutableDirective(D);
2946}
2947
Kelvin Li83c451e2016-12-25 04:52:54 +00002948void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2949 const OMPTargetTeamsDistributeDirective *D) {
2950 VisitOMPLoopDirective(D);
2951}
2952
Kelvin Li80e8f562016-12-29 22:16:30 +00002953void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2954 const OMPTargetTeamsDistributeParallelForDirective *D) {
2955 VisitOMPLoopDirective(D);
2956}
2957
Kelvin Li1851df52017-01-03 05:23:48 +00002958void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2959 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2960 VisitOMPLoopDirective(D);
2961}
2962
Kelvin Lida681182017-01-10 18:08:18 +00002963void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2964 const OMPTargetTeamsDistributeSimdDirective *D) {
2965 VisitOMPLoopDirective(D);
2966}
2967
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002968void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002969 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2970}
2971
2972bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2973 if (RegionOfInterest.isValid()) {
2974 SourceRange Range = getRawCursorExtent(C);
2975 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2976 return false;
2977 }
2978 return true;
2979}
2980
2981bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2982 while (!WL.empty()) {
2983 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002984 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002985
2986 // Set the Parent field, then back to its old value once we're done.
2987 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2988
2989 switch (LI.getKind()) {
2990 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002991 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 if (!D)
2993 continue;
2994
2995 // For now, perform default visitation for Decls.
2996 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2997 cast<DeclVisit>(&LI)->isFirst())))
2998 return true;
2999
3000 continue;
3001 }
3002 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003003 for (const TemplateArgumentLoc &Arg :
3004 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3005 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 return true;
3007 }
3008 continue;
3009 }
3010 case VisitorJob::TypeLocVisitKind: {
3011 // Perform default visitation for TypeLocs.
3012 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3013 return true;
3014 continue;
3015 }
3016 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003017 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 if (LabelStmt *stmt = LS->getStmt()) {
3019 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3020 TU))) {
3021 return true;
3022 }
3023 }
3024 continue;
3025 }
3026
3027 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3028 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3029 if (VisitNestedNameSpecifierLoc(V->get()))
3030 return true;
3031 continue;
3032 }
3033
3034 case VisitorJob::DeclarationNameInfoVisitKind: {
3035 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3036 ->get()))
3037 return true;
3038 continue;
3039 }
3040 case VisitorJob::MemberRefVisitKind: {
3041 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3042 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3043 return true;
3044 continue;
3045 }
3046 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003047 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 if (!S)
3049 continue;
3050
3051 // Update the current cursor.
3052 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3053 if (!IsInRegionOfInterest(Cursor))
3054 continue;
3055 switch (Visitor(Cursor, Parent, ClientData)) {
3056 case CXChildVisit_Break: return true;
3057 case CXChildVisit_Continue: break;
3058 case CXChildVisit_Recurse:
3059 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003060 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 EnqueueWorkList(WL, S);
3062 break;
3063 }
3064 continue;
3065 }
3066 case VisitorJob::MemberExprPartsKind: {
3067 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003068 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003069
3070 // Visit the nested-name-specifier
3071 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3072 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3073 return true;
3074
3075 // Visit the declaration name.
3076 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3077 return true;
3078
3079 // Visit the explicitly-specified template arguments, if any.
3080 if (M->hasExplicitTemplateArgs()) {
3081 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3082 *ArgEnd = Arg + M->getNumTemplateArgs();
3083 Arg != ArgEnd; ++Arg) {
3084 if (VisitTemplateArgumentLoc(*Arg))
3085 return true;
3086 }
3087 }
3088 continue;
3089 }
3090 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003091 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003092 // Visit nested-name-specifier, if present.
3093 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3094 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3095 return true;
3096 // Visit declaration name.
3097 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3098 return true;
3099 continue;
3100 }
3101 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003102 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 // Visit the nested-name-specifier.
3104 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3105 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3106 return true;
3107 // Visit the declaration name.
3108 if (VisitDeclarationNameInfo(O->getNameInfo()))
3109 return true;
3110 // Visit the overloaded declaration reference.
3111 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3112 return true;
3113 continue;
3114 }
3115 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003116 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 NamedDecl *Pack = E->getPack();
3118 if (isa<TemplateTypeParmDecl>(Pack)) {
3119 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3120 E->getPackLoc(), TU)))
3121 return true;
3122
3123 continue;
3124 }
3125
3126 if (isa<TemplateTemplateParmDecl>(Pack)) {
3127 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3128 E->getPackLoc(), TU)))
3129 return true;
3130
3131 continue;
3132 }
3133
3134 // Non-type template parameter packs and function parameter packs are
3135 // treated like DeclRefExpr cursors.
3136 continue;
3137 }
3138
3139 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003140 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003141 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3143 CEnd = E->explicit_capture_end();
3144 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003145 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003147
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3149 C->getLocation(),
3150 TU)))
3151 return true;
3152 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003153 // Visit init captures
3154 for (auto InitExpr : E->capture_inits()) {
3155 if (Visit(InitExpr))
3156 return true;
3157 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003158
Haojian Wuef87c262018-12-18 15:29:12 +00003159 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003160 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003161 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3162 if (E->hasExplicitParameters()) {
3163 // Visit parameters.
3164 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3165 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003166 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003167 }
3168 if (E->hasExplicitResultType()) {
3169 // Visit result type.
3170 if (Visit(Proto.getReturnLoc()))
3171 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 }
3173 }
3174 break;
3175 }
3176
3177 case VisitorJob::PostChildrenVisitKind:
3178 if (PostChildrenVisitor(Parent, ClientData))
3179 return true;
3180 break;
3181 }
3182 }
3183 return false;
3184}
3185
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003186bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003187 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003188 if (!WorkListFreeList.empty()) {
3189 WL = WorkListFreeList.back();
3190 WL->clear();
3191 WorkListFreeList.pop_back();
3192 }
3193 else {
3194 WL = new VisitorWorkList();
3195 WorkListCache.push_back(WL);
3196 }
3197 EnqueueWorkList(*WL, S);
3198 bool result = RunVisitorWorkList(*WL);
3199 WorkListFreeList.push_back(WL);
3200 return result;
3201}
3202
3203namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003204typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003205RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3206 const DeclarationNameInfo &NI, SourceRange QLoc,
3207 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003208 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3209 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3210 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3211
3212 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3213
3214 RefNamePieces Pieces;
3215
3216 if (WantQualifier && QLoc.isValid())
3217 Pieces.push_back(QLoc);
3218
3219 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3220 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003221
3222 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3223 Pieces.push_back(*TemplateArgsLoc);
3224
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 if (Kind == DeclarationName::CXXOperatorName) {
3226 Pieces.push_back(SourceLocation::getFromRawEncoding(
3227 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3228 Pieces.push_back(SourceLocation::getFromRawEncoding(
3229 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3230 }
3231
3232 if (WantSinglePiece) {
3233 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3234 Pieces.clear();
3235 Pieces.push_back(R);
3236 }
3237
3238 return Pieces;
3239}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003240}
Guy Benyei11169dd2012-12-18 14:30:41 +00003241
3242//===----------------------------------------------------------------------===//
3243// Misc. API hooks.
3244//===----------------------------------------------------------------------===//
3245
Chad Rosier05c71aa2013-03-27 18:28:23 +00003246static void fatal_error_handler(void *user_data, const std::string& reason,
3247 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 // Write the result out to stderr avoiding errs() because raw_ostreams can
3249 // call report_fatal_error.
3250 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3251 ::abort();
3252}
3253
Chandler Carruth66660742014-06-27 16:37:27 +00003254namespace {
3255struct RegisterFatalErrorHandler {
3256 RegisterFatalErrorHandler() {
3257 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3258 }
3259};
3260}
3261
3262static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3263
Guy Benyei11169dd2012-12-18 14:30:41 +00003264CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3265 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003266 // We use crash recovery to make some of our APIs more reliable, implicitly
3267 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003268 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3269 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003270
Chandler Carruth66660742014-06-27 16:37:27 +00003271 // Look through the managed static to trigger construction of the managed
3272 // static which registers our fatal error handler. This ensures it is only
3273 // registered once.
3274 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003275
Adrian Prantlbc068582015-07-08 01:00:30 +00003276 // Initialize targets for clang module support.
3277 llvm::InitializeAllTargets();
3278 llvm::InitializeAllTargetMCs();
3279 llvm::InitializeAllAsmPrinters();
3280 llvm::InitializeAllAsmParsers();
3281
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003282 CIndexer *CIdxr = new CIndexer();
3283
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 if (excludeDeclarationsFromPCH)
3285 CIdxr->setOnlyLocalDecls();
3286 if (displayDiagnostics)
3287 CIdxr->setDisplayDiagnostics();
3288
3289 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3290 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3291 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3292 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3293 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3294 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3295
3296 return CIdxr;
3297}
3298
3299void clang_disposeIndex(CXIndex CIdx) {
3300 if (CIdx)
3301 delete static_cast<CIndexer *>(CIdx);
3302}
3303
3304void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3305 if (CIdx)
3306 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3307}
3308
3309unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3310 if (CIdx)
3311 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3312 return 0;
3313}
3314
Alex Lorenz08615792017-12-04 21:56:36 +00003315void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3316 const char *Path) {
3317 if (CIdx)
3318 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3319}
3320
Guy Benyei11169dd2012-12-18 14:30:41 +00003321void clang_toggleCrashRecovery(unsigned isEnabled) {
3322 if (isEnabled)
3323 llvm::CrashRecoveryContext::Enable();
3324 else
3325 llvm::CrashRecoveryContext::Disable();
3326}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003327
Guy Benyei11169dd2012-12-18 14:30:41 +00003328CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3329 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003330 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003331 enum CXErrorCode Result =
3332 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003333 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003334 assert((TU && Result == CXError_Success) ||
3335 (!TU && Result != CXError_Success));
3336 return TU;
3337}
3338
3339enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3340 const char *ast_filename,
3341 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003342 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003343 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003344
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003345 if (!CIdx || !ast_filename || !out_TU)
3346 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003347
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003348 LOG_FUNC_SECTION {
3349 *Log << ast_filename;
3350 }
3351
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3353 FileSystemOptions FileSystemOpts;
3354
Justin Bognerd512c1e2014-10-15 00:33:06 +00003355 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3356 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003357 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003358 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3359 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003360 FileSystemOpts, /*UseDebugInfo=*/false,
3361 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003362 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003363 /*AllowPCHWithCompilerErrors=*/true,
3364 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003365 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003366 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003367}
3368
3369unsigned clang_defaultEditingTranslationUnitOptions() {
3370 return CXTranslationUnit_PrecompiledPreamble |
3371 CXTranslationUnit_CacheCompletionResults;
3372}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003373
Guy Benyei11169dd2012-12-18 14:30:41 +00003374CXTranslationUnit
3375clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3376 const char *source_filename,
3377 int num_command_line_args,
3378 const char * const *command_line_args,
3379 unsigned num_unsaved_files,
3380 struct CXUnsavedFile *unsaved_files) {
3381 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3382 return clang_parseTranslationUnit(CIdx, source_filename,
3383 command_line_args, num_command_line_args,
3384 unsaved_files, num_unsaved_files,
3385 Options);
3386}
3387
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003388static CXErrorCode
3389clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3390 const char *const *command_line_args,
3391 int num_command_line_args,
3392 ArrayRef<CXUnsavedFile> unsaved_files,
3393 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003394 // Set up the initial return values.
3395 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003396 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003397
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003398 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003399 if (!CIdx || !out_TU)
3400 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003401
Guy Benyei11169dd2012-12-18 14:30:41 +00003402 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3403
3404 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3405 setThreadBackgroundPriority();
3406
3407 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003408 bool CreatePreambleOnFirstParse =
3409 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003410 // FIXME: Add a flag for modules.
3411 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003412 = (options & (CXTranslationUnit_Incomplete |
3413 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003414 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003415 = options & CXTranslationUnit_CacheCompletionResults;
3416 bool IncludeBriefCommentsInCodeCompletion
3417 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003418 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3419 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003420 bool RetainExcludedCB = options &
3421 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003422 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3423 if (options & CXTranslationUnit_SkipFunctionBodies) {
3424 SkipFunctionBodies =
3425 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3426 ? SkipFunctionBodiesScope::Preamble
3427 : SkipFunctionBodiesScope::PreambleAndMainFile;
3428 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003429
3430 // Configure the diagnostics.
3431 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003432 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003433
Manuel Klimek016c0242016-03-01 10:56:19 +00003434 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003435 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003436
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003437 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3438 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3439 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3440
Guy Benyei11169dd2012-12-18 14:30:41 +00003441 // Recover resources if we crash before exiting this function.
3442 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3443 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003444 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003445
Ahmed Charlesb8984322014-03-07 20:03:18 +00003446 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3447 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003448
3449 // Recover resources if we crash before exiting this function.
3450 llvm::CrashRecoveryContextCleanupRegistrar<
3451 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3452
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003453 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003454 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003455 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003456 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003457 }
3458
Ahmed Charlesb8984322014-03-07 20:03:18 +00003459 std::unique_ptr<std::vector<const char *>> Args(
3460 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003461
3462 // Recover resources if we crash before exiting this method.
3463 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3464 ArgsCleanup(Args.get());
3465
3466 // Since the Clang C library is primarily used by batch tools dealing with
3467 // (often very broken) source code, where spell-checking can have a
3468 // significant negative impact on performance (particularly when
3469 // precompiled headers are involved), we disable it by default.
3470 // Only do this if we haven't found a spell-checking-related argument.
3471 bool FoundSpellCheckingArgument = false;
3472 for (int I = 0; I != num_command_line_args; ++I) {
3473 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3474 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3475 FoundSpellCheckingArgument = true;
3476 break;
3477 }
3478 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003479 Args->insert(Args->end(), command_line_args,
3480 command_line_args + num_command_line_args);
3481
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003482 if (!FoundSpellCheckingArgument)
3483 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3484
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 // The 'source_filename' argument is optional. If the caller does not
3486 // specify it then it is assumed that the source file is specified
3487 // in the actual argument list.
3488 // Put the source file after command_line_args otherwise if '-x' flag is
3489 // present it will be unused.
3490 if (source_filename)
3491 Args->push_back(source_filename);
3492
3493 // Do we need the detailed preprocessing record?
3494 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3495 Args->push_back("-Xclang");
3496 Args->push_back("-detailed-preprocessing-record");
3497 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003498
3499 // Suppress any editor placeholder diagnostics.
3500 Args->push_back("-fallow-editor-placeholders");
3501
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003503 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003504 // Unless the user specified that they want the preamble on the first parse
3505 // set it up to be created on the first reparse. This makes the first parse
3506 // faster, trading for a slower (first) reparse.
3507 unsigned PrecompilePreambleAfterNParses =
3508 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003509
Alex Lorenz08615792017-12-04 21:56:36 +00003510 LibclangInvocationReporter InvocationReporter(
3511 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003512 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3513 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003514 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003515 Args->data(), Args->data() + Args->size(),
3516 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003517 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003518 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003519 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3520 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003521 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003522 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003523 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3524 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003525
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003526 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003527 if (!Unit && !ErrUnit)
3528 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003529
Guy Benyei11169dd2012-12-18 14:30:41 +00003530 if (NumErrors != Diags->getClient()->getNumErrors()) {
3531 // Make sure to check that 'Unit' is non-NULL.
3532 if (CXXIdx->getDisplayDiagnostics())
3533 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3534 }
3535
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003536 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3537 return CXError_ASTReadError;
3538
David Blaikieea4395e2017-01-06 19:49:01 +00003539 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003540 if (CXTranslationUnitImpl *TU = *out_TU) {
3541 TU->ParsingOptions = options;
3542 TU->Arguments.reserve(Args->size());
3543 for (const char *Arg : *Args)
3544 TU->Arguments.push_back(Arg);
3545 return CXError_Success;
3546 }
3547 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003548}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003549
3550CXTranslationUnit
3551clang_parseTranslationUnit(CXIndex CIdx,
3552 const char *source_filename,
3553 const char *const *command_line_args,
3554 int num_command_line_args,
3555 struct CXUnsavedFile *unsaved_files,
3556 unsigned num_unsaved_files,
3557 unsigned options) {
3558 CXTranslationUnit TU;
3559 enum CXErrorCode Result = clang_parseTranslationUnit2(
3560 CIdx, source_filename, command_line_args, num_command_line_args,
3561 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003562 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003563 assert((TU && Result == CXError_Success) ||
3564 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003565 return TU;
3566}
3567
3568enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003569 CXIndex CIdx, const char *source_filename,
3570 const char *const *command_line_args, int num_command_line_args,
3571 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3572 unsigned options, CXTranslationUnit *out_TU) {
3573 SmallVector<const char *, 4> Args;
3574 Args.push_back("clang");
3575 Args.append(command_line_args, command_line_args + num_command_line_args);
3576 return clang_parseTranslationUnit2FullArgv(
3577 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3578 num_unsaved_files, options, out_TU);
3579}
3580
3581enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3582 CXIndex CIdx, const char *source_filename,
3583 const char *const *command_line_args, int num_command_line_args,
3584 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3585 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003586 LOG_FUNC_SECTION {
3587 *Log << source_filename << ": ";
3588 for (int i = 0; i != num_command_line_args; ++i)
3589 *Log << command_line_args[i] << " ";
3590 }
3591
Alp Toker9d85b182014-07-07 01:23:14 +00003592 if (num_unsaved_files && !unsaved_files)
3593 return CXError_InvalidArguments;
3594
Alp Toker5c532982014-07-07 22:42:03 +00003595 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003596 auto ParseTranslationUnitImpl = [=, &result] {
3597 result = clang_parseTranslationUnit_Impl(
3598 CIdx, source_filename, command_line_args, num_command_line_args,
3599 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3600 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003601
Guy Benyei11169dd2012-12-18 14:30:41 +00003602 llvm::CrashRecoveryContext CRC;
3603
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003604 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3606 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3607 fprintf(stderr, " 'command_line_args' : [");
3608 for (int i = 0; i != num_command_line_args; ++i) {
3609 if (i)
3610 fprintf(stderr, ", ");
3611 fprintf(stderr, "'%s'", command_line_args[i]);
3612 }
3613 fprintf(stderr, "],\n");
3614 fprintf(stderr, " 'unsaved_files' : [");
3615 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3616 if (i)
3617 fprintf(stderr, ", ");
3618 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3619 unsaved_files[i].Length);
3620 }
3621 fprintf(stderr, "],\n");
3622 fprintf(stderr, " 'options' : %d,\n", options);
3623 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003624
3625 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003626 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003627 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003628 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 }
Alp Toker5c532982014-07-07 22:42:03 +00003630
3631 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003632}
3633
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003634CXString clang_Type_getObjCEncoding(CXType CT) {
3635 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3636 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3637 std::string encoding;
3638 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3639 encoding);
3640
3641 return cxstring::createDup(encoding);
3642}
3643
3644static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3645 if (C.kind == CXCursor_MacroDefinition) {
3646 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3647 return MDR->getName();
3648 } else if (C.kind == CXCursor_MacroExpansion) {
3649 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3650 return ME.getName();
3651 }
3652 return nullptr;
3653}
3654
3655unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3656 const IdentifierInfo *II = getMacroIdentifier(C);
3657 if (!II) {
3658 return false;
3659 }
3660 ASTUnit *ASTU = getCursorASTUnit(C);
3661 Preprocessor &PP = ASTU->getPreprocessor();
3662 if (const MacroInfo *MI = PP.getMacroInfo(II))
3663 return MI->isFunctionLike();
3664 return false;
3665}
3666
3667unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3668 const IdentifierInfo *II = getMacroIdentifier(C);
3669 if (!II) {
3670 return false;
3671 }
3672 ASTUnit *ASTU = getCursorASTUnit(C);
3673 Preprocessor &PP = ASTU->getPreprocessor();
3674 if (const MacroInfo *MI = PP.getMacroInfo(II))
3675 return MI->isBuiltinMacro();
3676 return false;
3677}
3678
3679unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3680 const Decl *D = getCursorDecl(C);
3681 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3682 if (!FD) {
3683 return false;
3684 }
3685 return FD->isInlined();
3686}
3687
3688static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3689 if (callExpr->getNumArgs() != 1) {
3690 return nullptr;
3691 }
3692
3693 StringLiteral *S = nullptr;
3694 auto *arg = callExpr->getArg(0);
3695 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3696 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3697 auto *subExpr = I->getSubExprAsWritten();
3698
3699 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3700 return nullptr;
3701 }
3702
3703 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3704 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3705 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3706 } else {
3707 return nullptr;
3708 }
3709 return S;
3710}
3711
David Blaikie59272572016-04-13 18:23:33 +00003712struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003713 CXEvalResultKind EvalType;
3714 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003715 unsigned long long unsignedVal;
3716 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003717 double floatVal;
3718 char *stringVal;
3719 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003720 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003721 ~ExprEvalResult() {
3722 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3723 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003724 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003725 }
3726 }
3727};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003728
3729void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003730 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003731}
3732
3733CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3734 if (!E) {
3735 return CXEval_UnExposed;
3736 }
3737 return ((ExprEvalResult *)E)->EvalType;
3738}
3739
3740int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003741 return clang_EvalResult_getAsLongLong(E);
3742}
3743
3744long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003745 if (!E) {
3746 return 0;
3747 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003748 ExprEvalResult *Result = (ExprEvalResult*)E;
3749 if (Result->IsUnsignedInt)
3750 return Result->EvalData.unsignedVal;
3751 return Result->EvalData.intVal;
3752}
3753
3754unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3755 return ((ExprEvalResult *)E)->IsUnsignedInt;
3756}
3757
3758unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3759 if (!E) {
3760 return 0;
3761 }
3762
3763 ExprEvalResult *Result = (ExprEvalResult*)E;
3764 if (Result->IsUnsignedInt)
3765 return Result->EvalData.unsignedVal;
3766 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003767}
3768
3769double clang_EvalResult_getAsDouble(CXEvalResult E) {
3770 if (!E) {
3771 return 0;
3772 }
3773 return ((ExprEvalResult *)E)->EvalData.floatVal;
3774}
3775
3776const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3777 if (!E) {
3778 return nullptr;
3779 }
3780 return ((ExprEvalResult *)E)->EvalData.stringVal;
3781}
3782
3783static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3784 Expr::EvalResult ER;
3785 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003786 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003787 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003788
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003789 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003790 if (expr->isValueDependent())
3791 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003792 if (!expr->EvaluateAsRValue(ER, ctx))
3793 return nullptr;
3794
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003795 QualType rettype;
3796 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003797 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003798 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003799 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003800
David Blaikiebbc00882016-04-13 18:36:19 +00003801 if (ER.Val.isInt()) {
3802 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003803
3804 auto& val = ER.Val.getInt();
3805 if (val.isUnsigned()) {
3806 result->IsUnsignedInt = true;
3807 result->EvalData.unsignedVal = val.getZExtValue();
3808 } else {
3809 result->EvalData.intVal = val.getExtValue();
3810 }
3811
David Blaikiebbc00882016-04-13 18:36:19 +00003812 return result.release();
3813 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003814
David Blaikiebbc00882016-04-13 18:36:19 +00003815 if (ER.Val.isFloat()) {
3816 llvm::SmallVector<char, 100> Buffer;
3817 ER.Val.getFloat().toString(Buffer);
3818 std::string floatStr(Buffer.data(), Buffer.size());
3819 result->EvalType = CXEval_Float;
3820 bool ignored;
3821 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003822 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003823 llvm::APFloat::rmNearestTiesToEven, &ignored);
3824 result->EvalData.floatVal = apFloat.convertToDouble();
3825 return result.release();
3826 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003827
David Blaikiebbc00882016-04-13 18:36:19 +00003828 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3829 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3830 auto *subExpr = I->getSubExprAsWritten();
3831 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3832 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003833 const StringLiteral *StrE = nullptr;
3834 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003835 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003836
3837 if (ObjCExpr) {
3838 StrE = ObjCExpr->getString();
3839 result->EvalType = CXEval_ObjCStrLiteral;
3840 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003841 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003842 result->EvalType = CXEval_StrLiteral;
3843 }
3844
3845 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003846 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003847 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3848 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003849 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003850 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003851 }
3852 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3853 expr->getStmtClass() == Stmt::StringLiteralClass) {
3854 const StringLiteral *StrE = nullptr;
3855 const ObjCStringLiteral *ObjCExpr;
3856 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003857
David Blaikiebbc00882016-04-13 18:36:19 +00003858 if (ObjCExpr) {
3859 StrE = ObjCExpr->getString();
3860 result->EvalType = CXEval_ObjCStrLiteral;
3861 } else {
3862 StrE = cast<StringLiteral>(expr);
3863 result->EvalType = CXEval_StrLiteral;
3864 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003865
David Blaikiebbc00882016-04-13 18:36:19 +00003866 std::string strRef(StrE->getString().str());
3867 result->EvalData.stringVal = new char[strRef.size() + 1];
3868 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3869 result->EvalData.stringVal[strRef.size()] = '\0';
3870 return result.release();
3871 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003872
David Blaikiebbc00882016-04-13 18:36:19 +00003873 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3874 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003875
David Blaikiebbc00882016-04-13 18:36:19 +00003876 rettype = CC->getType();
3877 if (rettype.getAsString() == "CFStringRef" &&
3878 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003879
David Blaikiebbc00882016-04-13 18:36:19 +00003880 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3881 StringLiteral *S = getCFSTR_value(callExpr);
3882 if (S) {
3883 std::string strLiteral(S->getString().str());
3884 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003885
David Blaikiebbc00882016-04-13 18:36:19 +00003886 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3887 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3888 strLiteral.size());
3889 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003890 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003891 }
3892 }
3893
David Blaikiebbc00882016-04-13 18:36:19 +00003894 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3895 callExpr = static_cast<CallExpr *>(expr);
3896 rettype = callExpr->getCallReturnType(ctx);
3897
3898 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3899 return nullptr;
3900
3901 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3902 if (callExpr->getNumArgs() == 1 &&
3903 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3904 return nullptr;
3905 } else if (rettype.getAsString() == "CFStringRef") {
3906
3907 StringLiteral *S = getCFSTR_value(callExpr);
3908 if (S) {
3909 std::string strLiteral(S->getString().str());
3910 result->EvalType = CXEval_CFStr;
3911 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3912 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3913 strLiteral.size());
3914 result->EvalData.stringVal[strLiteral.size()] = '\0';
3915 return result.release();
3916 }
3917 }
3918 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3919 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3920 ValueDecl *V = D->getDecl();
3921 if (V->getKind() == Decl::Function) {
3922 std::string strName = V->getNameAsString();
3923 result->EvalType = CXEval_Other;
3924 result->EvalData.stringVal = new char[strName.size() + 1];
3925 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3926 result->EvalData.stringVal[strName.size()] = '\0';
3927 return result.release();
3928 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003929 }
3930
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003931 return nullptr;
3932}
3933
Alex Lorenz65317e12019-01-08 22:32:51 +00003934static const Expr *evaluateDeclExpr(const Decl *D) {
3935 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003936 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003937 if (auto *Var = dyn_cast<VarDecl>(D))
3938 return Var->getInit();
3939 else if (auto *Field = dyn_cast<FieldDecl>(D))
3940 return Field->getInClassInitializer();
3941 return nullptr;
3942}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003943
Alex Lorenz65317e12019-01-08 22:32:51 +00003944static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3945 assert(CS && "invalid compound statement");
3946 for (auto *bodyIterator : CS->body()) {
3947 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3948 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003949 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003950 return nullptr;
3951}
3952
Alex Lorenz65317e12019-01-08 22:32:51 +00003953CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3954 if (const Expr *E =
3955 clang_getCursorKind(C) == CXCursor_CompoundStmt
3956 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3957 : evaluateDeclExpr(getCursorDecl(C)))
3958 return const_cast<CXEvalResult>(
3959 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3960 return nullptr;
3961}
3962
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003963unsigned clang_Cursor_hasAttrs(CXCursor C) {
3964 const Decl *D = getCursorDecl(C);
3965 if (!D) {
3966 return 0;
3967 }
3968
3969 if (D->hasAttrs()) {
3970 return 1;
3971 }
3972
3973 return 0;
3974}
Guy Benyei11169dd2012-12-18 14:30:41 +00003975unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3976 return CXSaveTranslationUnit_None;
3977}
3978
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003979static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3980 const char *FileName,
3981 unsigned options) {
3982 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003983 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3984 setThreadBackgroundPriority();
3985
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003986 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3987 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003988}
3989
3990int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3991 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003992 LOG_FUNC_SECTION {
3993 *Log << TU << ' ' << FileName;
3994 }
3995
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003996 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003997 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003999 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004000
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004001 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4003 if (!CXXUnit->hasSema())
4004 return CXSaveError_InvalidTU;
4005
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004006 CXSaveError result;
4007 auto SaveTranslationUnitImpl = [=, &result]() {
4008 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4009 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004010
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004011 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004012 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004013
4014 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4015 PrintLibclangResourceUsage(TU);
4016
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004017 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 }
4019
4020 // We have an AST that has invalid nodes due to compiler errors.
4021 // Use a crash recovery thread for protection.
4022
4023 llvm::CrashRecoveryContext CRC;
4024
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004025 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004026 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4027 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4028 fprintf(stderr, " 'options' : %d,\n", options);
4029 fprintf(stderr, "}\n");
4030
4031 return CXSaveError_Unknown;
4032
4033 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4034 PrintLibclangResourceUsage(TU);
4035 }
4036
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004037 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004038}
4039
4040void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4041 if (CTUnit) {
4042 // If the translation unit has been marked as unsafe to free, just discard
4043 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004044 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4045 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 return;
4047
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004048 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004049 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4051 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004052 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004053 delete CTUnit;
4054 }
4055}
4056
Erik Verbruggen346066b2017-05-30 14:25:54 +00004057unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4058 if (CTUnit) {
4059 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4060
4061 if (Unit && Unit->isUnsafeToFree())
4062 return false;
4063
4064 Unit->ResetForParse();
4065 return true;
4066 }
4067
4068 return false;
4069}
4070
Guy Benyei11169dd2012-12-18 14:30:41 +00004071unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4072 return CXReparse_None;
4073}
4074
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004075static CXErrorCode
4076clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4077 ArrayRef<CXUnsavedFile> unsaved_files,
4078 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004079 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004080 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004081 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004082 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004083 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004084
4085 // Reset the associated diagnostics.
4086 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004087 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004088
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004089 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4091 setThreadBackgroundPriority();
4092
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004093 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004095
4096 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4097 new std::vector<ASTUnit::RemappedFile>());
4098
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 // Recover resources if we crash before exiting this function.
4100 llvm::CrashRecoveryContextCleanupRegistrar<
4101 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004102
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004103 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004104 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004105 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004106 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004107 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004108
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004109 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4110 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004111 return CXError_Success;
4112 if (isASTReadError(CXXUnit))
4113 return CXError_ASTReadError;
4114 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004115}
4116
4117int clang_reparseTranslationUnit(CXTranslationUnit TU,
4118 unsigned num_unsaved_files,
4119 struct CXUnsavedFile *unsaved_files,
4120 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004121 LOG_FUNC_SECTION {
4122 *Log << TU;
4123 }
4124
Alp Toker9d85b182014-07-07 01:23:14 +00004125 if (num_unsaved_files && !unsaved_files)
4126 return CXError_InvalidArguments;
4127
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004128 CXErrorCode result;
4129 auto ReparseTranslationUnitImpl = [=, &result]() {
4130 result = clang_reparseTranslationUnit_Impl(
4131 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4132 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004133
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 llvm::CrashRecoveryContext CRC;
4135
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004136 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004137 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004138 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004139 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004140 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4141 PrintLibclangResourceUsage(TU);
4142
Alp Toker5c532982014-07-07 22:42:03 +00004143 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004144}
4145
4146
4147CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004148 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004149 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004150 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004151 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004152
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004153 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004154 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004155}
4156
4157CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004158 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004159 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004160 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004161 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004162
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004163 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004164 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4165}
4166
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004167CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4168 if (isNotUsableTU(CTUnit)) {
4169 LOG_BAD_TU(CTUnit);
4170 return nullptr;
4171 }
4172
4173 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4174 impl->TranslationUnit = CTUnit;
4175 return impl;
4176}
4177
4178CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4179 if (!TargetInfo)
4180 return cxstring::createEmpty();
4181
4182 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4183 assert(!isNotUsableTU(CTUnit) &&
4184 "Unexpected unusable translation unit in TargetInfo");
4185
4186 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4187 std::string Triple =
4188 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4189 return cxstring::createDup(Triple);
4190}
4191
4192int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4193 if (!TargetInfo)
4194 return -1;
4195
4196 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4197 assert(!isNotUsableTU(CTUnit) &&
4198 "Unexpected unusable translation unit in TargetInfo");
4199
4200 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4201 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4202}
4203
4204void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4205 if (!TargetInfo)
4206 return;
4207
4208 delete TargetInfo;
4209}
4210
Guy Benyei11169dd2012-12-18 14:30:41 +00004211//===----------------------------------------------------------------------===//
4212// CXFile Operations.
4213//===----------------------------------------------------------------------===//
4214
Guy Benyei11169dd2012-12-18 14:30:41 +00004215CXString clang_getFileName(CXFile SFile) {
4216 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004217 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004218
4219 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004220 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004221}
4222
4223time_t clang_getFileTime(CXFile SFile) {
4224 if (!SFile)
4225 return 0;
4226
4227 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4228 return FEnt->getModificationTime();
4229}
4230
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004231CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004232 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004233 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004234 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004235 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004236
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004237 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004238
4239 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004240 auto File = FMgr.getFile(file_name);
4241 if (!File)
4242 return nullptr;
4243 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004244}
4245
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004246const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4247 size_t *size) {
4248 if (isNotUsableTU(TU)) {
4249 LOG_BAD_TU(TU);
4250 return nullptr;
4251 }
4252
4253 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4254 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4255 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004256 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004257 if (Invalid) {
4258 if (size)
4259 *size = 0;
4260 return nullptr;
4261 }
4262 if (size)
4263 *size = buf->getBufferSize();
4264 return buf->getBufferStart();
4265}
4266
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004267unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4268 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004269 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004270 LOG_BAD_TU(TU);
4271 return 0;
4272 }
4273
4274 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 return 0;
4276
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004277 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 FileEntry *FEnt = static_cast<FileEntry *>(file);
4279 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4280 .isFileMultipleIncludeGuarded(FEnt);
4281}
4282
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004283int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4284 if (!file || !outID)
4285 return 1;
4286
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004287 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004288 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4289 outID->data[0] = ID.getDevice();
4290 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004291 outID->data[2] = FEnt->getModificationTime();
4292 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004293}
4294
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004295int clang_File_isEqual(CXFile file1, CXFile file2) {
4296 if (file1 == file2)
4297 return true;
4298
4299 if (!file1 || !file2)
4300 return false;
4301
4302 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4303 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4304 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4305}
4306
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004307CXString clang_File_tryGetRealPathName(CXFile SFile) {
4308 if (!SFile)
4309 return cxstring::createNull();
4310
4311 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4312 return cxstring::createRef(FEnt->tryGetRealPathName());
4313}
4314
Guy Benyei11169dd2012-12-18 14:30:41 +00004315//===----------------------------------------------------------------------===//
4316// CXCursor Operations.
4317//===----------------------------------------------------------------------===//
4318
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004319static const Decl *getDeclFromExpr(const Stmt *E) {
4320 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 return getDeclFromExpr(CE->getSubExpr());
4322
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004323 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004325 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004327 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004329 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 if (PRE->isExplicitProperty())
4331 return PRE->getExplicitProperty();
4332 // It could be messaging both getter and setter as in:
4333 // ++myobj.myprop;
4334 // in which case prefer to associate the setter since it is less obvious
4335 // from inspecting the source that the setter is going to get called.
4336 if (PRE->isMessagingSetter())
4337 return PRE->getImplicitPropertySetter();
4338 return PRE->getImplicitPropertyGetter();
4339 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004340 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004342 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 if (Expr *Src = OVE->getSourceExpr())
4344 return getDeclFromExpr(Src);
4345
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004346 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004348 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 if (!CE->isElidable())
4350 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004351 if (const CXXInheritedCtorInitExpr *CE =
4352 dyn_cast<CXXInheritedCtorInitExpr>(E))
4353 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004354 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 return OME->getMethodDecl();
4356
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004357 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004359 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4361 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004362 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4364 isa<ParmVarDecl>(SizeOfPack->getPack()))
4365 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004366
4367 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004368}
4369
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004370static SourceLocation getLocationFromExpr(const Expr *E) {
4371 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 return getLocationFromExpr(CE->getSubExpr());
4373
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004374 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004376 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004378 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004380 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004382 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004384 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004386
4387 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004388}
4389
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004390extern "C" {
4391
Guy Benyei11169dd2012-12-18 14:30:41 +00004392unsigned clang_visitChildren(CXCursor parent,
4393 CXCursorVisitor visitor,
4394 CXClientData client_data) {
4395 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4396 /*VisitPreprocessorLast=*/false);
4397 return CursorVis.VisitChildren(parent);
4398}
4399
4400#ifndef __has_feature
4401#define __has_feature(x) 0
4402#endif
4403#if __has_feature(blocks)
4404typedef enum CXChildVisitResult
4405 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4406
4407static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4408 CXClientData client_data) {
4409 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4410 return block(cursor, parent);
4411}
4412#else
4413// If we are compiled with a compiler that doesn't have native blocks support,
4414// define and call the block manually, so the
4415typedef struct _CXChildVisitResult
4416{
4417 void *isa;
4418 int flags;
4419 int reserved;
4420 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4421 CXCursor);
4422} *CXCursorVisitorBlock;
4423
4424static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4425 CXClientData client_data) {
4426 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4427 return block->invoke(block, cursor, parent);
4428}
4429#endif
4430
4431
4432unsigned clang_visitChildrenWithBlock(CXCursor parent,
4433 CXCursorVisitorBlock block) {
4434 return clang_visitChildren(parent, visitWithBlock, block);
4435}
4436
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004437static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004439 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004440
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004441 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004443 if (const ObjCPropertyImplDecl *PropImpl =
4444 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004446 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004447
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004448 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004450 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004451
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004452 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 }
4454
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004455 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004456 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004457
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004458 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4460 // and returns different names. NamedDecl returns the class name and
4461 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004462 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004463
4464 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004465 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004466
4467 SmallString<1024> S;
4468 llvm::raw_svector_ostream os(S);
4469 ND->printName(os);
4470
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004471 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004472}
4473
4474CXString clang_getCursorSpelling(CXCursor C) {
4475 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004476 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004477
4478 if (clang_isReference(C.kind)) {
4479 switch (C.kind) {
4480 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004481 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004482 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 }
4484 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004485 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004486 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 }
4488 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004489 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004491 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 }
4493 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004494 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004495 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 }
4497 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004498 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 assert(Type && "Missing type decl");
4500
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004501 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 getAsString());
4503 }
4504 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004505 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 assert(Template && "Missing template decl");
4507
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004508 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 }
4510
4511 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004512 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 assert(NS && "Missing namespace decl");
4514
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004515 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 }
4517
4518 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004519 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 assert(Field && "Missing member decl");
4521
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004522 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 }
4524
4525 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004526 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 assert(Label && "Missing label");
4528
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004529 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004530 }
4531
4532 case CXCursor_OverloadedDeclRef: {
4533 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004534 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4535 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004536 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004537 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004539 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004540 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 OverloadedTemplateStorage *Ovl
4542 = Storage.get<OverloadedTemplateStorage*>();
4543 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004544 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004545 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 }
4547
4548 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004549 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 assert(Var && "Missing variable decl");
4551
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004552 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 }
4554
4555 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004556 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 }
4558 }
4559
4560 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004561 const Expr *E = getCursorExpr(C);
4562
4563 if (C.kind == CXCursor_ObjCStringLiteral ||
4564 C.kind == CXCursor_StringLiteral) {
4565 const StringLiteral *SLit;
4566 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4567 SLit = OSL->getString();
4568 } else {
4569 SLit = cast<StringLiteral>(E);
4570 }
4571 SmallString<256> Buf;
4572 llvm::raw_svector_ostream OS(Buf);
4573 SLit->outputString(OS);
4574 return cxstring::createDup(OS.str());
4575 }
4576
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004577 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 if (D)
4579 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004580 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 }
4582
4583 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004584 const Stmt *S = getCursorStmt(C);
4585 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004586 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004587
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004588 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 }
4590
4591 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004592 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 ->getNameStart());
4594
4595 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004596 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 ->getNameStart());
4598
4599 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004600 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004601
4602 if (clang_isDeclaration(C.kind))
4603 return getDeclSpelling(getCursorDecl(C));
4604
4605 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004606 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004607 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 }
4609
4610 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004611 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004612 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 }
4614
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004615 if (C.kind == CXCursor_PackedAttr) {
4616 return cxstring::createRef("packed");
4617 }
4618
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004619 if (C.kind == CXCursor_VisibilityAttr) {
4620 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4621 switch (AA->getVisibility()) {
4622 case VisibilityAttr::VisibilityType::Default:
4623 return cxstring::createRef("default");
4624 case VisibilityAttr::VisibilityType::Hidden:
4625 return cxstring::createRef("hidden");
4626 case VisibilityAttr::VisibilityType::Protected:
4627 return cxstring::createRef("protected");
4628 }
4629 llvm_unreachable("unknown visibility type");
4630 }
4631
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004632 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004633}
4634
4635CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4636 unsigned pieceIndex,
4637 unsigned options) {
4638 if (clang_Cursor_isNull(C))
4639 return clang_getNullRange();
4640
4641 ASTContext &Ctx = getCursorContext(C);
4642
4643 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004644 const Stmt *S = getCursorStmt(C);
4645 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 if (pieceIndex > 0)
4647 return clang_getNullRange();
4648 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4649 }
4650
4651 return clang_getNullRange();
4652 }
4653
4654 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004655 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4657 if (pieceIndex >= ME->getNumSelectorLocs())
4658 return clang_getNullRange();
4659 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4660 }
4661 }
4662
4663 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4664 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004665 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004666 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4667 if (pieceIndex >= MD->getNumSelectorLocs())
4668 return clang_getNullRange();
4669 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4670 }
4671 }
4672
4673 if (C.kind == CXCursor_ObjCCategoryDecl ||
4674 C.kind == CXCursor_ObjCCategoryImplDecl) {
4675 if (pieceIndex > 0)
4676 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004677 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004678 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4679 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004680 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4682 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4683 }
4684
4685 if (C.kind == CXCursor_ModuleImportDecl) {
4686 if (pieceIndex > 0)
4687 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004688 if (const ImportDecl *ImportD =
4689 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4691 if (!Locs.empty())
4692 return cxloc::translateSourceRange(Ctx,
4693 SourceRange(Locs.front(), Locs.back()));
4694 }
4695 return clang_getNullRange();
4696 }
4697
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004698 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004699 C.kind == CXCursor_ConversionFunction ||
4700 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004701 if (pieceIndex > 0)
4702 return clang_getNullRange();
4703 if (const FunctionDecl *FD =
4704 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4705 DeclarationNameInfo FunctionName = FD->getNameInfo();
4706 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4707 }
4708 return clang_getNullRange();
4709 }
4710
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 // FIXME: A CXCursor_InclusionDirective should give the location of the
4712 // filename, but we don't keep track of this.
4713
4714 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4715 // but we don't keep track of this.
4716
4717 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4718 // but we don't keep track of this.
4719
4720 // Default handling, give the location of the cursor.
4721
4722 if (pieceIndex > 0)
4723 return clang_getNullRange();
4724
4725 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4726 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4727 return cxloc::translateSourceRange(Ctx, Loc);
4728}
4729
Eli Bendersky44a206f2014-07-31 18:04:56 +00004730CXString clang_Cursor_getMangling(CXCursor C) {
4731 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4732 return cxstring::createEmpty();
4733
Eli Bendersky44a206f2014-07-31 18:04:56 +00004734 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004735 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004736 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4737 return cxstring::createEmpty();
4738
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004739 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004740 ASTNameGenerator ASTNameGen(Ctx);
4741 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004742}
4743
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004744CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4745 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4746 return nullptr;
4747
4748 const Decl *D = getCursorDecl(C);
4749 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4750 return nullptr;
4751
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004752 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004753 ASTNameGenerator ASTNameGen(Ctx);
4754 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004755 return cxstring::createSet(Manglings);
4756}
4757
Dave Lee1a532c92017-09-22 16:58:57 +00004758CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4759 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4760 return nullptr;
4761
4762 const Decl *D = getCursorDecl(C);
4763 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4764 return nullptr;
4765
4766 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004767 ASTNameGenerator ASTNameGen(Ctx);
4768 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004769 return cxstring::createSet(Manglings);
4770}
4771
Jonathan Coe45ef5032018-01-16 10:19:56 +00004772CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4773 if (clang_Cursor_isNull(C))
4774 return 0;
4775 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4776}
4777
4778void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4779 if (Policy)
4780 delete static_cast<PrintingPolicy *>(Policy);
4781}
4782
4783unsigned
4784clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4785 enum CXPrintingPolicyProperty Property) {
4786 if (!Policy)
4787 return 0;
4788
4789 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4790 switch (Property) {
4791 case CXPrintingPolicy_Indentation:
4792 return P->Indentation;
4793 case CXPrintingPolicy_SuppressSpecifiers:
4794 return P->SuppressSpecifiers;
4795 case CXPrintingPolicy_SuppressTagKeyword:
4796 return P->SuppressTagKeyword;
4797 case CXPrintingPolicy_IncludeTagDefinition:
4798 return P->IncludeTagDefinition;
4799 case CXPrintingPolicy_SuppressScope:
4800 return P->SuppressScope;
4801 case CXPrintingPolicy_SuppressUnwrittenScope:
4802 return P->SuppressUnwrittenScope;
4803 case CXPrintingPolicy_SuppressInitializers:
4804 return P->SuppressInitializers;
4805 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4806 return P->ConstantArraySizeAsWritten;
4807 case CXPrintingPolicy_AnonymousTagLocations:
4808 return P->AnonymousTagLocations;
4809 case CXPrintingPolicy_SuppressStrongLifetime:
4810 return P->SuppressStrongLifetime;
4811 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4812 return P->SuppressLifetimeQualifiers;
4813 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4814 return P->SuppressTemplateArgsInCXXConstructors;
4815 case CXPrintingPolicy_Bool:
4816 return P->Bool;
4817 case CXPrintingPolicy_Restrict:
4818 return P->Restrict;
4819 case CXPrintingPolicy_Alignof:
4820 return P->Alignof;
4821 case CXPrintingPolicy_UnderscoreAlignof:
4822 return P->UnderscoreAlignof;
4823 case CXPrintingPolicy_UseVoidForZeroParams:
4824 return P->UseVoidForZeroParams;
4825 case CXPrintingPolicy_TerseOutput:
4826 return P->TerseOutput;
4827 case CXPrintingPolicy_PolishForDeclaration:
4828 return P->PolishForDeclaration;
4829 case CXPrintingPolicy_Half:
4830 return P->Half;
4831 case CXPrintingPolicy_MSWChar:
4832 return P->MSWChar;
4833 case CXPrintingPolicy_IncludeNewlines:
4834 return P->IncludeNewlines;
4835 case CXPrintingPolicy_MSVCFormatting:
4836 return P->MSVCFormatting;
4837 case CXPrintingPolicy_ConstantsAsWritten:
4838 return P->ConstantsAsWritten;
4839 case CXPrintingPolicy_SuppressImplicitBase:
4840 return P->SuppressImplicitBase;
4841 case CXPrintingPolicy_FullyQualifiedName:
4842 return P->FullyQualifiedName;
4843 }
4844
4845 assert(false && "Invalid CXPrintingPolicyProperty");
4846 return 0;
4847}
4848
4849void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4850 enum CXPrintingPolicyProperty Property,
4851 unsigned Value) {
4852 if (!Policy)
4853 return;
4854
4855 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4856 switch (Property) {
4857 case CXPrintingPolicy_Indentation:
4858 P->Indentation = Value;
4859 return;
4860 case CXPrintingPolicy_SuppressSpecifiers:
4861 P->SuppressSpecifiers = Value;
4862 return;
4863 case CXPrintingPolicy_SuppressTagKeyword:
4864 P->SuppressTagKeyword = Value;
4865 return;
4866 case CXPrintingPolicy_IncludeTagDefinition:
4867 P->IncludeTagDefinition = Value;
4868 return;
4869 case CXPrintingPolicy_SuppressScope:
4870 P->SuppressScope = Value;
4871 return;
4872 case CXPrintingPolicy_SuppressUnwrittenScope:
4873 P->SuppressUnwrittenScope = Value;
4874 return;
4875 case CXPrintingPolicy_SuppressInitializers:
4876 P->SuppressInitializers = Value;
4877 return;
4878 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4879 P->ConstantArraySizeAsWritten = Value;
4880 return;
4881 case CXPrintingPolicy_AnonymousTagLocations:
4882 P->AnonymousTagLocations = Value;
4883 return;
4884 case CXPrintingPolicy_SuppressStrongLifetime:
4885 P->SuppressStrongLifetime = Value;
4886 return;
4887 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4888 P->SuppressLifetimeQualifiers = Value;
4889 return;
4890 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4891 P->SuppressTemplateArgsInCXXConstructors = Value;
4892 return;
4893 case CXPrintingPolicy_Bool:
4894 P->Bool = Value;
4895 return;
4896 case CXPrintingPolicy_Restrict:
4897 P->Restrict = Value;
4898 return;
4899 case CXPrintingPolicy_Alignof:
4900 P->Alignof = Value;
4901 return;
4902 case CXPrintingPolicy_UnderscoreAlignof:
4903 P->UnderscoreAlignof = Value;
4904 return;
4905 case CXPrintingPolicy_UseVoidForZeroParams:
4906 P->UseVoidForZeroParams = Value;
4907 return;
4908 case CXPrintingPolicy_TerseOutput:
4909 P->TerseOutput = Value;
4910 return;
4911 case CXPrintingPolicy_PolishForDeclaration:
4912 P->PolishForDeclaration = Value;
4913 return;
4914 case CXPrintingPolicy_Half:
4915 P->Half = Value;
4916 return;
4917 case CXPrintingPolicy_MSWChar:
4918 P->MSWChar = Value;
4919 return;
4920 case CXPrintingPolicy_IncludeNewlines:
4921 P->IncludeNewlines = Value;
4922 return;
4923 case CXPrintingPolicy_MSVCFormatting:
4924 P->MSVCFormatting = Value;
4925 return;
4926 case CXPrintingPolicy_ConstantsAsWritten:
4927 P->ConstantsAsWritten = Value;
4928 return;
4929 case CXPrintingPolicy_SuppressImplicitBase:
4930 P->SuppressImplicitBase = Value;
4931 return;
4932 case CXPrintingPolicy_FullyQualifiedName:
4933 P->FullyQualifiedName = Value;
4934 return;
4935 }
4936
4937 assert(false && "Invalid CXPrintingPolicyProperty");
4938}
4939
4940CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4941 if (clang_Cursor_isNull(C))
4942 return cxstring::createEmpty();
4943
4944 if (clang_isDeclaration(C.kind)) {
4945 const Decl *D = getCursorDecl(C);
4946 if (!D)
4947 return cxstring::createEmpty();
4948
4949 SmallString<128> Str;
4950 llvm::raw_svector_ostream OS(Str);
4951 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4952 D->print(OS, UserPolicy ? *UserPolicy
4953 : getCursorContext(C).getPrintingPolicy());
4954
4955 return cxstring::createDup(OS.str());
4956 }
4957
4958 return cxstring::createEmpty();
4959}
4960
Guy Benyei11169dd2012-12-18 14:30:41 +00004961CXString clang_getCursorDisplayName(CXCursor C) {
4962 if (!clang_isDeclaration(C.kind))
4963 return clang_getCursorSpelling(C);
4964
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004965 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004966 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004967 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004968
4969 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004970 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004971 D = FunTmpl->getTemplatedDecl();
4972
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004973 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 SmallString<64> Str;
4975 llvm::raw_svector_ostream OS(Str);
4976 OS << *Function;
4977 if (Function->getPrimaryTemplate())
4978 OS << "<>";
4979 OS << "(";
4980 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4981 if (I)
4982 OS << ", ";
4983 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4984 }
4985
4986 if (Function->isVariadic()) {
4987 if (Function->getNumParams())
4988 OS << ", ";
4989 OS << "...";
4990 }
4991 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004992 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 }
4994
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004995 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004996 SmallString<64> Str;
4997 llvm::raw_svector_ostream OS(Str);
4998 OS << *ClassTemplate;
4999 OS << "<";
5000 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5001 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5002 if (I)
5003 OS << ", ";
5004
5005 NamedDecl *Param = Params->getParam(I);
5006 if (Param->getIdentifier()) {
5007 OS << Param->getIdentifier()->getName();
5008 continue;
5009 }
5010
5011 // There is no parameter name, which makes this tricky. Try to come up
5012 // with something useful that isn't too long.
5013 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5014 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
5015 else if (NonTypeTemplateParmDecl *NTTP
5016 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5017 OS << NTTP->getType().getAsString(Policy);
5018 else
5019 OS << "template<...> class";
5020 }
5021
5022 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005023 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 }
5025
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005026 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5028 // If the type was explicitly written, use that.
5029 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005030 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005031
Benjamin Kramer9170e912013-02-22 15:46:01 +00005032 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 llvm::raw_svector_ostream OS(Str);
5034 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005035 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5036 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005037 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 }
5039
5040 return clang_getCursorSpelling(C);
5041}
5042
5043CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5044 switch (Kind) {
5045 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005094 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005109 case CXCursor_FixedPointLiteral:
5110 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005125 case CXCursor_OMPArraySectionExpr:
5126 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005177 case CXCursor_ObjCAvailabilityCheckExpr:
5178 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005179 case CXCursor_ObjCSelfExpr:
5180 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005207 case CXCursor_BuiltinBitCastExpr:
5208 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005262 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005268 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005270 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005271 case CXCursor_SEHLeaveStmt:
5272 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005273 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005274 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005275 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005276 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005278 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005280 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005282 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005284 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005286 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005288 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005290 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005292 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005294 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005295 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005296 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005298 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005300 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005301 case CXCursor_PackedAttr:
5302 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005303 case CXCursor_PureAttr:
5304 return cxstring::createRef("attribute(pure)");
5305 case CXCursor_ConstAttr:
5306 return cxstring::createRef("attribute(const)");
5307 case CXCursor_NoDuplicateAttr:
5308 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005309 case CXCursor_CUDAConstantAttr:
5310 return cxstring::createRef("attribute(constant)");
5311 case CXCursor_CUDADeviceAttr:
5312 return cxstring::createRef("attribute(device)");
5313 case CXCursor_CUDAGlobalAttr:
5314 return cxstring::createRef("attribute(global)");
5315 case CXCursor_CUDAHostAttr:
5316 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005317 case CXCursor_CUDASharedAttr:
5318 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005319 case CXCursor_VisibilityAttr:
5320 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005321 case CXCursor_DLLExport:
5322 return cxstring::createRef("attribute(dllexport)");
5323 case CXCursor_DLLImport:
5324 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005325 case CXCursor_NSReturnsRetained:
5326 return cxstring::createRef("attribute(ns_returns_retained)");
5327 case CXCursor_NSReturnsNotRetained:
5328 return cxstring::createRef("attribute(ns_returns_not_retained)");
5329 case CXCursor_NSReturnsAutoreleased:
5330 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5331 case CXCursor_NSConsumesSelf:
5332 return cxstring::createRef("attribute(ns_consumes_self)");
5333 case CXCursor_NSConsumed:
5334 return cxstring::createRef("attribute(ns_consumed)");
5335 case CXCursor_ObjCException:
5336 return cxstring::createRef("attribute(objc_exception)");
5337 case CXCursor_ObjCNSObject:
5338 return cxstring::createRef("attribute(NSObject)");
5339 case CXCursor_ObjCIndependentClass:
5340 return cxstring::createRef("attribute(objc_independent_class)");
5341 case CXCursor_ObjCPreciseLifetime:
5342 return cxstring::createRef("attribute(objc_precise_lifetime)");
5343 case CXCursor_ObjCReturnsInnerPointer:
5344 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5345 case CXCursor_ObjCRequiresSuper:
5346 return cxstring::createRef("attribute(objc_requires_super)");
5347 case CXCursor_ObjCRootClass:
5348 return cxstring::createRef("attribute(objc_root_class)");
5349 case CXCursor_ObjCSubclassingRestricted:
5350 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5351 case CXCursor_ObjCExplicitProtocolImpl:
5352 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5353 case CXCursor_ObjCDesignatedInitializer:
5354 return cxstring::createRef("attribute(objc_designated_initializer)");
5355 case CXCursor_ObjCRuntimeVisible:
5356 return cxstring::createRef("attribute(objc_runtime_visible)");
5357 case CXCursor_ObjCBoxable:
5358 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005359 case CXCursor_FlagEnum:
5360 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005362 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005364 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005365 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005366 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005368 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005369 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005370 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005371 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005372 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005374 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005375 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005376 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005378 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005379 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005380 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005381 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005382 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005384 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005385 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005386 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005387 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005388 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005389 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005390 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005391 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005392 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005393 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005394 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005395 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005396 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005397 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005398 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005399 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005400 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005401 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005402 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005403 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005404 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005405 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005406 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005407 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005408 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005409 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005410 return cxstring::createRef("OMPParallelDirective");
5411 case CXCursor_OMPSimdDirective:
5412 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005413 case CXCursor_OMPForDirective:
5414 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005415 case CXCursor_OMPForSimdDirective:
5416 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005417 case CXCursor_OMPSectionsDirective:
5418 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005419 case CXCursor_OMPSectionDirective:
5420 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005421 case CXCursor_OMPSingleDirective:
5422 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005423 case CXCursor_OMPMasterDirective:
5424 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005425 case CXCursor_OMPCriticalDirective:
5426 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005427 case CXCursor_OMPParallelForDirective:
5428 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005429 case CXCursor_OMPParallelForSimdDirective:
5430 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005431 case CXCursor_OMPParallelSectionsDirective:
5432 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005433 case CXCursor_OMPTaskDirective:
5434 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005435 case CXCursor_OMPTaskyieldDirective:
5436 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005437 case CXCursor_OMPBarrierDirective:
5438 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005439 case CXCursor_OMPTaskwaitDirective:
5440 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005441 case CXCursor_OMPTaskgroupDirective:
5442 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005443 case CXCursor_OMPFlushDirective:
5444 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005445 case CXCursor_OMPOrderedDirective:
5446 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005447 case CXCursor_OMPAtomicDirective:
5448 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005449 case CXCursor_OMPTargetDirective:
5450 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005451 case CXCursor_OMPTargetDataDirective:
5452 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005453 case CXCursor_OMPTargetEnterDataDirective:
5454 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005455 case CXCursor_OMPTargetExitDataDirective:
5456 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005457 case CXCursor_OMPTargetParallelDirective:
5458 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005459 case CXCursor_OMPTargetParallelForDirective:
5460 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005461 case CXCursor_OMPTargetUpdateDirective:
5462 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005463 case CXCursor_OMPTeamsDirective:
5464 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005465 case CXCursor_OMPCancellationPointDirective:
5466 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005467 case CXCursor_OMPCancelDirective:
5468 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005469 case CXCursor_OMPTaskLoopDirective:
5470 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005471 case CXCursor_OMPTaskLoopSimdDirective:
5472 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005473 case CXCursor_OMPDistributeDirective:
5474 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005475 case CXCursor_OMPDistributeParallelForDirective:
5476 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005477 case CXCursor_OMPDistributeParallelForSimdDirective:
5478 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005479 case CXCursor_OMPDistributeSimdDirective:
5480 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005481 case CXCursor_OMPTargetParallelForSimdDirective:
5482 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005483 case CXCursor_OMPTargetSimdDirective:
5484 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005485 case CXCursor_OMPTeamsDistributeDirective:
5486 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005487 case CXCursor_OMPTeamsDistributeSimdDirective:
5488 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005489 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5490 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005491 case CXCursor_OMPTeamsDistributeParallelForDirective:
5492 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005493 case CXCursor_OMPTargetTeamsDirective:
5494 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005495 case CXCursor_OMPTargetTeamsDistributeDirective:
5496 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005497 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5498 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005499 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5500 return cxstring::createRef(
5501 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005502 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5503 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005504 case CXCursor_OverloadCandidate:
5505 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005506 case CXCursor_TypeAliasTemplateDecl:
5507 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005508 case CXCursor_StaticAssert:
5509 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005510 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005511 return cxstring::createRef("FriendDecl");
5512 case CXCursor_ConvergentAttr:
5513 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005514 case CXCursor_WarnUnusedAttr:
5515 return cxstring::createRef("attribute(warn_unused)");
5516 case CXCursor_WarnUnusedResultAttr:
5517 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005518 case CXCursor_AlignedAttr:
5519 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005520 }
5521
5522 llvm_unreachable("Unhandled CXCursorKind");
5523}
5524
5525struct GetCursorData {
5526 SourceLocation TokenBeginLoc;
5527 bool PointsAtMacroArgExpansion;
5528 bool VisitedObjCPropertyImplDecl;
5529 SourceLocation VisitedDeclaratorDeclStartLoc;
5530 CXCursor &BestCursor;
5531
5532 GetCursorData(SourceManager &SM,
5533 SourceLocation tokenBegin, CXCursor &outputCursor)
5534 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5535 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5536 VisitedObjCPropertyImplDecl = false;
5537 }
5538};
5539
5540static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5541 CXCursor parent,
5542 CXClientData client_data) {
5543 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5544 CXCursor *BestCursor = &Data->BestCursor;
5545
5546 // If we point inside a macro argument we should provide info of what the
5547 // token is so use the actual cursor, don't replace it with a macro expansion
5548 // cursor.
5549 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5550 return CXChildVisit_Recurse;
5551
5552 if (clang_isDeclaration(cursor.kind)) {
5553 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005554 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005555 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5556 if (MD->isImplicit())
5557 return CXChildVisit_Break;
5558
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005559 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005560 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5561 // Check that when we have multiple @class references in the same line,
5562 // that later ones do not override the previous ones.
5563 // If we have:
5564 // @class Foo, Bar;
5565 // source ranges for both start at '@', so 'Bar' will end up overriding
5566 // 'Foo' even though the cursor location was at 'Foo'.
5567 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5568 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005569 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005570 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5571 if (PrevID != ID &&
5572 !PrevID->isThisDeclarationADefinition() &&
5573 !ID->isThisDeclarationADefinition())
5574 return CXChildVisit_Break;
5575 }
5576
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005577 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005578 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5579 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5580 // Check that when we have multiple declarators in the same line,
5581 // that later ones do not override the previous ones.
5582 // If we have:
5583 // int Foo, Bar;
5584 // source ranges for both start at 'int', so 'Bar' will end up overriding
5585 // 'Foo' even though the cursor location was at 'Foo'.
5586 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5587 return CXChildVisit_Break;
5588 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5589
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005590 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005591 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5592 (void)PropImp;
5593 // Check that when we have multiple @synthesize in the same line,
5594 // that later ones do not override the previous ones.
5595 // If we have:
5596 // @synthesize Foo, Bar;
5597 // source ranges for both start at '@', so 'Bar' will end up overriding
5598 // 'Foo' even though the cursor location was at 'Foo'.
5599 if (Data->VisitedObjCPropertyImplDecl)
5600 return CXChildVisit_Break;
5601 Data->VisitedObjCPropertyImplDecl = true;
5602 }
5603 }
5604
5605 if (clang_isExpression(cursor.kind) &&
5606 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005607 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005608 // Avoid having the cursor of an expression replace the declaration cursor
5609 // when the expression source range overlaps the declaration range.
5610 // This can happen for C++ constructor expressions whose range generally
5611 // include the variable declaration, e.g.:
5612 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5613 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5614 D->getLocation() == Data->TokenBeginLoc)
5615 return CXChildVisit_Break;
5616 }
5617 }
5618
5619 // If our current best cursor is the construction of a temporary object,
5620 // don't replace that cursor with a type reference, because we want
5621 // clang_getCursor() to point at the constructor.
5622 if (clang_isExpression(BestCursor->kind) &&
5623 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5624 cursor.kind == CXCursor_TypeRef) {
5625 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5626 // as having the actual point on the type reference.
5627 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5628 return CXChildVisit_Recurse;
5629 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005630
5631 // If we already have an Objective-C superclass reference, don't
5632 // update it further.
5633 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5634 return CXChildVisit_Break;
5635
Guy Benyei11169dd2012-12-18 14:30:41 +00005636 *BestCursor = cursor;
5637 return CXChildVisit_Recurse;
5638}
5639
5640CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005641 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005642 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005643 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005644 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005645
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005646 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005647 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5648
5649 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5650 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5651
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005652 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005653 CXFile SearchFile;
5654 unsigned SearchLine, SearchColumn;
5655 CXFile ResultFile;
5656 unsigned ResultLine, ResultColumn;
5657 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5658 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5659 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005660
5661 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5662 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005663 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005664 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005665 SearchFileName = clang_getFileName(SearchFile);
5666 ResultFileName = clang_getFileName(ResultFile);
5667 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5668 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005669 *Log << llvm::format("(%s:%d:%d) = %s",
5670 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5671 clang_getCString(KindSpelling))
5672 << llvm::format("(%s:%d:%d):%s%s",
5673 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5674 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005675 clang_disposeString(SearchFileName);
5676 clang_disposeString(ResultFileName);
5677 clang_disposeString(KindSpelling);
5678 clang_disposeString(USR);
5679
5680 CXCursor Definition = clang_getCursorDefinition(Result);
5681 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5682 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5683 CXString DefinitionKindSpelling
5684 = clang_getCursorKindSpelling(Definition.kind);
5685 CXFile DefinitionFile;
5686 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005687 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005688 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005689 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005690 *Log << llvm::format(" -> %s(%s:%d:%d)",
5691 clang_getCString(DefinitionKindSpelling),
5692 clang_getCString(DefinitionFileName),
5693 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005694 clang_disposeString(DefinitionFileName);
5695 clang_disposeString(DefinitionKindSpelling);
5696 }
5697 }
5698
5699 return Result;
5700}
5701
5702CXCursor clang_getNullCursor(void) {
5703 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5704}
5705
5706unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005707 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5708 // can't set consistently. For example, when visiting a DeclStmt we will set
5709 // it but we don't set it on the result of clang_getCursorDefinition for
5710 // a reference of the same declaration.
5711 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5712 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5713 // to provide that kind of info.
5714 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005715 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005716 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005717 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005718
Guy Benyei11169dd2012-12-18 14:30:41 +00005719 return X == Y;
5720}
5721
5722unsigned clang_hashCursor(CXCursor C) {
5723 unsigned Index = 0;
5724 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5725 Index = 1;
5726
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005727 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005728 std::make_pair(C.kind, C.data[Index]));
5729}
5730
5731unsigned clang_isInvalid(enum CXCursorKind K) {
5732 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5733}
5734
5735unsigned clang_isDeclaration(enum CXCursorKind K) {
5736 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005737 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5738}
5739
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005740unsigned clang_isInvalidDeclaration(CXCursor C) {
5741 if (clang_isDeclaration(C.kind)) {
5742 if (const Decl *D = getCursorDecl(C))
5743 return D->isInvalidDecl();
5744 }
5745
5746 return 0;
5747}
5748
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005749unsigned clang_isReference(enum CXCursorKind K) {
5750 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5751}
Guy Benyei11169dd2012-12-18 14:30:41 +00005752
5753unsigned clang_isExpression(enum CXCursorKind K) {
5754 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5755}
5756
5757unsigned clang_isStatement(enum CXCursorKind K) {
5758 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5759}
5760
5761unsigned clang_isAttribute(enum CXCursorKind K) {
5762 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5763}
5764
5765unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5766 return K == CXCursor_TranslationUnit;
5767}
5768
5769unsigned clang_isPreprocessing(enum CXCursorKind K) {
5770 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5771}
5772
5773unsigned clang_isUnexposed(enum CXCursorKind K) {
5774 switch (K) {
5775 case CXCursor_UnexposedDecl:
5776 case CXCursor_UnexposedExpr:
5777 case CXCursor_UnexposedStmt:
5778 case CXCursor_UnexposedAttr:
5779 return true;
5780 default:
5781 return false;
5782 }
5783}
5784
5785CXCursorKind clang_getCursorKind(CXCursor C) {
5786 return C.kind;
5787}
5788
5789CXSourceLocation clang_getCursorLocation(CXCursor C) {
5790 if (clang_isReference(C.kind)) {
5791 switch (C.kind) {
5792 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005793 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005794 = getCursorObjCSuperClassRef(C);
5795 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5796 }
5797
5798 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005799 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005800 = getCursorObjCProtocolRef(C);
5801 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5802 }
5803
5804 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005805 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005806 = getCursorObjCClassRef(C);
5807 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5808 }
5809
5810 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005811 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005812 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5813 }
5814
5815 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005816 std::pair<const TemplateDecl *, SourceLocation> P =
5817 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005818 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5819 }
5820
5821 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005822 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005823 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5824 }
5825
5826 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005827 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005828 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5829 }
5830
5831 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005832 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005833 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5834 }
5835
5836 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005837 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005838 if (!BaseSpec)
5839 return clang_getNullLocation();
5840
5841 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5842 return cxloc::translateSourceLocation(getCursorContext(C),
5843 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005844
Guy Benyei11169dd2012-12-18 14:30:41 +00005845 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005846 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005847 }
5848
5849 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005850 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005851 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5852 }
5853
5854 case CXCursor_OverloadedDeclRef:
5855 return cxloc::translateSourceLocation(getCursorContext(C),
5856 getCursorOverloadedDeclRef(C).second);
5857
5858 default:
5859 // FIXME: Need a way to enumerate all non-reference cases.
5860 llvm_unreachable("Missed a reference kind");
5861 }
5862 }
5863
5864 if (clang_isExpression(C.kind))
5865 return cxloc::translateSourceLocation(getCursorContext(C),
5866 getLocationFromExpr(getCursorExpr(C)));
5867
5868 if (clang_isStatement(C.kind))
5869 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005870 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005871
5872 if (C.kind == CXCursor_PreprocessingDirective) {
5873 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5874 return cxloc::translateSourceLocation(getCursorContext(C), L);
5875 }
5876
5877 if (C.kind == CXCursor_MacroExpansion) {
5878 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005879 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005880 return cxloc::translateSourceLocation(getCursorContext(C), L);
5881 }
5882
5883 if (C.kind == CXCursor_MacroDefinition) {
5884 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5885 return cxloc::translateSourceLocation(getCursorContext(C), L);
5886 }
5887
5888 if (C.kind == CXCursor_InclusionDirective) {
5889 SourceLocation L
5890 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5891 return cxloc::translateSourceLocation(getCursorContext(C), L);
5892 }
5893
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005894 if (clang_isAttribute(C.kind)) {
5895 SourceLocation L
5896 = cxcursor::getCursorAttr(C)->getLocation();
5897 return cxloc::translateSourceLocation(getCursorContext(C), L);
5898 }
5899
Guy Benyei11169dd2012-12-18 14:30:41 +00005900 if (!clang_isDeclaration(C.kind))
5901 return clang_getNullLocation();
5902
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005903 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 if (!D)
5905 return clang_getNullLocation();
5906
5907 SourceLocation Loc = D->getLocation();
5908 // FIXME: Multiple variables declared in a single declaration
5909 // currently lack the information needed to correctly determine their
5910 // ranges when accounting for the type-specifier. We use context
5911 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5912 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005913 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005914 if (!cxcursor::isFirstInDeclGroup(C))
5915 Loc = VD->getLocation();
5916 }
5917
5918 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005919 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005920 Loc = MD->getSelectorStartLoc();
5921
5922 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5923}
5924
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005925} // end extern "C"
5926
Guy Benyei11169dd2012-12-18 14:30:41 +00005927CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5928 assert(TU);
5929
5930 // Guard against an invalid SourceLocation, or we may assert in one
5931 // of the following calls.
5932 if (SLoc.isInvalid())
5933 return clang_getNullCursor();
5934
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005935 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005936
5937 // Translate the given source location to make it point at the beginning of
5938 // the token under the cursor.
5939 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5940 CXXUnit->getASTContext().getLangOpts());
5941
5942 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5943 if (SLoc.isValid()) {
5944 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5945 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5946 /*VisitPreprocessorLast=*/true,
5947 /*VisitIncludedEntities=*/false,
5948 SourceLocation(SLoc));
5949 CursorVis.visitFileRegion();
5950 }
5951
5952 return Result;
5953}
5954
5955static SourceRange getRawCursorExtent(CXCursor C) {
5956 if (clang_isReference(C.kind)) {
5957 switch (C.kind) {
5958 case CXCursor_ObjCSuperClassRef:
5959 return getCursorObjCSuperClassRef(C).second;
5960
5961 case CXCursor_ObjCProtocolRef:
5962 return getCursorObjCProtocolRef(C).second;
5963
5964 case CXCursor_ObjCClassRef:
5965 return getCursorObjCClassRef(C).second;
5966
5967 case CXCursor_TypeRef:
5968 return getCursorTypeRef(C).second;
5969
5970 case CXCursor_TemplateRef:
5971 return getCursorTemplateRef(C).second;
5972
5973 case CXCursor_NamespaceRef:
5974 return getCursorNamespaceRef(C).second;
5975
5976 case CXCursor_MemberRef:
5977 return getCursorMemberRef(C).second;
5978
5979 case CXCursor_CXXBaseSpecifier:
5980 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5981
5982 case CXCursor_LabelRef:
5983 return getCursorLabelRef(C).second;
5984
5985 case CXCursor_OverloadedDeclRef:
5986 return getCursorOverloadedDeclRef(C).second;
5987
5988 case CXCursor_VariableRef:
5989 return getCursorVariableRef(C).second;
5990
5991 default:
5992 // FIXME: Need a way to enumerate all non-reference cases.
5993 llvm_unreachable("Missed a reference kind");
5994 }
5995 }
5996
5997 if (clang_isExpression(C.kind))
5998 return getCursorExpr(C)->getSourceRange();
5999
6000 if (clang_isStatement(C.kind))
6001 return getCursorStmt(C)->getSourceRange();
6002
6003 if (clang_isAttribute(C.kind))
6004 return getCursorAttr(C)->getRange();
6005
6006 if (C.kind == CXCursor_PreprocessingDirective)
6007 return cxcursor::getCursorPreprocessingDirective(C);
6008
6009 if (C.kind == CXCursor_MacroExpansion) {
6010 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006011 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006012 return TU->mapRangeFromPreamble(Range);
6013 }
6014
6015 if (C.kind == CXCursor_MacroDefinition) {
6016 ASTUnit *TU = getCursorASTUnit(C);
6017 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6018 return TU->mapRangeFromPreamble(Range);
6019 }
6020
6021 if (C.kind == CXCursor_InclusionDirective) {
6022 ASTUnit *TU = getCursorASTUnit(C);
6023 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6024 return TU->mapRangeFromPreamble(Range);
6025 }
6026
6027 if (C.kind == CXCursor_TranslationUnit) {
6028 ASTUnit *TU = getCursorASTUnit(C);
6029 FileID MainID = TU->getSourceManager().getMainFileID();
6030 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6031 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6032 return SourceRange(Start, End);
6033 }
6034
6035 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006036 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 if (!D)
6038 return SourceRange();
6039
6040 SourceRange R = D->getSourceRange();
6041 // FIXME: Multiple variables declared in a single declaration
6042 // currently lack the information needed to correctly determine their
6043 // ranges when accounting for the type-specifier. We use context
6044 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6045 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006046 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 if (!cxcursor::isFirstInDeclGroup(C))
6048 R.setBegin(VD->getLocation());
6049 }
6050 return R;
6051 }
6052 return SourceRange();
6053}
6054
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006055/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006056/// the decl-specifier-seq for declarations.
6057static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6058 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006059 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006060 if (!D)
6061 return SourceRange();
6062
6063 SourceRange R = D->getSourceRange();
6064
6065 // Adjust the start of the location for declarations preceded by
6066 // declaration specifiers.
6067 SourceLocation StartLoc;
6068 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6069 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006070 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006071 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006072 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006073 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 }
6075
6076 if (StartLoc.isValid() && R.getBegin().isValid() &&
6077 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6078 R.setBegin(StartLoc);
6079
6080 // FIXME: Multiple variables declared in a single declaration
6081 // currently lack the information needed to correctly determine their
6082 // ranges when accounting for the type-specifier. We use context
6083 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6084 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006085 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006086 if (!cxcursor::isFirstInDeclGroup(C))
6087 R.setBegin(VD->getLocation());
6088 }
6089
6090 return R;
6091 }
6092
6093 return getRawCursorExtent(C);
6094}
6095
Guy Benyei11169dd2012-12-18 14:30:41 +00006096CXSourceRange clang_getCursorExtent(CXCursor C) {
6097 SourceRange R = getRawCursorExtent(C);
6098 if (R.isInvalid())
6099 return clang_getNullRange();
6100
6101 return cxloc::translateSourceRange(getCursorContext(C), R);
6102}
6103
6104CXCursor clang_getCursorReferenced(CXCursor C) {
6105 if (clang_isInvalid(C.kind))
6106 return clang_getNullCursor();
6107
6108 CXTranslationUnit tu = getCursorTU(C);
6109 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006110 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006111 if (!D)
6112 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006113 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006115 if (const ObjCPropertyImplDecl *PropImpl =
6116 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006117 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6118 return MakeCXCursor(Property, tu);
6119
6120 return C;
6121 }
6122
6123 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006124 const Expr *E = getCursorExpr(C);
6125 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006126 if (D) {
6127 CXCursor declCursor = MakeCXCursor(D, tu);
6128 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6129 declCursor);
6130 return declCursor;
6131 }
6132
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006133 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006134 return MakeCursorOverloadedDeclRef(Ovl, tu);
6135
6136 return clang_getNullCursor();
6137 }
6138
6139 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006140 const Stmt *S = getCursorStmt(C);
6141 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006142 if (LabelDecl *label = Goto->getLabel())
6143 if (LabelStmt *labelS = label->getStmt())
6144 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6145
6146 return clang_getNullCursor();
6147 }
Richard Smith66a81862015-05-04 02:25:31 +00006148
Guy Benyei11169dd2012-12-18 14:30:41 +00006149 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006150 if (const MacroDefinitionRecord *Def =
6151 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006152 return MakeMacroDefinitionCursor(Def, tu);
6153 }
6154
6155 if (!clang_isReference(C.kind))
6156 return clang_getNullCursor();
6157
6158 switch (C.kind) {
6159 case CXCursor_ObjCSuperClassRef:
6160 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6161
6162 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006163 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6164 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 return MakeCXCursor(Def, tu);
6166
6167 return MakeCXCursor(Prot, tu);
6168 }
6169
6170 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006171 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6172 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006173 return MakeCXCursor(Def, tu);
6174
6175 return MakeCXCursor(Class, tu);
6176 }
6177
6178 case CXCursor_TypeRef:
6179 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6180
6181 case CXCursor_TemplateRef:
6182 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6183
6184 case CXCursor_NamespaceRef:
6185 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6186
6187 case CXCursor_MemberRef:
6188 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6189
6190 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006191 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6193 tu ));
6194 }
6195
6196 case CXCursor_LabelRef:
6197 // FIXME: We end up faking the "parent" declaration here because we
6198 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006199 return MakeCXCursor(getCursorLabelRef(C).first,
6200 cxtu::getASTUnit(tu)->getASTContext()
6201 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006202 tu);
6203
6204 case CXCursor_OverloadedDeclRef:
6205 return C;
6206
6207 case CXCursor_VariableRef:
6208 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6209
6210 default:
6211 // We would prefer to enumerate all non-reference cursor kinds here.
6212 llvm_unreachable("Unhandled reference cursor kind");
6213 }
6214}
6215
6216CXCursor clang_getCursorDefinition(CXCursor C) {
6217 if (clang_isInvalid(C.kind))
6218 return clang_getNullCursor();
6219
6220 CXTranslationUnit TU = getCursorTU(C);
6221
6222 bool WasReference = false;
6223 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6224 C = clang_getCursorReferenced(C);
6225 WasReference = true;
6226 }
6227
6228 if (C.kind == CXCursor_MacroExpansion)
6229 return clang_getCursorReferenced(C);
6230
6231 if (!clang_isDeclaration(C.kind))
6232 return clang_getNullCursor();
6233
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006234 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 if (!D)
6236 return clang_getNullCursor();
6237
6238 switch (D->getKind()) {
6239 // Declaration kinds that don't really separate the notions of
6240 // declaration and definition.
6241 case Decl::Namespace:
6242 case Decl::Typedef:
6243 case Decl::TypeAlias:
6244 case Decl::TypeAliasTemplate:
6245 case Decl::TemplateTypeParm:
6246 case Decl::EnumConstant:
6247 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006248 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006249 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006250 case Decl::IndirectField:
6251 case Decl::ObjCIvar:
6252 case Decl::ObjCAtDefsField:
6253 case Decl::ImplicitParam:
6254 case Decl::ParmVar:
6255 case Decl::NonTypeTemplateParm:
6256 case Decl::TemplateTemplateParm:
6257 case Decl::ObjCCategoryImpl:
6258 case Decl::ObjCImplementation:
6259 case Decl::AccessSpec:
6260 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006261 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006262 case Decl::ObjCPropertyImpl:
6263 case Decl::FileScopeAsm:
6264 case Decl::StaticAssert:
6265 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006266 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006267 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006268 case Decl::Label: // FIXME: Is this right??
6269 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006270 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006271 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006272 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006273 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006274 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006275 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006276 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006277 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006278 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006279 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006280 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006281 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006282 case Decl::Concept:
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 return C;
6284
6285 // Declaration kinds that don't make any sense here, but are
6286 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006287 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006288 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006289 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 break;
6291
6292 // Declaration kinds for which the definition is not resolvable.
6293 case Decl::UnresolvedUsingTypename:
6294 case Decl::UnresolvedUsingValue:
6295 break;
6296
6297 case Decl::UsingDirective:
6298 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6299 TU);
6300
6301 case Decl::NamespaceAlias:
6302 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6303
6304 case Decl::Enum:
6305 case Decl::Record:
6306 case Decl::CXXRecord:
6307 case Decl::ClassTemplateSpecialization:
6308 case Decl::ClassTemplatePartialSpecialization:
6309 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6310 return MakeCXCursor(Def, TU);
6311 return clang_getNullCursor();
6312
6313 case Decl::Function:
6314 case Decl::CXXMethod:
6315 case Decl::CXXConstructor:
6316 case Decl::CXXDestructor:
6317 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006318 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006319 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006320 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006321 return clang_getNullCursor();
6322 }
6323
Larisse Voufo39a1e502013-08-06 01:03:05 +00006324 case Decl::Var:
6325 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006326 case Decl::VarTemplatePartialSpecialization:
6327 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006328 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006329 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 return MakeCXCursor(Def, TU);
6331 return clang_getNullCursor();
6332 }
6333
6334 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006335 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006336 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6337 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6338 return clang_getNullCursor();
6339 }
6340
6341 case Decl::ClassTemplate: {
6342 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6343 ->getDefinition())
6344 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6345 TU);
6346 return clang_getNullCursor();
6347 }
6348
Larisse Voufo39a1e502013-08-06 01:03:05 +00006349 case Decl::VarTemplate: {
6350 if (VarDecl *Def =
6351 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6352 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6353 return clang_getNullCursor();
6354 }
6355
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 case Decl::Using:
6357 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6358 D->getLocation(), TU);
6359
6360 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006361 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006362 return clang_getCursorDefinition(
6363 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6364 TU));
6365
6366 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006367 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006368 if (Method->isThisDeclarationADefinition())
6369 return C;
6370
6371 // Dig out the method definition in the associated
6372 // @implementation, if we have it.
6373 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006374 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6376 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6377 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6378 Method->isInstanceMethod()))
6379 if (Def->isThisDeclarationADefinition())
6380 return MakeCXCursor(Def, TU);
6381
6382 return clang_getNullCursor();
6383 }
6384
6385 case Decl::ObjCCategory:
6386 if (ObjCCategoryImplDecl *Impl
6387 = cast<ObjCCategoryDecl>(D)->getImplementation())
6388 return MakeCXCursor(Impl, TU);
6389 return clang_getNullCursor();
6390
6391 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006392 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006393 return MakeCXCursor(Def, TU);
6394 return clang_getNullCursor();
6395
6396 case Decl::ObjCInterface: {
6397 // There are two notions of a "definition" for an Objective-C
6398 // class: the interface and its implementation. When we resolved a
6399 // reference to an Objective-C class, produce the @interface as
6400 // the definition; when we were provided with the interface,
6401 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006402 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006404 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006405 return MakeCXCursor(Def, TU);
6406 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6407 return MakeCXCursor(Impl, TU);
6408 return clang_getNullCursor();
6409 }
6410
6411 case Decl::ObjCProperty:
6412 // FIXME: We don't really know where to find the
6413 // ObjCPropertyImplDecls that implement this property.
6414 return clang_getNullCursor();
6415
6416 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006417 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006418 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006419 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006420 return MakeCXCursor(Def, TU);
6421
6422 return clang_getNullCursor();
6423
6424 case Decl::Friend:
6425 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6426 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6427 return clang_getNullCursor();
6428
6429 case Decl::FriendTemplate:
6430 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6431 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6432 return clang_getNullCursor();
6433 }
6434
6435 return clang_getNullCursor();
6436}
6437
6438unsigned clang_isCursorDefinition(CXCursor C) {
6439 if (!clang_isDeclaration(C.kind))
6440 return 0;
6441
6442 return clang_getCursorDefinition(C) == C;
6443}
6444
6445CXCursor clang_getCanonicalCursor(CXCursor C) {
6446 if (!clang_isDeclaration(C.kind))
6447 return C;
6448
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006449 if (const Decl *D = getCursorDecl(C)) {
6450 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6452 return MakeCXCursor(CatD, getCursorTU(C));
6453
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006454 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6455 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006456 return MakeCXCursor(IFD, getCursorTU(C));
6457
6458 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6459 }
6460
6461 return C;
6462}
6463
6464int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6465 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6466}
6467
6468unsigned clang_getNumOverloadedDecls(CXCursor C) {
6469 if (C.kind != CXCursor_OverloadedDeclRef)
6470 return 0;
6471
6472 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006473 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006474 return E->getNumDecls();
6475
6476 if (OverloadedTemplateStorage *S
6477 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6478 return S->size();
6479
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006480 const Decl *D = Storage.get<const Decl *>();
6481 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006482 return Using->shadow_size();
6483
6484 return 0;
6485}
6486
6487CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6488 if (cursor.kind != CXCursor_OverloadedDeclRef)
6489 return clang_getNullCursor();
6490
6491 if (index >= clang_getNumOverloadedDecls(cursor))
6492 return clang_getNullCursor();
6493
6494 CXTranslationUnit TU = getCursorTU(cursor);
6495 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006496 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 return MakeCXCursor(E->decls_begin()[index], TU);
6498
6499 if (OverloadedTemplateStorage *S
6500 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6501 return MakeCXCursor(S->begin()[index], TU);
6502
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006503 const Decl *D = Storage.get<const Decl *>();
6504 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006505 // FIXME: This is, unfortunately, linear time.
6506 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6507 std::advance(Pos, index);
6508 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6509 }
6510
6511 return clang_getNullCursor();
6512}
6513
6514void clang_getDefinitionSpellingAndExtent(CXCursor C,
6515 const char **startBuf,
6516 const char **endBuf,
6517 unsigned *startLine,
6518 unsigned *startColumn,
6519 unsigned *endLine,
6520 unsigned *endColumn) {
6521 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006522 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6524
6525 SourceManager &SM = FD->getASTContext().getSourceManager();
6526 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6527 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6528 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6529 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6530 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6531 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6532}
6533
6534
6535CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6536 unsigned PieceIndex) {
6537 RefNamePieces Pieces;
6538
6539 switch (C.kind) {
6540 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006541 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006542 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6543 E->getQualifierLoc().getSourceRange());
6544 break;
6545
6546 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006547 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6548 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6549 Pieces =
6550 buildPieces(NameFlags, false, E->getNameInfo(),
6551 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6552 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 break;
6554
6555 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006556 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006557 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006558 const Expr *Callee = OCE->getCallee();
6559 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006560 Callee = ICE->getSubExpr();
6561
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006562 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006563 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6564 DRE->getQualifierLoc().getSourceRange());
6565 }
6566 break;
6567
6568 default:
6569 break;
6570 }
6571
6572 if (Pieces.empty()) {
6573 if (PieceIndex == 0)
6574 return clang_getCursorExtent(C);
6575 } else if (PieceIndex < Pieces.size()) {
6576 SourceRange R = Pieces[PieceIndex];
6577 if (R.isValid())
6578 return cxloc::translateSourceRange(getCursorContext(C), R);
6579 }
6580
6581 return clang_getNullRange();
6582}
6583
6584void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006585 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6586 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006587}
6588
6589void clang_executeOnThread(void (*fn)(void*), void *user_data,
6590 unsigned stack_size) {
6591 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6592}
6593
Guy Benyei11169dd2012-12-18 14:30:41 +00006594//===----------------------------------------------------------------------===//
6595// Token-based Operations.
6596//===----------------------------------------------------------------------===//
6597
6598/* CXToken layout:
6599 * int_data[0]: a CXTokenKind
6600 * int_data[1]: starting token location
6601 * int_data[2]: token length
6602 * int_data[3]: reserved
6603 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6604 * otherwise unused.
6605 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006606CXTokenKind clang_getTokenKind(CXToken CXTok) {
6607 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6608}
6609
6610CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6611 switch (clang_getTokenKind(CXTok)) {
6612 case CXToken_Identifier:
6613 case CXToken_Keyword:
6614 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006615 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006616 ->getNameStart());
6617
6618 case CXToken_Literal: {
6619 // We have stashed the starting pointer in the ptr_data field. Use it.
6620 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006621 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006622 }
6623
6624 case CXToken_Punctuation:
6625 case CXToken_Comment:
6626 break;
6627 }
6628
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006629 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006630 LOG_BAD_TU(TU);
6631 return cxstring::createEmpty();
6632 }
6633
Guy Benyei11169dd2012-12-18 14:30:41 +00006634 // We have to find the starting buffer pointer the hard way, by
6635 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006636 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006637 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006638 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006639
6640 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6641 std::pair<FileID, unsigned> LocInfo
6642 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6643 bool Invalid = false;
6644 StringRef Buffer
6645 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6646 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006647 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006648
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006649 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006650}
6651
6652CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006653 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006654 LOG_BAD_TU(TU);
6655 return clang_getNullLocation();
6656 }
6657
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006658 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006659 if (!CXXUnit)
6660 return clang_getNullLocation();
6661
6662 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6663 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6664}
6665
6666CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006667 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006668 LOG_BAD_TU(TU);
6669 return clang_getNullRange();
6670 }
6671
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006672 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006673 if (!CXXUnit)
6674 return clang_getNullRange();
6675
6676 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6677 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6678}
6679
6680static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6681 SmallVectorImpl<CXToken> &CXTokens) {
6682 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6683 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006684 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006685 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006686 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006687
6688 // Cannot tokenize across files.
6689 if (BeginLocInfo.first != EndLocInfo.first)
6690 return;
6691
6692 // Create a lexer
6693 bool Invalid = false;
6694 StringRef Buffer
6695 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6696 if (Invalid)
6697 return;
6698
6699 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6700 CXXUnit->getASTContext().getLangOpts(),
6701 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6702 Lex.SetCommentRetentionState(true);
6703
6704 // Lex tokens until we hit the end of the range.
6705 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6706 Token Tok;
6707 bool previousWasAt = false;
6708 do {
6709 // Lex the next token
6710 Lex.LexFromRawLexer(Tok);
6711 if (Tok.is(tok::eof))
6712 break;
6713
6714 // Initialize the CXToken.
6715 CXToken CXTok;
6716
6717 // - Common fields
6718 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6719 CXTok.int_data[2] = Tok.getLength();
6720 CXTok.int_data[3] = 0;
6721
6722 // - Kind-specific fields
6723 if (Tok.isLiteral()) {
6724 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006725 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 } else if (Tok.is(tok::raw_identifier)) {
6727 // Lookup the identifier to determine whether we have a keyword.
6728 IdentifierInfo *II
6729 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6730
6731 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6732 CXTok.int_data[0] = CXToken_Keyword;
6733 }
6734 else {
6735 CXTok.int_data[0] = Tok.is(tok::identifier)
6736 ? CXToken_Identifier
6737 : CXToken_Keyword;
6738 }
6739 CXTok.ptr_data = II;
6740 } else if (Tok.is(tok::comment)) {
6741 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006742 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006743 } else {
6744 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006745 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006746 }
6747 CXTokens.push_back(CXTok);
6748 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006749 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006750}
6751
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006752CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6753 LOG_FUNC_SECTION {
6754 *Log << TU << ' ' << Location;
6755 }
6756
6757 if (isNotUsableTU(TU)) {
6758 LOG_BAD_TU(TU);
6759 return NULL;
6760 }
6761
6762 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6763 if (!CXXUnit)
6764 return NULL;
6765
6766 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6767 if (Begin.isInvalid())
6768 return NULL;
6769 SourceManager &SM = CXXUnit->getSourceManager();
6770 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6771 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6772
6773 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6774
6775 SmallVector<CXToken, 32> CXTokens;
6776 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6777
6778 if (CXTokens.empty())
6779 return NULL;
6780
6781 CXTokens.resize(1);
6782 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6783
6784 memmove(Token, CXTokens.data(), sizeof(CXToken));
6785 return Token;
6786}
6787
Guy Benyei11169dd2012-12-18 14:30:41 +00006788void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6789 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006790 LOG_FUNC_SECTION {
6791 *Log << TU << ' ' << Range;
6792 }
6793
Guy Benyei11169dd2012-12-18 14:30:41 +00006794 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006795 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006796 if (NumTokens)
6797 *NumTokens = 0;
6798
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006799 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006800 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006801 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006802 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006803
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006804 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006805 if (!CXXUnit || !Tokens || !NumTokens)
6806 return;
6807
6808 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6809
6810 SourceRange R = cxloc::translateCXSourceRange(Range);
6811 if (R.isInvalid())
6812 return;
6813
6814 SmallVector<CXToken, 32> CXTokens;
6815 getTokens(CXXUnit, R, CXTokens);
6816
6817 if (CXTokens.empty())
6818 return;
6819
Serge Pavlov52525732018-02-21 02:02:39 +00006820 *Tokens = static_cast<CXToken *>(
6821 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006822 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6823 *NumTokens = CXTokens.size();
6824}
6825
6826void clang_disposeTokens(CXTranslationUnit TU,
6827 CXToken *Tokens, unsigned NumTokens) {
6828 free(Tokens);
6829}
6830
Guy Benyei11169dd2012-12-18 14:30:41 +00006831//===----------------------------------------------------------------------===//
6832// Token annotation APIs.
6833//===----------------------------------------------------------------------===//
6834
Guy Benyei11169dd2012-12-18 14:30:41 +00006835static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6836 CXCursor parent,
6837 CXClientData client_data);
6838static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6839 CXClientData client_data);
6840
6841namespace {
6842class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006843 CXToken *Tokens;
6844 CXCursor *Cursors;
6845 unsigned NumTokens;
6846 unsigned TokIdx;
6847 unsigned PreprocessingTokIdx;
6848 CursorVisitor AnnotateVis;
6849 SourceManager &SrcMgr;
6850 bool HasContextSensitiveKeywords;
6851
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006852 struct PostChildrenAction {
6853 CXCursor cursor;
6854 enum Action { Invalid, Ignore, Postpone } action;
6855 };
6856 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6857
Guy Benyei11169dd2012-12-18 14:30:41 +00006858 struct PostChildrenInfo {
6859 CXCursor Cursor;
6860 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006861 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006862 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006863 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006864 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006865 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006866
6867 CXToken &getTok(unsigned Idx) {
6868 assert(Idx < NumTokens);
6869 return Tokens[Idx];
6870 }
6871 const CXToken &getTok(unsigned Idx) const {
6872 assert(Idx < NumTokens);
6873 return Tokens[Idx];
6874 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006875 bool MoreTokens() const { return TokIdx < NumTokens; }
6876 unsigned NextToken() const { return TokIdx; }
6877 void AdvanceToken() { ++TokIdx; }
6878 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006879 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 }
6881 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006882 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006883 }
6884 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006885 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006886 }
6887
6888 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006889 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006890 SourceRange);
6891
6892public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006893 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006894 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006895 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006896 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006897 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006898 AnnotateTokensVisitor, this,
6899 /*VisitPreprocessorLast=*/true,
6900 /*VisitIncludedEntities=*/false,
6901 RegionOfInterest,
6902 /*VisitDeclsOnly=*/false,
6903 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006904 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006905 HasContextSensitiveKeywords(false) { }
6906
6907 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6908 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006909 bool IsIgnoredChildCursor(CXCursor cursor) const;
6910 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6911
Guy Benyei11169dd2012-12-18 14:30:41 +00006912 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006913 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6914 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6915
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 void AnnotateTokens();
6917
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006918 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006919 /// context-sensitive keywords.
6920 bool hasContextSensitiveKeywords() const {
6921 return HasContextSensitiveKeywords;
6922 }
6923
6924 ~AnnotateTokensWorker() {
6925 assert(PostChildrenInfos.empty());
6926 }
6927};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006928}
Guy Benyei11169dd2012-12-18 14:30:41 +00006929
6930void AnnotateTokensWorker::AnnotateTokens() {
6931 // Walk the AST within the region of interest, annotating tokens
6932 // along the way.
6933 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006934}
Guy Benyei11169dd2012-12-18 14:30:41 +00006935
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006936bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6937 if (PostChildrenInfos.empty())
6938 return false;
6939
6940 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6941 if (ChildAction.cursor == cursor &&
6942 ChildAction.action == PostChildrenAction::Ignore) {
6943 return true;
6944 }
6945 }
6946
6947 return false;
6948}
6949
6950const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6951 if (!clang_isExpression(Cursor.kind))
6952 return nullptr;
6953
6954 const Expr *E = getCursorExpr(Cursor);
6955 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6956 const OverloadedOperatorKind Kind = OCE->getOperator();
6957 if (Kind == OO_Call || Kind == OO_Subscript)
6958 return OCE;
6959 }
6960
6961 return nullptr;
6962}
6963
6964AnnotateTokensWorker::PostChildrenActions
6965AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6966 PostChildrenActions actions;
6967
6968 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6969 // visited before the arguments to the operator call. For the Call and
6970 // Subscript operator the range of this DeclRefExpr includes the whole call
6971 // expression, so that all tokens in that range would be mapped to the
6972 // operator function, including the tokens of the arguments. To avoid that,
6973 // ensure to visit this DeclRefExpr as last node.
6974 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6975 const Expr *Callee = OCE->getCallee();
6976 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6977 const Expr *SubExpr = ICE->getSubExpr();
6978 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00006979 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006980 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6981
6982 // Visit the DeclRefExpr as last.
6983 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6984 actions.push_back({cxChild, PostChildrenAction::Postpone});
6985
6986 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6987 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6988 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6989 actions.push_back({cxChild, PostChildrenAction::Ignore});
6990 }
6991 }
6992 }
6993
6994 return actions;
6995}
6996
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006997static inline void updateCursorAnnotation(CXCursor &Cursor,
6998 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006999 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007000 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007001 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007002}
7003
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007004/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007005//// between the cursor location and the source range is the same as
7006/// \arg compResult.
7007///
7008/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7009/// Pass RangeOverlap to annotate tokens inside a range.
7010void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7011 RangeComparisonResult compResult,
7012 SourceRange range) {
7013 while (MoreTokens()) {
7014 const unsigned I = NextToken();
7015 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007016 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7017 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007018
7019 SourceLocation TokLoc = GetTokenLoc(I);
7020 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007021 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007022 AdvanceToken();
7023 continue;
7024 }
7025 break;
7026 }
7027}
7028
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007029/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007030/// \returns true if it advanced beyond all macro tokens, false otherwise.
7031bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 CXCursor updateC,
7033 RangeComparisonResult compResult,
7034 SourceRange range) {
7035 assert(MoreTokens());
7036 assert(isFunctionMacroToken(NextToken()) &&
7037 "Should be called only for macro arg tokens");
7038
7039 // This works differently than annotateAndAdvanceTokens; because expanded
7040 // macro arguments can have arbitrary translation-unit source order, we do not
7041 // advance the token index one by one until a token fails the range test.
7042 // We only advance once past all of the macro arg tokens if all of them
7043 // pass the range test. If one of them fails we keep the token index pointing
7044 // at the start of the macro arg tokens so that the failing token will be
7045 // annotated by a subsequent annotation try.
7046
7047 bool atLeastOneCompFail = false;
7048
7049 unsigned I = NextToken();
7050 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7051 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7052 if (TokLoc.isFileID())
7053 continue; // not macro arg token, it's parens or comma.
7054 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7055 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7056 Cursors[I] = updateC;
7057 } else
7058 atLeastOneCompFail = true;
7059 }
7060
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007061 if (atLeastOneCompFail)
7062 return false;
7063
7064 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7065 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007066}
7067
7068enum CXChildVisitResult
7069AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 SourceRange cursorRange = getRawCursorExtent(cursor);
7071 if (cursorRange.isInvalid())
7072 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007073
7074 if (IsIgnoredChildCursor(cursor))
7075 return CXChildVisit_Continue;
7076
Guy Benyei11169dd2012-12-18 14:30:41 +00007077 if (!HasContextSensitiveKeywords) {
7078 // Objective-C properties can have context-sensitive keywords.
7079 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007080 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007081 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7082 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7083 }
7084 // Objective-C methods can have context-sensitive keywords.
7085 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7086 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007087 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007088 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7089 if (Method->getObjCDeclQualifier())
7090 HasContextSensitiveKeywords = true;
7091 else {
David Majnemer59f77922016-06-24 04:05:48 +00007092 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007093 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007094 HasContextSensitiveKeywords = true;
7095 break;
7096 }
7097 }
7098 }
7099 }
7100 }
7101 // C++ methods can have context-sensitive keywords.
7102 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007103 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7105 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7106 HasContextSensitiveKeywords = true;
7107 }
7108 }
7109 // C++ classes can have context-sensitive keywords.
7110 else if (cursor.kind == CXCursor_StructDecl ||
7111 cursor.kind == CXCursor_ClassDecl ||
7112 cursor.kind == CXCursor_ClassTemplate ||
7113 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007114 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007115 if (D->hasAttr<FinalAttr>())
7116 HasContextSensitiveKeywords = true;
7117 }
7118 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007119
7120 // Don't override a property annotation with its getter/setter method.
7121 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7122 parent.kind == CXCursor_ObjCPropertyDecl)
7123 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007124
7125 if (clang_isPreprocessing(cursor.kind)) {
7126 // Items in the preprocessing record are kept separate from items in
7127 // declarations, so we keep a separate token index.
7128 unsigned SavedTokIdx = TokIdx;
7129 TokIdx = PreprocessingTokIdx;
7130
7131 // Skip tokens up until we catch up to the beginning of the preprocessing
7132 // entry.
7133 while (MoreTokens()) {
7134 const unsigned I = NextToken();
7135 SourceLocation TokLoc = GetTokenLoc(I);
7136 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7137 case RangeBefore:
7138 AdvanceToken();
7139 continue;
7140 case RangeAfter:
7141 case RangeOverlap:
7142 break;
7143 }
7144 break;
7145 }
7146
7147 // Look at all of the tokens within this range.
7148 while (MoreTokens()) {
7149 const unsigned I = NextToken();
7150 SourceLocation TokLoc = GetTokenLoc(I);
7151 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7152 case RangeBefore:
7153 llvm_unreachable("Infeasible");
7154 case RangeAfter:
7155 break;
7156 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007157 // For macro expansions, just note where the beginning of the macro
7158 // expansion occurs.
7159 if (cursor.kind == CXCursor_MacroExpansion) {
7160 if (TokLoc == cursorRange.getBegin())
7161 Cursors[I] = cursor;
7162 AdvanceToken();
7163 break;
7164 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007165 // We may have already annotated macro names inside macro definitions.
7166 if (Cursors[I].kind != CXCursor_MacroExpansion)
7167 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007168 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007169 continue;
7170 }
7171 break;
7172 }
7173
7174 // Save the preprocessing token index; restore the non-preprocessing
7175 // token index.
7176 PreprocessingTokIdx = TokIdx;
7177 TokIdx = SavedTokIdx;
7178 return CXChildVisit_Recurse;
7179 }
7180
7181 if (cursorRange.isInvalid())
7182 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007183
7184 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007185 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007186 const enum CXCursorKind K = clang_getCursorKind(parent);
7187 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007188 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7189 // Attributes are annotated out-of-order, skip tokens until we reach it.
7190 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007191 ? clang_getNullCursor() : parent;
7192
7193 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7194
7195 // Avoid having the cursor of an expression "overwrite" the annotation of the
7196 // variable declaration that it belongs to.
7197 // This can happen for C++ constructor expressions whose range generally
7198 // include the variable declaration, e.g.:
7199 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007200 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007201 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007202 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007204 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7205 E->getBeginLoc() == D->getLocation() &&
7206 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007207 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007208 AdvanceToken();
7209 }
7210 }
7211 }
7212
7213 // Before recursing into the children keep some state that we are going
7214 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7215 // extra work after the child nodes are visited.
7216 // Note that we don't call VisitChildren here to avoid traversing statements
7217 // code-recursively which can blow the stack.
7218
7219 PostChildrenInfo Info;
7220 Info.Cursor = cursor;
7221 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007222 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007223 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007224 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007225 PostChildrenInfos.push_back(Info);
7226
7227 return CXChildVisit_Recurse;
7228}
7229
7230bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7231 if (PostChildrenInfos.empty())
7232 return false;
7233 const PostChildrenInfo &Info = PostChildrenInfos.back();
7234 if (!clang_equalCursors(Info.Cursor, cursor))
7235 return false;
7236
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007237 HandlePostPonedChildCursors(Info);
7238
Guy Benyei11169dd2012-12-18 14:30:41 +00007239 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7240 const unsigned AfterChildren = NextToken();
7241 SourceRange cursorRange = Info.CursorRange;
7242
7243 // Scan the tokens that are at the end of the cursor, but are not captured
7244 // but the child cursors.
7245 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7246
7247 // Scan the tokens that are at the beginning of the cursor, but are not
7248 // capture by the child cursors.
7249 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7250 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7251 break;
7252
7253 Cursors[I] = cursor;
7254 }
7255
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007256 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7257 // encountered the attribute cursor.
7258 if (clang_isAttribute(cursor.kind))
7259 TokIdx = Info.BeforeReachingCursorIdx;
7260
Guy Benyei11169dd2012-12-18 14:30:41 +00007261 PostChildrenInfos.pop_back();
7262 return false;
7263}
7264
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007265void AnnotateTokensWorker::HandlePostPonedChildCursors(
7266 const PostChildrenInfo &Info) {
7267 for (const auto &ChildAction : Info.ChildActions) {
7268 if (ChildAction.action == PostChildrenAction::Postpone) {
7269 HandlePostPonedChildCursor(ChildAction.cursor,
7270 Info.BeforeChildrenTokenIdx);
7271 }
7272 }
7273}
7274
7275void AnnotateTokensWorker::HandlePostPonedChildCursor(
7276 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007277 unsigned I = StartTokenIndex;
7278
7279 // The bracket tokens of a Call or Subscript operator are mapped to
7280 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7281 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7282 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007283 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7284 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007285 if (clang_Range_isNull(CXRefNameRange))
7286 break; // All ranges handled.
7287
7288 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7289 while (I < NumTokens) {
7290 const SourceLocation TokenLocation = GetTokenLoc(I);
7291 if (!TokenLocation.isValid())
7292 break;
7293
7294 // Adapt the end range, because LocationCompare() reports
7295 // RangeOverlap even for the not-inclusive end location.
7296 const SourceLocation fixedEnd =
7297 RefNameRange.getEnd().getLocWithOffset(-1);
7298 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7299
7300 const RangeComparisonResult ComparisonResult =
7301 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7302
7303 if (ComparisonResult == RangeOverlap) {
7304 Cursors[I++] = Cursor;
7305 } else if (ComparisonResult == RangeBefore) {
7306 ++I; // Not relevant token, check next one.
7307 } else if (ComparisonResult == RangeAfter) {
7308 break; // All tokens updated for current range, check next.
7309 }
7310 }
7311 }
7312}
7313
Guy Benyei11169dd2012-12-18 14:30:41 +00007314static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7315 CXCursor parent,
7316 CXClientData client_data) {
7317 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7318}
7319
7320static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7321 CXClientData client_data) {
7322 return static_cast<AnnotateTokensWorker*>(client_data)->
7323 postVisitChildren(cursor);
7324}
7325
7326namespace {
7327
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007328/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007329/// and mark tokens that are macro arguments. This info is used by the
7330/// AnnotateTokensWorker.
7331class MarkMacroArgTokensVisitor {
7332 SourceManager &SM;
7333 CXToken *Tokens;
7334 unsigned NumTokens;
7335 unsigned CurIdx;
7336
7337public:
7338 MarkMacroArgTokensVisitor(SourceManager &SM,
7339 CXToken *tokens, unsigned numTokens)
7340 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7341
7342 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7343 if (cursor.kind != CXCursor_MacroExpansion)
7344 return CXChildVisit_Continue;
7345
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007346 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007347 if (macroRange.getBegin() == macroRange.getEnd())
7348 return CXChildVisit_Continue; // it's not a function macro.
7349
7350 for (; CurIdx < NumTokens; ++CurIdx) {
7351 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7352 macroRange.getBegin()))
7353 break;
7354 }
7355
7356 if (CurIdx == NumTokens)
7357 return CXChildVisit_Break;
7358
7359 for (; CurIdx < NumTokens; ++CurIdx) {
7360 SourceLocation tokLoc = getTokenLoc(CurIdx);
7361 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7362 break;
7363
7364 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7365 }
7366
7367 if (CurIdx == NumTokens)
7368 return CXChildVisit_Break;
7369
7370 return CXChildVisit_Continue;
7371 }
7372
7373private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007374 CXToken &getTok(unsigned Idx) {
7375 assert(Idx < NumTokens);
7376 return Tokens[Idx];
7377 }
7378 const CXToken &getTok(unsigned Idx) const {
7379 assert(Idx < NumTokens);
7380 return Tokens[Idx];
7381 }
7382
Guy Benyei11169dd2012-12-18 14:30:41 +00007383 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007384 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007385 }
7386
7387 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7388 // The third field is reserved and currently not used. Use it here
7389 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007390 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007391 }
7392};
7393
7394} // end anonymous namespace
7395
7396static CXChildVisitResult
7397MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7398 CXClientData client_data) {
7399 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7400 parent);
7401}
7402
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007403/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007404/// \returns true if lexing was finished, false otherwise.
7405static bool lexNext(Lexer &Lex, Token &Tok,
7406 unsigned &NextIdx, unsigned NumTokens) {
7407 if (NextIdx >= NumTokens)
7408 return true;
7409
7410 ++NextIdx;
7411 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007412 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007413}
7414
Guy Benyei11169dd2012-12-18 14:30:41 +00007415static void annotatePreprocessorTokens(CXTranslationUnit TU,
7416 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007417 CXCursor *Cursors,
7418 CXToken *Tokens,
7419 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007420 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007421
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007422 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007423 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7424 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007425 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007426 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007427 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007428
7429 if (BeginLocInfo.first != EndLocInfo.first)
7430 return;
7431
7432 StringRef Buffer;
7433 bool Invalid = false;
7434 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7435 if (Buffer.empty() || Invalid)
7436 return;
7437
7438 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7439 CXXUnit->getASTContext().getLangOpts(),
7440 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7441 Buffer.end());
7442 Lex.SetCommentRetentionState(true);
7443
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007444 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007445 // Lex tokens in raw mode until we hit the end of the range, to avoid
7446 // entering #includes or expanding macros.
7447 while (true) {
7448 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007449 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7450 break;
7451 unsigned TokIdx = NextIdx-1;
7452 assert(Tok.getLocation() ==
7453 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007454
7455 reprocess:
7456 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007457 // We have found a preprocessing directive. Annotate the tokens
7458 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007459 //
7460 // FIXME: Some simple tests here could identify macro definitions and
7461 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007462
7463 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007464 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7465 break;
7466
Craig Topper69186e72014-06-08 08:38:04 +00007467 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007468 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007469 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7470 break;
7471
7472 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007473 IdentifierInfo &II =
7474 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007475 SourceLocation MappedTokLoc =
7476 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7477 MI = getMacroInfo(II, MappedTokLoc, TU);
7478 }
7479 }
7480
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007481 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007482 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007483 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7484 finished = true;
7485 break;
7486 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007487 // If we are in a macro definition, check if the token was ever a
7488 // macro name and annotate it if that's the case.
7489 if (MI) {
7490 SourceLocation SaveLoc = Tok.getLocation();
7491 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007492 MacroDefinitionRecord *MacroDef =
7493 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007494 Tok.setLocation(SaveLoc);
7495 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007496 Cursors[NextIdx - 1] =
7497 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007498 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007499 } while (!Tok.isAtStartOfLine());
7500
7501 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7502 assert(TokIdx <= LastIdx);
7503 SourceLocation EndLoc =
7504 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7505 CXCursor Cursor =
7506 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7507
7508 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007509 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007510
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007511 if (finished)
7512 break;
7513 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007515 }
7516}
7517
7518// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007519static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7520 CXToken *Tokens, unsigned NumTokens,
7521 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007522 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007523 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7524 setThreadBackgroundPriority();
7525
7526 // Determine the region of interest, which contains all of the tokens.
7527 SourceRange RegionOfInterest;
7528 RegionOfInterest.setBegin(
7529 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7530 RegionOfInterest.setEnd(
7531 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7532 Tokens[NumTokens-1])));
7533
Guy Benyei11169dd2012-12-18 14:30:41 +00007534 // Relex the tokens within the source range to look for preprocessing
7535 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007536 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007537
7538 // If begin location points inside a macro argument, set it to the expansion
7539 // location so we can have the full context when annotating semantically.
7540 {
7541 SourceManager &SM = CXXUnit->getSourceManager();
7542 SourceLocation Loc =
7543 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7544 if (Loc.isMacroID())
7545 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7546 }
7547
Guy Benyei11169dd2012-12-18 14:30:41 +00007548 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7549 // Search and mark tokens that are macro argument expansions.
7550 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7551 Tokens, NumTokens);
7552 CursorVisitor MacroArgMarker(TU,
7553 MarkMacroArgTokensVisitorDelegate, &Visitor,
7554 /*VisitPreprocessorLast=*/true,
7555 /*VisitIncludedEntities=*/false,
7556 RegionOfInterest);
7557 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7558 }
7559
7560 // Annotate all of the source locations in the region of interest that map to
7561 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007562 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007563
7564 // FIXME: We use a ridiculous stack size here because the data-recursion
7565 // algorithm uses a large stack frame than the non-data recursive version,
7566 // and AnnotationTokensWorker currently transforms the data-recursion
7567 // algorithm back into a traditional recursion by explicitly calling
7568 // VisitChildren(). We will need to remove this explicit recursive call.
7569 W.AnnotateTokens();
7570
7571 // If we ran into any entities that involve context-sensitive keywords,
7572 // take another pass through the tokens to mark them as such.
7573 if (W.hasContextSensitiveKeywords()) {
7574 for (unsigned I = 0; I != NumTokens; ++I) {
7575 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7576 continue;
7577
7578 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7579 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007580 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007581 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7582 if (Property->getPropertyAttributesAsWritten() != 0 &&
7583 llvm::StringSwitch<bool>(II->getName())
7584 .Case("readonly", true)
7585 .Case("assign", true)
7586 .Case("unsafe_unretained", true)
7587 .Case("readwrite", true)
7588 .Case("retain", true)
7589 .Case("copy", true)
7590 .Case("nonatomic", true)
7591 .Case("atomic", true)
7592 .Case("getter", true)
7593 .Case("setter", true)
7594 .Case("strong", true)
7595 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007596 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007597 .Default(false))
7598 Tokens[I].int_data[0] = CXToken_Keyword;
7599 }
7600 continue;
7601 }
7602
7603 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7604 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7605 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7606 if (llvm::StringSwitch<bool>(II->getName())
7607 .Case("in", true)
7608 .Case("out", true)
7609 .Case("inout", true)
7610 .Case("oneway", true)
7611 .Case("bycopy", true)
7612 .Case("byref", true)
7613 .Default(false))
7614 Tokens[I].int_data[0] = CXToken_Keyword;
7615 continue;
7616 }
7617
7618 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7619 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7620 Tokens[I].int_data[0] = CXToken_Keyword;
7621 continue;
7622 }
7623 }
7624 }
7625}
7626
Guy Benyei11169dd2012-12-18 14:30:41 +00007627void clang_annotateTokens(CXTranslationUnit TU,
7628 CXToken *Tokens, unsigned NumTokens,
7629 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007630 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007631 LOG_BAD_TU(TU);
7632 return;
7633 }
7634 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007635 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007636 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007637 }
7638
7639 LOG_FUNC_SECTION {
7640 *Log << TU << ' ';
7641 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7642 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7643 *Log << clang_getRange(bloc, eloc);
7644 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007645
7646 // Any token we don't specifically annotate will have a NULL cursor.
7647 CXCursor C = clang_getNullCursor();
7648 for (unsigned I = 0; I != NumTokens; ++I)
7649 Cursors[I] = C;
7650
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007651 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007652 if (!CXXUnit)
7653 return;
7654
7655 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007656
7657 auto AnnotateTokensImpl = [=]() {
7658 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7659 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007660 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007661 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007662 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7663 }
7664}
7665
Guy Benyei11169dd2012-12-18 14:30:41 +00007666//===----------------------------------------------------------------------===//
7667// Operations for querying linkage of a cursor.
7668//===----------------------------------------------------------------------===//
7669
Guy Benyei11169dd2012-12-18 14:30:41 +00007670CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7671 if (!clang_isDeclaration(cursor.kind))
7672 return CXLinkage_Invalid;
7673
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007674 const Decl *D = cxcursor::getCursorDecl(cursor);
7675 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007676 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007677 case NoLinkage:
7678 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007679 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007680 case InternalLinkage: return CXLinkage_Internal;
7681 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007682 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007683 case ExternalLinkage: return CXLinkage_External;
7684 };
7685
7686 return CXLinkage_Invalid;
7687}
Guy Benyei11169dd2012-12-18 14:30:41 +00007688
7689//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007690// Operations for querying visibility of a cursor.
7691//===----------------------------------------------------------------------===//
7692
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007693CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7694 if (!clang_isDeclaration(cursor.kind))
7695 return CXVisibility_Invalid;
7696
7697 const Decl *D = cxcursor::getCursorDecl(cursor);
7698 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7699 switch (ND->getVisibility()) {
7700 case HiddenVisibility: return CXVisibility_Hidden;
7701 case ProtectedVisibility: return CXVisibility_Protected;
7702 case DefaultVisibility: return CXVisibility_Default;
7703 };
7704
7705 return CXVisibility_Invalid;
7706}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007707
7708//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007709// Operations for querying language of a cursor.
7710//===----------------------------------------------------------------------===//
7711
7712static CXLanguageKind getDeclLanguage(const Decl *D) {
7713 if (!D)
7714 return CXLanguage_C;
7715
7716 switch (D->getKind()) {
7717 default:
7718 break;
7719 case Decl::ImplicitParam:
7720 case Decl::ObjCAtDefsField:
7721 case Decl::ObjCCategory:
7722 case Decl::ObjCCategoryImpl:
7723 case Decl::ObjCCompatibleAlias:
7724 case Decl::ObjCImplementation:
7725 case Decl::ObjCInterface:
7726 case Decl::ObjCIvar:
7727 case Decl::ObjCMethod:
7728 case Decl::ObjCProperty:
7729 case Decl::ObjCPropertyImpl:
7730 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007731 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007732 return CXLanguage_ObjC;
7733 case Decl::CXXConstructor:
7734 case Decl::CXXConversion:
7735 case Decl::CXXDestructor:
7736 case Decl::CXXMethod:
7737 case Decl::CXXRecord:
7738 case Decl::ClassTemplate:
7739 case Decl::ClassTemplatePartialSpecialization:
7740 case Decl::ClassTemplateSpecialization:
7741 case Decl::Friend:
7742 case Decl::FriendTemplate:
7743 case Decl::FunctionTemplate:
7744 case Decl::LinkageSpec:
7745 case Decl::Namespace:
7746 case Decl::NamespaceAlias:
7747 case Decl::NonTypeTemplateParm:
7748 case Decl::StaticAssert:
7749 case Decl::TemplateTemplateParm:
7750 case Decl::TemplateTypeParm:
7751 case Decl::UnresolvedUsingTypename:
7752 case Decl::UnresolvedUsingValue:
7753 case Decl::Using:
7754 case Decl::UsingDirective:
7755 case Decl::UsingShadow:
7756 return CXLanguage_CPlusPlus;
7757 }
7758
7759 return CXLanguage_C;
7760}
7761
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007762static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7763 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007764 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007765
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007766 switch (D->getAvailability()) {
7767 case AR_Available:
7768 case AR_NotYetIntroduced:
7769 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007770 return getCursorAvailabilityForDecl(
7771 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007772 return CXAvailability_Available;
7773
7774 case AR_Deprecated:
7775 return CXAvailability_Deprecated;
7776
7777 case AR_Unavailable:
7778 return CXAvailability_NotAvailable;
7779 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007780
7781 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007782}
7783
Guy Benyei11169dd2012-12-18 14:30:41 +00007784enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7785 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007786 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7787 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007788
7789 return CXAvailability_Available;
7790}
7791
7792static CXVersion convertVersion(VersionTuple In) {
7793 CXVersion Out = { -1, -1, -1 };
7794 if (In.empty())
7795 return Out;
7796
7797 Out.Major = In.getMajor();
7798
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007799 Optional<unsigned> Minor = In.getMinor();
7800 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007801 Out.Minor = *Minor;
7802 else
7803 return Out;
7804
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007805 Optional<unsigned> Subminor = In.getSubminor();
7806 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007807 Out.Subminor = *Subminor;
7808
7809 return Out;
7810}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007811
Alex Lorenz1345ea22017-06-12 19:06:30 +00007812static void getCursorPlatformAvailabilityForDecl(
7813 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7814 int *always_unavailable, CXString *unavailable_message,
7815 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007816 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007817 for (auto A : D->attrs()) {
7818 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007819 HadAvailAttr = true;
7820 if (always_deprecated)
7821 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007822 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007823 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007824 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007825 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007826 continue;
7827 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007828
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007829 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007830 HadAvailAttr = true;
7831 if (always_unavailable)
7832 *always_unavailable = 1;
7833 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007834 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007835 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7836 }
7837 continue;
7838 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007839
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007840 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007841 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007842 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007843 }
7844 }
7845
7846 if (!HadAvailAttr)
7847 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7848 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007849 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7850 deprecated_message, always_unavailable, unavailable_message,
7851 AvailabilityAttrs);
7852
7853 if (AvailabilityAttrs.empty())
7854 return;
7855
Fangrui Song55fab262018-09-26 22:16:28 +00007856 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007857 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7858 return LHS->getPlatform()->getName() <
7859 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007860 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007861 ASTContext &Ctx = D->getASTContext();
7862 auto It = std::unique(
7863 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7864 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7865 if (LHS->getPlatform() != RHS->getPlatform())
7866 return false;
7867
7868 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7869 LHS->getDeprecated() == RHS->getDeprecated() &&
7870 LHS->getObsoleted() == RHS->getObsoleted() &&
7871 LHS->getMessage() == RHS->getMessage() &&
7872 LHS->getReplacement() == RHS->getReplacement())
7873 return true;
7874
7875 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7876 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7877 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7878 return false;
7879
7880 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7881 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7882
7883 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7884 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7885 if (LHS->getMessage().empty())
7886 LHS->setMessage(Ctx, RHS->getMessage());
7887 if (LHS->getReplacement().empty())
7888 LHS->setReplacement(Ctx, RHS->getReplacement());
7889 }
7890
7891 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7892 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7893 if (LHS->getMessage().empty())
7894 LHS->setMessage(Ctx, RHS->getMessage());
7895 if (LHS->getReplacement().empty())
7896 LHS->setReplacement(Ctx, RHS->getReplacement());
7897 }
7898
7899 return true;
7900 });
7901 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007902}
7903
Alex Lorenz1345ea22017-06-12 19:06:30 +00007904int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007905 CXString *deprecated_message,
7906 int *always_unavailable,
7907 CXString *unavailable_message,
7908 CXPlatformAvailability *availability,
7909 int availability_size) {
7910 if (always_deprecated)
7911 *always_deprecated = 0;
7912 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007913 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007914 if (always_unavailable)
7915 *always_unavailable = 0;
7916 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007917 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007918
Guy Benyei11169dd2012-12-18 14:30:41 +00007919 if (!clang_isDeclaration(cursor.kind))
7920 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007921
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007922 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007923 if (!D)
7924 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007925
Alex Lorenz1345ea22017-06-12 19:06:30 +00007926 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7927 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7928 always_unavailable, unavailable_message,
7929 AvailabilityAttrs);
7930 for (const auto &Avail :
7931 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7932 .take_front(availability_size))) {
7933 availability[Avail.index()].Platform =
7934 cxstring::createDup(Avail.value()->getPlatform()->getName());
7935 availability[Avail.index()].Introduced =
7936 convertVersion(Avail.value()->getIntroduced());
7937 availability[Avail.index()].Deprecated =
7938 convertVersion(Avail.value()->getDeprecated());
7939 availability[Avail.index()].Obsoleted =
7940 convertVersion(Avail.value()->getObsoleted());
7941 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7942 availability[Avail.index()].Message =
7943 cxstring::createDup(Avail.value()->getMessage());
7944 }
7945
7946 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007947}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007948
Guy Benyei11169dd2012-12-18 14:30:41 +00007949void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7950 clang_disposeString(availability->Platform);
7951 clang_disposeString(availability->Message);
7952}
7953
7954CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7955 if (clang_isDeclaration(cursor.kind))
7956 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7957
7958 return CXLanguage_Invalid;
7959}
7960
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007961CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7962 const Decl *D = cxcursor::getCursorDecl(cursor);
7963 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7964 switch (VD->getTLSKind()) {
7965 case VarDecl::TLS_None:
7966 return CXTLS_None;
7967 case VarDecl::TLS_Dynamic:
7968 return CXTLS_Dynamic;
7969 case VarDecl::TLS_Static:
7970 return CXTLS_Static;
7971 }
7972 }
7973
7974 return CXTLS_None;
7975}
7976
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007977 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007978 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007979 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007980static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007982 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007983
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007984 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007985 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7986 return FunTmpl;
7987
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007988 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007989 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7990 return ClassTmpl;
7991
7992 return D;
7993}
7994
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007995
7996enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7997 StorageClass sc = SC_None;
7998 const Decl *D = getCursorDecl(C);
7999 if (D) {
8000 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8001 sc = FD->getStorageClass();
8002 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8003 sc = VD->getStorageClass();
8004 } else {
8005 return CX_SC_Invalid;
8006 }
8007 } else {
8008 return CX_SC_Invalid;
8009 }
8010 switch (sc) {
8011 case SC_None:
8012 return CX_SC_None;
8013 case SC_Extern:
8014 return CX_SC_Extern;
8015 case SC_Static:
8016 return CX_SC_Static;
8017 case SC_PrivateExtern:
8018 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008019 case SC_Auto:
8020 return CX_SC_Auto;
8021 case SC_Register:
8022 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008023 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008024 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008025}
8026
Guy Benyei11169dd2012-12-18 14:30:41 +00008027CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8028 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008029 if (const Decl *D = getCursorDecl(cursor)) {
8030 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008031 if (!DC)
8032 return clang_getNullCursor();
8033
8034 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8035 getCursorTU(cursor));
8036 }
8037 }
8038
8039 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008040 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008041 return MakeCXCursor(D, getCursorTU(cursor));
8042 }
8043
8044 return clang_getNullCursor();
8045}
8046
8047CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8048 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008049 if (const Decl *D = getCursorDecl(cursor)) {
8050 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008051 if (!DC)
8052 return clang_getNullCursor();
8053
8054 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8055 getCursorTU(cursor));
8056 }
8057 }
8058
8059 // FIXME: Note that we can't easily compute the lexical context of a
8060 // statement or expression, so we return nothing.
8061 return clang_getNullCursor();
8062}
8063
8064CXFile clang_getIncludedFile(CXCursor cursor) {
8065 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008066 return nullptr;
8067
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008068 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008069 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008070}
8071
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008072unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8073 if (C.kind != CXCursor_ObjCPropertyDecl)
8074 return CXObjCPropertyAttr_noattr;
8075
8076 unsigned Result = CXObjCPropertyAttr_noattr;
8077 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8078 ObjCPropertyDecl::PropertyAttributeKind Attr =
8079 PD->getPropertyAttributesAsWritten();
8080
8081#define SET_CXOBJCPROP_ATTR(A) \
8082 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8083 Result |= CXObjCPropertyAttr_##A
8084 SET_CXOBJCPROP_ATTR(readonly);
8085 SET_CXOBJCPROP_ATTR(getter);
8086 SET_CXOBJCPROP_ATTR(assign);
8087 SET_CXOBJCPROP_ATTR(readwrite);
8088 SET_CXOBJCPROP_ATTR(retain);
8089 SET_CXOBJCPROP_ATTR(copy);
8090 SET_CXOBJCPROP_ATTR(nonatomic);
8091 SET_CXOBJCPROP_ATTR(setter);
8092 SET_CXOBJCPROP_ATTR(atomic);
8093 SET_CXOBJCPROP_ATTR(weak);
8094 SET_CXOBJCPROP_ATTR(strong);
8095 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008096 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008097#undef SET_CXOBJCPROP_ATTR
8098
8099 return Result;
8100}
8101
Michael Wu6e88f532018-08-03 05:38:29 +00008102CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8103 if (C.kind != CXCursor_ObjCPropertyDecl)
8104 return cxstring::createNull();
8105
8106 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8107 Selector sel = PD->getGetterName();
8108 if (sel.isNull())
8109 return cxstring::createNull();
8110
8111 return cxstring::createDup(sel.getAsString());
8112}
8113
8114CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8115 if (C.kind != CXCursor_ObjCPropertyDecl)
8116 return cxstring::createNull();
8117
8118 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8119 Selector sel = PD->getSetterName();
8120 if (sel.isNull())
8121 return cxstring::createNull();
8122
8123 return cxstring::createDup(sel.getAsString());
8124}
8125
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008126unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8127 if (!clang_isDeclaration(C.kind))
8128 return CXObjCDeclQualifier_None;
8129
8130 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8131 const Decl *D = getCursorDecl(C);
8132 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8133 QT = MD->getObjCDeclQualifier();
8134 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8135 QT = PD->getObjCDeclQualifier();
8136 if (QT == Decl::OBJC_TQ_None)
8137 return CXObjCDeclQualifier_None;
8138
8139 unsigned Result = CXObjCDeclQualifier_None;
8140 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8141 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8142 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8143 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8144 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8145 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8146
8147 return Result;
8148}
8149
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008150unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8151 if (!clang_isDeclaration(C.kind))
8152 return 0;
8153
8154 const Decl *D = getCursorDecl(C);
8155 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8156 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8157 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8158 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8159
8160 return 0;
8161}
8162
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008163unsigned clang_Cursor_isVariadic(CXCursor C) {
8164 if (!clang_isDeclaration(C.kind))
8165 return 0;
8166
8167 const Decl *D = getCursorDecl(C);
8168 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8169 return FD->isVariadic();
8170 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8171 return MD->isVariadic();
8172
8173 return 0;
8174}
8175
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008176unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8177 CXString *language, CXString *definedIn,
8178 unsigned *isGenerated) {
8179 if (!clang_isDeclaration(C.kind))
8180 return 0;
8181
8182 const Decl *D = getCursorDecl(C);
8183
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008184 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008185 if (language)
8186 *language = cxstring::createDup(attr->getLanguage());
8187 if (definedIn)
8188 *definedIn = cxstring::createDup(attr->getDefinedIn());
8189 if (isGenerated)
8190 *isGenerated = attr->getGeneratedDeclaration();
8191 return 1;
8192 }
8193 return 0;
8194}
8195
Guy Benyei11169dd2012-12-18 14:30:41 +00008196CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8197 if (!clang_isDeclaration(C.kind))
8198 return clang_getNullRange();
8199
8200 const Decl *D = getCursorDecl(C);
8201 ASTContext &Context = getCursorContext(C);
8202 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8203 if (!RC)
8204 return clang_getNullRange();
8205
8206 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8207}
8208
8209CXString clang_Cursor_getRawCommentText(CXCursor C) {
8210 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008211 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008212
8213 const Decl *D = getCursorDecl(C);
8214 ASTContext &Context = getCursorContext(C);
8215 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8216 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8217 StringRef();
8218
8219 // Don't duplicate the string because RawText points directly into source
8220 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008221 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008222}
8223
8224CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8225 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008226 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008227
8228 const Decl *D = getCursorDecl(C);
8229 const ASTContext &Context = getCursorContext(C);
8230 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8231
8232 if (RC) {
8233 StringRef BriefText = RC->getBriefText(Context);
8234
8235 // Don't duplicate the string because RawComment ensures that this memory
8236 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008237 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 }
8239
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008240 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008241}
8242
Guy Benyei11169dd2012-12-18 14:30:41 +00008243CXModule clang_Cursor_getModule(CXCursor C) {
8244 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008245 if (const ImportDecl *ImportD =
8246 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008247 return ImportD->getImportedModule();
8248 }
8249
Craig Topper69186e72014-06-08 08:38:04 +00008250 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008251}
8252
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008253CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8254 if (isNotUsableTU(TU)) {
8255 LOG_BAD_TU(TU);
8256 return nullptr;
8257 }
8258 if (!File)
8259 return nullptr;
8260 FileEntry *FE = static_cast<FileEntry *>(File);
8261
8262 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8263 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8264 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8265
Richard Smithfeb54b62014-10-23 02:01:19 +00008266 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008267}
8268
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008269CXFile clang_Module_getASTFile(CXModule CXMod) {
8270 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008271 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008272 Module *Mod = static_cast<Module*>(CXMod);
8273 return const_cast<FileEntry *>(Mod->getASTFile());
8274}
8275
Guy Benyei11169dd2012-12-18 14:30:41 +00008276CXModule clang_Module_getParent(CXModule CXMod) {
8277 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008278 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008279 Module *Mod = static_cast<Module*>(CXMod);
8280 return Mod->Parent;
8281}
8282
8283CXString clang_Module_getName(CXModule CXMod) {
8284 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008285 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008286 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008287 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008288}
8289
8290CXString clang_Module_getFullName(CXModule CXMod) {
8291 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008292 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008293 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008294 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008295}
8296
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008297int clang_Module_isSystem(CXModule CXMod) {
8298 if (!CXMod)
8299 return 0;
8300 Module *Mod = static_cast<Module*>(CXMod);
8301 return Mod->IsSystem;
8302}
8303
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008304unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8305 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008306 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008307 LOG_BAD_TU(TU);
8308 return 0;
8309 }
8310 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008311 return 0;
8312 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008313 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8314 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8315 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008316}
8317
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008318CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8319 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008320 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008321 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008322 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008323 }
8324 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008325 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008326 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008327 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008328
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008329 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8330 if (Index < TopHeaders.size())
8331 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008332
Craig Topper69186e72014-06-08 08:38:04 +00008333 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008334}
8335
Guy Benyei11169dd2012-12-18 14:30:41 +00008336//===----------------------------------------------------------------------===//
8337// C++ AST instrospection.
8338//===----------------------------------------------------------------------===//
8339
Jonathan Coe29565352016-04-27 12:48:25 +00008340unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8341 if (!clang_isDeclaration(C.kind))
8342 return 0;
8343
8344 const Decl *D = cxcursor::getCursorDecl(C);
8345 const CXXConstructorDecl *Constructor =
8346 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8347 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8348}
8349
8350unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8351 if (!clang_isDeclaration(C.kind))
8352 return 0;
8353
8354 const Decl *D = cxcursor::getCursorDecl(C);
8355 const CXXConstructorDecl *Constructor =
8356 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8357 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8358}
8359
8360unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8361 if (!clang_isDeclaration(C.kind))
8362 return 0;
8363
8364 const Decl *D = cxcursor::getCursorDecl(C);
8365 const CXXConstructorDecl *Constructor =
8366 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8367 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8368}
8369
8370unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8371 if (!clang_isDeclaration(C.kind))
8372 return 0;
8373
8374 const Decl *D = cxcursor::getCursorDecl(C);
8375 const CXXConstructorDecl *Constructor =
8376 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8377 // Passing 'false' excludes constructors marked 'explicit'.
8378 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8379}
8380
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008381unsigned clang_CXXField_isMutable(CXCursor C) {
8382 if (!clang_isDeclaration(C.kind))
8383 return 0;
8384
8385 if (const auto D = cxcursor::getCursorDecl(C))
8386 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8387 return FD->isMutable() ? 1 : 0;
8388 return 0;
8389}
8390
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008391unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8392 if (!clang_isDeclaration(C.kind))
8393 return 0;
8394
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008395 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008396 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008397 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008398 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8399}
8400
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008401unsigned clang_CXXMethod_isConst(CXCursor C) {
8402 if (!clang_isDeclaration(C.kind))
8403 return 0;
8404
8405 const Decl *D = cxcursor::getCursorDecl(C);
8406 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008407 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008408 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008409}
8410
Jonathan Coe29565352016-04-27 12:48:25 +00008411unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8412 if (!clang_isDeclaration(C.kind))
8413 return 0;
8414
8415 const Decl *D = cxcursor::getCursorDecl(C);
8416 const CXXMethodDecl *Method =
8417 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8418 return (Method && Method->isDefaulted()) ? 1 : 0;
8419}
8420
Guy Benyei11169dd2012-12-18 14:30:41 +00008421unsigned clang_CXXMethod_isStatic(CXCursor C) {
8422 if (!clang_isDeclaration(C.kind))
8423 return 0;
8424
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008425 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008426 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008427 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008428 return (Method && Method->isStatic()) ? 1 : 0;
8429}
8430
8431unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8432 if (!clang_isDeclaration(C.kind))
8433 return 0;
8434
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008435 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008436 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008437 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008438 return (Method && Method->isVirtual()) ? 1 : 0;
8439}
Guy Benyei11169dd2012-12-18 14:30:41 +00008440
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008441unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8442 if (!clang_isDeclaration(C.kind))
8443 return 0;
8444
8445 const auto *D = cxcursor::getCursorDecl(C);
8446 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8447 if (RD)
8448 RD = RD->getDefinition();
8449 return (RD && RD->isAbstract()) ? 1 : 0;
8450}
8451
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008452unsigned clang_EnumDecl_isScoped(CXCursor C) {
8453 if (!clang_isDeclaration(C.kind))
8454 return 0;
8455
8456 const Decl *D = cxcursor::getCursorDecl(C);
8457 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8458 return (Enum && Enum->isScoped()) ? 1 : 0;
8459}
8460
Guy Benyei11169dd2012-12-18 14:30:41 +00008461//===----------------------------------------------------------------------===//
8462// Attribute introspection.
8463//===----------------------------------------------------------------------===//
8464
Guy Benyei11169dd2012-12-18 14:30:41 +00008465CXType clang_getIBOutletCollectionType(CXCursor C) {
8466 if (C.kind != CXCursor_IBOutletCollectionAttr)
8467 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8468
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008469 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008470 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8471
8472 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8473}
Guy Benyei11169dd2012-12-18 14:30:41 +00008474
8475//===----------------------------------------------------------------------===//
8476// Inspecting memory usage.
8477//===----------------------------------------------------------------------===//
8478
8479typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8480
8481static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8482 enum CXTUResourceUsageKind k,
8483 unsigned long amount) {
8484 CXTUResourceUsageEntry entry = { k, amount };
8485 entries.push_back(entry);
8486}
8487
Guy Benyei11169dd2012-12-18 14:30:41 +00008488const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8489 const char *str = "";
8490 switch (kind) {
8491 case CXTUResourceUsage_AST:
8492 str = "ASTContext: expressions, declarations, and types";
8493 break;
8494 case CXTUResourceUsage_Identifiers:
8495 str = "ASTContext: identifiers";
8496 break;
8497 case CXTUResourceUsage_Selectors:
8498 str = "ASTContext: selectors";
8499 break;
8500 case CXTUResourceUsage_GlobalCompletionResults:
8501 str = "Code completion: cached global results";
8502 break;
8503 case CXTUResourceUsage_SourceManagerContentCache:
8504 str = "SourceManager: content cache allocator";
8505 break;
8506 case CXTUResourceUsage_AST_SideTables:
8507 str = "ASTContext: side tables";
8508 break;
8509 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8510 str = "SourceManager: malloc'ed memory buffers";
8511 break;
8512 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8513 str = "SourceManager: mmap'ed memory buffers";
8514 break;
8515 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8516 str = "ExternalASTSource: malloc'ed memory buffers";
8517 break;
8518 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8519 str = "ExternalASTSource: mmap'ed memory buffers";
8520 break;
8521 case CXTUResourceUsage_Preprocessor:
8522 str = "Preprocessor: malloc'ed memory";
8523 break;
8524 case CXTUResourceUsage_PreprocessingRecord:
8525 str = "Preprocessor: PreprocessingRecord";
8526 break;
8527 case CXTUResourceUsage_SourceManager_DataStructures:
8528 str = "SourceManager: data structures and tables";
8529 break;
8530 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8531 str = "Preprocessor: header search tables";
8532 break;
8533 }
8534 return str;
8535}
8536
8537CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008538 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008539 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008540 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008541 return usage;
8542 }
8543
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008544 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008545 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008546 ASTContext &astContext = astUnit->getASTContext();
8547
8548 // How much memory is used by AST nodes and types?
8549 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8550 (unsigned long) astContext.getASTAllocatedMemory());
8551
8552 // How much memory is used by identifiers?
8553 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8554 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8555
8556 // How much memory is used for selectors?
8557 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8558 (unsigned long) astContext.Selectors.getTotalMemory());
8559
8560 // How much memory is used by ASTContext's side tables?
8561 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8562 (unsigned long) astContext.getSideTableAllocatedMemory());
8563
8564 // How much memory is used for caching global code completion results?
8565 unsigned long completionBytes = 0;
8566 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008567 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008568 completionBytes = completionAllocator->getTotalMemory();
8569 }
8570 createCXTUResourceUsageEntry(*entries,
8571 CXTUResourceUsage_GlobalCompletionResults,
8572 completionBytes);
8573
8574 // How much memory is being used by SourceManager's content cache?
8575 createCXTUResourceUsageEntry(*entries,
8576 CXTUResourceUsage_SourceManagerContentCache,
8577 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8578
8579 // How much memory is being used by the MemoryBuffer's in SourceManager?
8580 const SourceManager::MemoryBufferSizes &srcBufs =
8581 astUnit->getSourceManager().getMemoryBufferSizes();
8582
8583 createCXTUResourceUsageEntry(*entries,
8584 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8585 (unsigned long) srcBufs.malloc_bytes);
8586 createCXTUResourceUsageEntry(*entries,
8587 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8588 (unsigned long) srcBufs.mmap_bytes);
8589 createCXTUResourceUsageEntry(*entries,
8590 CXTUResourceUsage_SourceManager_DataStructures,
8591 (unsigned long) astContext.getSourceManager()
8592 .getDataStructureSizes());
8593
8594 // How much memory is being used by the ExternalASTSource?
8595 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8596 const ExternalASTSource::MemoryBufferSizes &sizes =
8597 esrc->getMemoryBufferSizes();
8598
8599 createCXTUResourceUsageEntry(*entries,
8600 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8601 (unsigned long) sizes.malloc_bytes);
8602 createCXTUResourceUsageEntry(*entries,
8603 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8604 (unsigned long) sizes.mmap_bytes);
8605 }
8606
8607 // How much memory is being used by the Preprocessor?
8608 Preprocessor &pp = astUnit->getPreprocessor();
8609 createCXTUResourceUsageEntry(*entries,
8610 CXTUResourceUsage_Preprocessor,
8611 pp.getTotalMemory());
8612
8613 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8614 createCXTUResourceUsageEntry(*entries,
8615 CXTUResourceUsage_PreprocessingRecord,
8616 pRec->getTotalMemory());
8617 }
8618
8619 createCXTUResourceUsageEntry(*entries,
8620 CXTUResourceUsage_Preprocessor_HeaderSearch,
8621 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008622
Guy Benyei11169dd2012-12-18 14:30:41 +00008623 CXTUResourceUsage usage = { (void*) entries.get(),
8624 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008625 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008626 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008627 return usage;
8628}
8629
8630void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8631 if (usage.data)
8632 delete (MemUsageEntries*) usage.data;
8633}
8634
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008635CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8636 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008637 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008638 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008639
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008640 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008641 LOG_BAD_TU(TU);
8642 return skipped;
8643 }
8644
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008645 if (!file)
8646 return skipped;
8647
8648 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8649 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8650 if (!ppRec)
8651 return skipped;
8652
8653 ASTContext &Ctx = astUnit->getASTContext();
8654 SourceManager &sm = Ctx.getSourceManager();
8655 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8656 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008657 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008658
8659 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8660 std::vector<SourceRange> wantedRanges;
8661 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8662 i != ei; ++i) {
8663 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8664 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008665 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8666 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008667 }
8668
8669 skipped->count = wantedRanges.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, wantedRanges[i]);
8673
8674 return skipped;
8675}
8676
Cameron Desrochersd8091282016-08-18 15:43:55 +00008677CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8678 CXSourceRangeList *skipped = new CXSourceRangeList;
8679 skipped->count = 0;
8680 skipped->ranges = nullptr;
8681
8682 if (isNotUsableTU(TU)) {
8683 LOG_BAD_TU(TU);
8684 return skipped;
8685 }
8686
8687 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8688 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8689 if (!ppRec)
8690 return skipped;
8691
8692 ASTContext &Ctx = astUnit->getASTContext();
8693
8694 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8695
8696 skipped->count = SkippedRanges.size();
8697 skipped->ranges = new CXSourceRange[skipped->count];
8698 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8699 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8700
8701 return skipped;
8702}
8703
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008704void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8705 if (ranges) {
8706 delete[] ranges->ranges;
8707 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008708 }
8709}
8710
Guy Benyei11169dd2012-12-18 14:30:41 +00008711void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8712 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8713 for (unsigned I = 0; I != Usage.numEntries; ++I)
8714 fprintf(stderr, " %s: %lu\n",
8715 clang_getTUResourceUsageName(Usage.entries[I].kind),
8716 Usage.entries[I].amount);
8717
8718 clang_disposeCXTUResourceUsage(Usage);
8719}
8720
8721//===----------------------------------------------------------------------===//
8722// Misc. utility functions.
8723//===----------------------------------------------------------------------===//
8724
Richard Smith0a7b2972018-07-03 21:34:13 +00008725/// Default to using our desired 8 MB stack size on "safety" threads.
8726static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008727
8728namespace clang {
8729
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008730bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008731 unsigned Size) {
8732 if (!Size)
8733 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008734 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008735 return CRC.RunSafelyOnThread(Fn, Size);
8736 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008737}
8738
8739unsigned GetSafetyThreadStackSize() {
8740 return SafetyStackThreadSize;
8741}
8742
8743void SetSafetyThreadStackSize(unsigned Value) {
8744 SafetyStackThreadSize = Value;
8745}
8746
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008747}
Guy Benyei11169dd2012-12-18 14:30:41 +00008748
8749void clang::setThreadBackgroundPriority() {
8750 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8751 return;
8752
Nico Weber18cfd9f2019-04-21 19:18:41 +00008753#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008754 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008755#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008756}
8757
8758void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8759 if (!Unit)
8760 return;
8761
8762 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8763 DEnd = Unit->stored_diag_end();
8764 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008765 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008766 CXString Msg = clang_formatDiagnostic(&Diag,
8767 clang_defaultDiagnosticDisplayOptions());
8768 fprintf(stderr, "%s\n", clang_getCString(Msg));
8769 clang_disposeString(Msg);
8770 }
Nico Weber1865df42018-04-27 19:11:14 +00008771#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008772 // On Windows, force a flush, since there may be multiple copies of
8773 // stderr and stdout in the file system, all with different buffers
8774 // but writing to the same device.
8775 fflush(stderr);
8776#endif
8777}
8778
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008779MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8780 SourceLocation MacroDefLoc,
8781 CXTranslationUnit TU){
8782 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008783 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008784 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008785 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008786
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008787 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008788 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008789 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008790 if (MD) {
8791 for (MacroDirective::DefInfo
8792 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8793 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8794 return Def.getMacroInfo();
8795 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008796 }
8797
Craig Topper69186e72014-06-08 08:38:04 +00008798 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008799}
8800
Richard Smith66a81862015-05-04 02:25:31 +00008801const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008802 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008803 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008804 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008805 const IdentifierInfo *II = MacroDef->getName();
8806 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008807 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008808
8809 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8810}
8811
Richard Smith66a81862015-05-04 02:25:31 +00008812MacroDefinitionRecord *
8813cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8814 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008815 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008816 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008817 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008818 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008819
8820 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008821 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008822 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8823 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008824 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008825
8826 // Check that the token is inside the definition and not its argument list.
8827 SourceManager &SM = Unit->getSourceManager();
8828 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008829 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008830 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008831 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008832
8833 Preprocessor &PP = Unit->getPreprocessor();
8834 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8835 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008836 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008837
Alp Toker2d57cea2014-05-17 04:53:25 +00008838 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008839 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008840 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008841
8842 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008843 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008844 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008845
Richard Smith20e883e2015-04-29 23:20:19 +00008846 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008847 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008848 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008849
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008850 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008851}
8852
Richard Smith66a81862015-05-04 02:25:31 +00008853MacroDefinitionRecord *
8854cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8855 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008856 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008857 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008858
8859 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008860 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008861 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008862 Preprocessor &PP = Unit->getPreprocessor();
8863 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008864 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008865 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8866 Token Tok;
8867 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008868 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008869
8870 return checkForMacroInMacroDefinition(MI, Tok, TU);
8871}
8872
Guy Benyei11169dd2012-12-18 14:30:41 +00008873CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008874 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008875}
8876
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008877Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8878 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008879 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008880 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008881 if (Unit->isMainFileAST())
8882 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008883 return *this;
8884 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008885 } else {
8886 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008887 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008888 return *this;
8889}
8890
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008891Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8892 *this << FE->getName();
8893 return *this;
8894}
8895
8896Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8897 CXString cursorName = clang_getCursorDisplayName(cursor);
8898 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8899 clang_disposeString(cursorName);
8900 return *this;
8901}
8902
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008903Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8904 CXFile File;
8905 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008906 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008907 CXString FileName = clang_getFileName(File);
8908 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8909 clang_disposeString(FileName);
8910 return *this;
8911}
8912
8913Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8914 CXSourceLocation BLoc = clang_getRangeStart(range);
8915 CXSourceLocation ELoc = clang_getRangeEnd(range);
8916
8917 CXFile BFile;
8918 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008919 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008920
8921 CXFile EFile;
8922 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008923 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008924
8925 CXString BFileName = clang_getFileName(BFile);
8926 if (BFile == EFile) {
8927 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8928 BLine, BColumn, ELine, EColumn);
8929 } else {
8930 CXString EFileName = clang_getFileName(EFile);
8931 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8932 BLine, BColumn)
8933 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8934 ELine, EColumn);
8935 clang_disposeString(EFileName);
8936 }
8937 clang_disposeString(BFileName);
8938 return *this;
8939}
8940
8941Logger &cxindex::Logger::operator<<(CXString Str) {
8942 *this << clang_getCString(Str);
8943 return *this;
8944}
8945
8946Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8947 LogOS << Fmt;
8948 return *this;
8949}
8950
Benjamin Kramer762bc332019-08-07 14:44:40 +00008951static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00008952
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008953cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00008954 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008955
8956 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8957
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008958 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008959 OS << "[libclang:" << Name << ':';
8960
Alp Toker1a86ad22014-07-06 06:24:00 +00008961#ifdef USE_DARWIN_THREADS
8962 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008963 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8964 OS << tid << ':';
8965#endif
8966
8967 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8968 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008969 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008970
8971 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008972 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008973 OS << "--------------------------------------------------\n";
8974 }
8975}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00008976
8977#ifdef CLANG_TOOL_EXTRA_BUILD
8978// This anchor is used to force the linker to link the clang-tidy plugin.
8979extern volatile int ClangTidyPluginAnchorSource;
8980static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8981 ClangTidyPluginAnchorSource;
8982
8983// This anchor is used to force the linker to link the clang-include-fixer
8984// plugin.
8985extern volatile int ClangIncludeFixerPluginAnchorSource;
8986static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8987 ClangIncludeFixerPluginAnchorSource;
8988#endif