blob: 715618c3c0f06392d75cbd2c405b4818b66bd3a0 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the main API hooks in the Clang-C Source Indexing
10// library.
11//
12//===----------------------------------------------------------------------===//
13
Guy Benyei11169dd2012-12-18 14:30:41 +000014#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000015#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000016#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CXCursor.h"
18#include "CXSourceLocation.h"
19#include "CXString.h"
20#include "CXTranslationUnit.h"
21#include "CXType.h"
22#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000023#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/StmtVisitor.h"
25#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000026#include "clang/Basic/DiagnosticCategories.h"
27#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000028#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000029#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/Basic/Version.h"
31#include "clang/Frontend/ASTUnit.h"
32#include "clang/Frontend/CompilerInstance.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "llvm/ADT/Optional.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000042#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000043#include "llvm/Support/Compiler.h"
44#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000045#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000046#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/Support/Program.h"
50#include "llvm/Support/SaveAndRestore.h"
51#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000052#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000053#include "llvm/Support/Threading.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000056
Alp Toker1a86ad22014-07-06 06:24:00 +000057#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
58#define USE_DARWIN_THREADS
59#endif
60
61#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000062#include <pthread.h>
63#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000064
65using namespace clang;
66using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000067using namespace clang::cxtu;
68using namespace clang::cxindex;
69
David Blaikieea4395e2017-01-06 19:49:01 +000070CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
71 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000072 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000073 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000074 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000075 CXTranslationUnit D = new CXTranslationUnitImpl();
76 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000077 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000078 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000079 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000080 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000082 D->ParsingOptions = 0;
83 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000084 return D;
85}
86
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000087bool cxtu::isASTReadError(ASTUnit *AU) {
88 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
89 DEnd = AU->stored_diag_end();
90 D != DEnd; ++D) {
91 if (D->getLevel() >= DiagnosticsEngine::Error &&
92 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
93 diag::DiagCat_AST_Deserialization_Issue)
94 return true;
95 }
96 return false;
97}
98
Guy Benyei11169dd2012-12-18 14:30:41 +000099cxtu::CXTUOwner::~CXTUOwner() {
100 if (TU)
101 clang_disposeTranslationUnit(TU);
102}
103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000104/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000105/// the translation unit.
106static RangeComparisonResult RangeCompare(SourceManager &SM,
107 SourceRange R1,
108 SourceRange R2) {
109 assert(R1.isValid() && "First range is invalid?");
110 assert(R2.isValid() && "Second range is invalid?");
111 if (R1.getEnd() != R2.getBegin() &&
112 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
113 return RangeBefore;
114 if (R2.getEnd() != R1.getBegin() &&
115 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
116 return RangeAfter;
117 return RangeOverlap;
118}
119
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000120/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000121/// a given source range.
122static RangeComparisonResult LocationCompare(SourceManager &SM,
123 SourceLocation L, SourceRange R) {
124 assert(R.isValid() && "First range is invalid?");
125 assert(L.isValid() && "Second range is invalid?");
126 if (L == R.getBegin() || L == R.getEnd())
127 return RangeOverlap;
128 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
129 return RangeBefore;
130 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
131 return RangeAfter;
132 return RangeOverlap;
133}
134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000135/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000136///
137/// Clang internally represents ranges where the end location points to the
138/// start of the token at the end. However, for external clients it is more
139/// useful to have a CXSourceRange be a proper half-open interval. This routine
140/// does the appropriate translation.
141CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
142 const LangOptions &LangOpts,
143 const CharSourceRange &R) {
144 // We want the last character in this location, so we will adjust the
145 // location accordingly.
146 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000147 bool IsTokenRange = R.isTokenRange();
148 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
149 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
150 EndLoc = Expansion.getEnd();
151 IsTokenRange = Expansion.isTokenRange();
152 }
153 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000154 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
155 SM, LangOpts);
156 EndLoc = EndLoc.getLocWithOffset(Length);
157 }
158
Bill Wendlingeade3622013-01-23 08:25:41 +0000159 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000160 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000161 R.getBegin().getRawEncoding(),
162 EndLoc.getRawEncoding()
163 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000164 return Result;
165}
166
167//===----------------------------------------------------------------------===//
168// Cursor visitor.
169//===----------------------------------------------------------------------===//
170
171static SourceRange getRawCursorExtent(CXCursor C);
172static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
173
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:
Guy Benyei11169dd2012-12-18 14:30:41 +00001530#define BUILTIN_TYPE(Id, SingletonId)
1531#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1532#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1533#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1534#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1535#include "clang/AST/BuiltinTypes.def"
1536 break;
1537
1538 case BuiltinType::ObjCId:
1539 VisitType = Context.getObjCIdType();
1540 break;
1541
1542 case BuiltinType::ObjCClass:
1543 VisitType = Context.getObjCClassType();
1544 break;
1545
1546 case BuiltinType::ObjCSel:
1547 VisitType = Context.getObjCSelType();
1548 break;
1549 }
1550
1551 if (!VisitType.isNull()) {
1552 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1553 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1554 TU));
1555 }
1556
1557 return false;
1558}
1559
1560bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1561 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1562}
1563
1564bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1565 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1566}
1567
1568bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1569 if (TL.isDefinition())
1570 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1571
1572 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1573}
1574
1575bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1576 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1577}
1578
1579bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001580 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001581}
1582
Manman Rene6be26c2016-09-13 17:25:08 +00001583bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001584 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001585 return true;
1586 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1587 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1588 TU)))
1589 return true;
1590 }
1591
1592 return false;
1593}
1594
Guy Benyei11169dd2012-12-18 14:30:41 +00001595bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1596 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1597 return true;
1598
Douglas Gregore9d95f12015-07-07 03:57:35 +00001599 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1600 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1601 return true;
1602 }
1603
Guy Benyei11169dd2012-12-18 14:30:41 +00001604 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1605 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1606 TU)))
1607 return true;
1608 }
1609
1610 return false;
1611}
1612
1613bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1614 return Visit(TL.getPointeeLoc());
1615}
1616
1617bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1618 return Visit(TL.getInnerLoc());
1619}
1620
Leonard Chanc72aaf62019-05-07 03:20:17 +00001621bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1622 return Visit(TL.getInnerLoc());
1623}
1624
Guy Benyei11169dd2012-12-18 14:30:41 +00001625bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1626 return Visit(TL.getPointeeLoc());
1627}
1628
1629bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1630 return Visit(TL.getPointeeLoc());
1631}
1632
1633bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1634 return Visit(TL.getPointeeLoc());
1635}
1636
1637bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1638 return Visit(TL.getPointeeLoc());
1639}
1640
1641bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1642 return Visit(TL.getPointeeLoc());
1643}
1644
1645bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1646 return Visit(TL.getModifiedLoc());
1647}
1648
1649bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1650 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001651 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 return true;
1653
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001654 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1655 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1657 return true;
1658
1659 return false;
1660}
1661
1662bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1663 if (Visit(TL.getElementLoc()))
1664 return true;
1665
1666 if (Expr *Size = TL.getSizeExpr())
1667 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1668
1669 return false;
1670}
1671
Reid Kleckner8a365022013-06-24 17:51:48 +00001672bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1673 return Visit(TL.getOriginalLoc());
1674}
1675
Reid Kleckner0503a872013-12-05 01:23:43 +00001676bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1677 return Visit(TL.getOriginalLoc());
1678}
1679
Richard Smith600b5262017-01-26 20:40:47 +00001680bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1681 DeducedTemplateSpecializationTypeLoc TL) {
1682 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1683 TL.getTemplateNameLoc()))
1684 return true;
1685
1686 return false;
1687}
1688
Guy Benyei11169dd2012-12-18 14:30:41 +00001689bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1690 TemplateSpecializationTypeLoc TL) {
1691 // Visit the template name.
1692 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1693 TL.getTemplateNameLoc()))
1694 return true;
1695
1696 // Visit the template arguments.
1697 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1698 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1699 return true;
1700
1701 return false;
1702}
1703
1704bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1705 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1706}
1707
1708bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1709 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1710 return Visit(TSInfo->getTypeLoc());
1711
1712 return false;
1713}
1714
1715bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1716 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1717 return Visit(TSInfo->getTypeLoc());
1718
1719 return false;
1720}
1721
1722bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001723 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001724}
1725
1726bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1727 DependentTemplateSpecializationTypeLoc TL) {
1728 // Visit the nested-name-specifier, if there is one.
1729 if (TL.getQualifierLoc() &&
1730 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1731 return true;
1732
1733 // Visit the template arguments.
1734 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1735 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1736 return true;
1737
1738 return false;
1739}
1740
1741bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1742 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1743 return true;
1744
1745 return Visit(TL.getNamedTypeLoc());
1746}
1747
1748bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1749 return Visit(TL.getPatternLoc());
1750}
1751
1752bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1753 if (Expr *E = TL.getUnderlyingExpr())
1754 return Visit(MakeCXCursor(E, StmtParent, TU));
1755
1756 return false;
1757}
1758
1759bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1760 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1761}
1762
1763bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1764 return Visit(TL.getValueLoc());
1765}
1766
Xiuli Pan9c14e282016-01-09 12:53:17 +00001767bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1768 return Visit(TL.getValueLoc());
1769}
1770
Guy Benyei11169dd2012-12-18 14:30:41 +00001771#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1772bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1773 return Visit##PARENT##Loc(TL); \
1774}
1775
1776DEFAULT_TYPELOC_IMPL(Complex, Type)
1777DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1778DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1779DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1780DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001781DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001782DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001783DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1784DEFAULT_TYPELOC_IMPL(Vector, Type)
1785DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1786DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1787DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1788DEFAULT_TYPELOC_IMPL(Record, TagType)
1789DEFAULT_TYPELOC_IMPL(Enum, TagType)
1790DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1791DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1792DEFAULT_TYPELOC_IMPL(Auto, Type)
1793
1794bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1795 // Visit the nested-name-specifier, if present.
1796 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1797 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1798 return true;
1799
1800 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001801 for (const auto &I : D->bases()) {
1802 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001803 return true;
1804 }
1805 }
1806
1807 return VisitTagDecl(D);
1808}
1809
1810bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001811 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001812 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1813 !I->isImplicit()) &&
1814 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001815 return true;
1816
1817 return false;
1818}
1819
1820//===----------------------------------------------------------------------===//
1821// Data-recursive visitor methods.
1822//===----------------------------------------------------------------------===//
1823
1824namespace {
1825#define DEF_JOB(NAME, DATA, KIND)\
1826class NAME : public VisitorJob {\
1827public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001828 NAME(const DATA *d, CXCursor parent) : \
1829 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001831 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001832};
1833
1834DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1835DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1836DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1837DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001838DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1839DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1840DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1841#undef DEF_JOB
1842
James Y Knight04ec5bf2015-12-24 02:59:37 +00001843class ExplicitTemplateArgsVisit : public VisitorJob {
1844public:
1845 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1846 const TemplateArgumentLoc *End, CXCursor parent)
1847 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1848 End) {}
1849 static bool classof(const VisitorJob *VJ) {
1850 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1851 }
1852 const TemplateArgumentLoc *begin() const {
1853 return static_cast<const TemplateArgumentLoc *>(data[0]);
1854 }
1855 const TemplateArgumentLoc *end() {
1856 return static_cast<const TemplateArgumentLoc *>(data[1]);
1857 }
1858};
Guy Benyei11169dd2012-12-18 14:30:41 +00001859class DeclVisit : public VisitorJob {
1860public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001861 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001862 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001863 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001864 static bool classof(const VisitorJob *VJ) {
1865 return VJ->getKind() == DeclVisitKind;
1866 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001867 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001868 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001869};
1870class TypeLocVisit : public VisitorJob {
1871public:
1872 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1873 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1874 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1875
1876 static bool classof(const VisitorJob *VJ) {
1877 return VJ->getKind() == TypeLocVisitKind;
1878 }
1879
1880 TypeLoc get() const {
1881 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001882 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001883 }
1884};
1885
1886class LabelRefVisit : public VisitorJob {
1887public:
1888 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1889 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1890 labelLoc.getPtrEncoding()) {}
1891
1892 static bool classof(const VisitorJob *VJ) {
1893 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1894 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001895 const LabelDecl *get() const {
1896 return static_cast<const LabelDecl *>(data[0]);
1897 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001898 SourceLocation getLoc() const {
1899 return SourceLocation::getFromPtrEncoding(data[1]); }
1900};
1901
1902class NestedNameSpecifierLocVisit : public VisitorJob {
1903public:
1904 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1905 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1906 Qualifier.getNestedNameSpecifier(),
1907 Qualifier.getOpaqueData()) { }
1908
1909 static bool classof(const VisitorJob *VJ) {
1910 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1911 }
1912
1913 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001914 return NestedNameSpecifierLoc(
1915 const_cast<NestedNameSpecifier *>(
1916 static_cast<const NestedNameSpecifier *>(data[0])),
1917 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001918 }
1919};
1920
1921class DeclarationNameInfoVisit : public VisitorJob {
1922public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001923 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001924 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001925 static bool classof(const VisitorJob *VJ) {
1926 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1927 }
1928 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001929 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001930 switch (S->getStmtClass()) {
1931 default:
1932 llvm_unreachable("Unhandled Stmt");
1933 case clang::Stmt::MSDependentExistsStmtClass:
1934 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1935 case Stmt::CXXDependentScopeMemberExprClass:
1936 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1937 case Stmt::DependentScopeDeclRefExprClass:
1938 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001939 case Stmt::OMPCriticalDirectiveClass:
1940 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001941 }
1942 }
1943};
1944class MemberRefVisit : public VisitorJob {
1945public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001946 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001947 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1948 L.getPtrEncoding()) {}
1949 static bool classof(const VisitorJob *VJ) {
1950 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1951 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001952 const FieldDecl *get() const {
1953 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 }
1955 SourceLocation getLoc() const {
1956 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1957 }
1958};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001959class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001960 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001961 VisitorWorkList &WL;
1962 CXCursor Parent;
1963public:
1964 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1965 : WL(wl), Parent(parent) {}
1966
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001967 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1968 void VisitBlockExpr(const BlockExpr *B);
1969 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1970 void VisitCompoundStmt(const CompoundStmt *S);
1971 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1972 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1973 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1974 void VisitCXXNewExpr(const CXXNewExpr *E);
1975 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1976 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1977 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1978 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1979 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1980 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1981 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1982 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001983 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001984 void VisitDeclRefExpr(const DeclRefExpr *D);
1985 void VisitDeclStmt(const DeclStmt *S);
1986 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1987 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1988 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1989 void VisitForStmt(const ForStmt *FS);
1990 void VisitGotoStmt(const GotoStmt *GS);
1991 void VisitIfStmt(const IfStmt *If);
1992 void VisitInitListExpr(const InitListExpr *IE);
1993 void VisitMemberExpr(const MemberExpr *M);
1994 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1995 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1996 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1997 void VisitOverloadExpr(const OverloadExpr *E);
1998 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1999 void VisitStmt(const Stmt *S);
2000 void VisitSwitchStmt(const SwitchStmt *S);
2001 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002002 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2003 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2004 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2005 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2006 void VisitVAArgExpr(const VAArgExpr *E);
2007 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2008 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2009 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2010 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002011 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002012 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002013 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002014 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002015 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002016 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002017 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002018 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002019 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002020 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002021 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002022 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002023 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002024 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002025 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002026 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002027 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002028 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002029 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002030 void
2031 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002032 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002033 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002034 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002035 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002036 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002037 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002038 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002039 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002040 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002041 void
2042 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002043 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002044 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002045 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002046 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002047 void VisitOMPDistributeParallelForDirective(
2048 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002049 void VisitOMPDistributeParallelForSimdDirective(
2050 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002051 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002052 void VisitOMPTargetParallelForSimdDirective(
2053 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002054 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002055 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002056 void VisitOMPTeamsDistributeSimdDirective(
2057 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002058 void VisitOMPTeamsDistributeParallelForSimdDirective(
2059 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002060 void VisitOMPTeamsDistributeParallelForDirective(
2061 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002062 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002063 void VisitOMPTargetTeamsDistributeDirective(
2064 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002065 void VisitOMPTargetTeamsDistributeParallelForDirective(
2066 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002067 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2068 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002069 void VisitOMPTargetTeamsDistributeSimdDirective(
2070 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002071
Guy Benyei11169dd2012-12-18 14:30:41 +00002072private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002073 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002074 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002075 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2076 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002077 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2078 void AddStmt(const Stmt *S);
2079 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002081 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002082 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002083};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002084} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002085
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002086void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002087 // 'S' should always be non-null, since it comes from the
2088 // statement we are visiting.
2089 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2090}
2091
2092void
2093EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2094 if (Qualifier)
2095 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2096}
2097
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002098void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002099 if (S)
2100 WL.push_back(StmtVisit(S, Parent));
2101}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002102void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002103 if (D)
2104 WL.push_back(DeclVisit(D, Parent, isFirst));
2105}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002106void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2107 unsigned NumTemplateArgs) {
2108 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002109}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002110void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 if (D)
2112 WL.push_back(MemberRefVisit(D, L, Parent));
2113}
2114void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2115 if (TI)
2116 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2117 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002118void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002120 for (const Stmt *SubStmt : S->children()) {
2121 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002122 }
2123 if (size == WL.size())
2124 return;
2125 // Now reverse the entries we just added. This will match the DFS
2126 // ordering performed by the worklist.
2127 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2128 std::reverse(I, E);
2129}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002130namespace {
2131class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2132 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002133 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002134 template <typename T>
2135 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002136public:
2137 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2138#define OPENMP_CLAUSE(Name, Class) \
2139 void Visit##Class(const Class *C);
2140#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002141 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002142 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002143};
2144
Alexey Bataev3392d762016-02-16 11:18:12 +00002145void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2146 const OMPClauseWithPreInit *C) {
2147 Visitor->AddStmt(C->getPreInitStmt());
2148}
2149
Alexey Bataev005248a2016-02-25 05:25:57 +00002150void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2151 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002152 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002153 Visitor->AddStmt(C->getPostUpdateExpr());
2154}
2155
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002156void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002157 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002158 Visitor->AddStmt(C->getCondition());
2159}
2160
Alexey Bataev3778b602014-07-17 07:32:53 +00002161void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2162 Visitor->AddStmt(C->getCondition());
2163}
2164
Alexey Bataev568a8332014-03-06 06:15:19 +00002165void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002166 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002167 Visitor->AddStmt(C->getNumThreads());
2168}
2169
Alexey Bataev62c87d22014-03-21 04:51:18 +00002170void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2171 Visitor->AddStmt(C->getSafelen());
2172}
2173
Alexey Bataev66b15b52015-08-21 11:14:16 +00002174void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2175 Visitor->AddStmt(C->getSimdlen());
2176}
2177
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002178void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2179 Visitor->AddStmt(C->getAllocator());
2180}
2181
Alexander Musman8bd31e62014-05-27 15:12:19 +00002182void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2183 Visitor->AddStmt(C->getNumForLoops());
2184}
2185
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002186void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002187
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002188void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2189
Alexey Bataev56dafe82014-06-20 07:16:17 +00002190void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002191 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002192 Visitor->AddStmt(C->getChunkSize());
2193}
2194
Alexey Bataev10e775f2015-07-30 11:36:16 +00002195void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2196 Visitor->AddStmt(C->getNumForLoops());
2197}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002198
Alexey Bataev236070f2014-06-20 11:19:47 +00002199void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2200
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002201void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2202
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002203void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2204
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002205void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2206
Alexey Bataevdea47612014-07-23 07:46:59 +00002207void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2208
Alexey Bataev67a4f222014-07-23 10:25:33 +00002209void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2210
Alexey Bataev459dec02014-07-24 06:46:57 +00002211void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2212
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002213void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2214
Alexey Bataev346265e2015-09-25 10:37:12 +00002215void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2216
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002217void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2218
Alexey Bataevb825de12015-12-07 10:51:44 +00002219void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2220
Kelvin Li1408f912018-09-26 04:28:39 +00002221void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2222 const OMPUnifiedAddressClause *) {}
2223
Patrick Lyster4a370b92018-10-01 13:47:43 +00002224void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2225 const OMPUnifiedSharedMemoryClause *) {}
2226
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002227void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2228 const OMPReverseOffloadClause *) {}
2229
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002230void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2231 const OMPDynamicAllocatorsClause *) {}
2232
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002233void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2234 const OMPAtomicDefaultMemOrderClause *) {}
2235
Michael Wonge710d542015-08-07 16:16:36 +00002236void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2237 Visitor->AddStmt(C->getDevice());
2238}
2239
Kelvin Li099bb8c2015-11-24 20:50:12 +00002240void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002241 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002242 Visitor->AddStmt(C->getNumTeams());
2243}
2244
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002245void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002246 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002247 Visitor->AddStmt(C->getThreadLimit());
2248}
2249
Alexey Bataeva0569352015-12-01 10:17:31 +00002250void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2251 Visitor->AddStmt(C->getPriority());
2252}
2253
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002254void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2255 Visitor->AddStmt(C->getGrainsize());
2256}
2257
Alexey Bataev382967a2015-12-08 12:06:20 +00002258void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2259 Visitor->AddStmt(C->getNumTasks());
2260}
2261
Alexey Bataev28c75412015-12-15 08:19:24 +00002262void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2263 Visitor->AddStmt(C->getHint());
2264}
2265
Alexey Bataev756c1962013-09-24 03:17:45 +00002266template<typename T>
2267void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002268 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002269 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002270 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002271}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002272
Alexey Bataeve04483e2019-03-27 14:14:31 +00002273void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2274 VisitOMPClauseList(C);
2275 Visitor->AddStmt(C->getAllocator());
2276}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002277void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002278 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002279 for (const auto *E : C->private_copies()) {
2280 Visitor->AddStmt(E);
2281 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002282}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002283void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2284 const OMPFirstprivateClause *C) {
2285 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002286 VisitOMPClauseWithPreInit(C);
2287 for (const auto *E : C->private_copies()) {
2288 Visitor->AddStmt(E);
2289 }
2290 for (const auto *E : C->inits()) {
2291 Visitor->AddStmt(E);
2292 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002293}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002294void OMPClauseEnqueue::VisitOMPLastprivateClause(
2295 const OMPLastprivateClause *C) {
2296 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002297 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002298 for (auto *E : C->private_copies()) {
2299 Visitor->AddStmt(E);
2300 }
2301 for (auto *E : C->source_exprs()) {
2302 Visitor->AddStmt(E);
2303 }
2304 for (auto *E : C->destination_exprs()) {
2305 Visitor->AddStmt(E);
2306 }
2307 for (auto *E : C->assignment_ops()) {
2308 Visitor->AddStmt(E);
2309 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002310}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002311void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002312 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002313}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002314void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2315 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002316 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002317 for (auto *E : C->privates()) {
2318 Visitor->AddStmt(E);
2319 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002320 for (auto *E : C->lhs_exprs()) {
2321 Visitor->AddStmt(E);
2322 }
2323 for (auto *E : C->rhs_exprs()) {
2324 Visitor->AddStmt(E);
2325 }
2326 for (auto *E : C->reduction_ops()) {
2327 Visitor->AddStmt(E);
2328 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002329}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002330void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2331 const OMPTaskReductionClause *C) {
2332 VisitOMPClauseList(C);
2333 VisitOMPClauseWithPostUpdate(C);
2334 for (auto *E : C->privates()) {
2335 Visitor->AddStmt(E);
2336 }
2337 for (auto *E : C->lhs_exprs()) {
2338 Visitor->AddStmt(E);
2339 }
2340 for (auto *E : C->rhs_exprs()) {
2341 Visitor->AddStmt(E);
2342 }
2343 for (auto *E : C->reduction_ops()) {
2344 Visitor->AddStmt(E);
2345 }
2346}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002347void OMPClauseEnqueue::VisitOMPInReductionClause(
2348 const OMPInReductionClause *C) {
2349 VisitOMPClauseList(C);
2350 VisitOMPClauseWithPostUpdate(C);
2351 for (auto *E : C->privates()) {
2352 Visitor->AddStmt(E);
2353 }
2354 for (auto *E : C->lhs_exprs()) {
2355 Visitor->AddStmt(E);
2356 }
2357 for (auto *E : C->rhs_exprs()) {
2358 Visitor->AddStmt(E);
2359 }
2360 for (auto *E : C->reduction_ops()) {
2361 Visitor->AddStmt(E);
2362 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002363 for (auto *E : C->taskgroup_descriptors())
2364 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002365}
Alexander Musman8dba6642014-04-22 13:09:42 +00002366void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2367 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002368 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002369 for (const auto *E : C->privates()) {
2370 Visitor->AddStmt(E);
2371 }
Alexander Musman3276a272015-03-21 10:12:56 +00002372 for (const auto *E : C->inits()) {
2373 Visitor->AddStmt(E);
2374 }
2375 for (const auto *E : C->updates()) {
2376 Visitor->AddStmt(E);
2377 }
2378 for (const auto *E : C->finals()) {
2379 Visitor->AddStmt(E);
2380 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002381 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002382 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002383}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002384void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2385 VisitOMPClauseList(C);
2386 Visitor->AddStmt(C->getAlignment());
2387}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002388void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2389 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002390 for (auto *E : C->source_exprs()) {
2391 Visitor->AddStmt(E);
2392 }
2393 for (auto *E : C->destination_exprs()) {
2394 Visitor->AddStmt(E);
2395 }
2396 for (auto *E : C->assignment_ops()) {
2397 Visitor->AddStmt(E);
2398 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002399}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002400void
2401OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2402 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002403 for (auto *E : C->source_exprs()) {
2404 Visitor->AddStmt(E);
2405 }
2406 for (auto *E : C->destination_exprs()) {
2407 Visitor->AddStmt(E);
2408 }
2409 for (auto *E : C->assignment_ops()) {
2410 Visitor->AddStmt(E);
2411 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002412}
Alexey Bataev6125da92014-07-21 11:26:11 +00002413void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2414 VisitOMPClauseList(C);
2415}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002416void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2417 VisitOMPClauseList(C);
2418}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002419void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2420 VisitOMPClauseList(C);
2421}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002422void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2423 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002424 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002425 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002426}
Alexey Bataev3392d762016-02-16 11:18:12 +00002427void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2428 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002429void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2430 VisitOMPClauseList(C);
2431}
Samuel Antaoec172c62016-05-26 17:49:04 +00002432void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2433 VisitOMPClauseList(C);
2434}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002435void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2436 VisitOMPClauseList(C);
2437}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002438void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2439 VisitOMPClauseList(C);
2440}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002441}
Alexey Bataev756c1962013-09-24 03:17:45 +00002442
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002443void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2444 unsigned size = WL.size();
2445 OMPClauseEnqueue Visitor(this);
2446 Visitor.Visit(S);
2447 if (size == WL.size())
2448 return;
2449 // Now reverse the entries we just added. This will match the DFS
2450 // ordering performed by the worklist.
2451 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2452 std::reverse(I, E);
2453}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002454void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2456}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002457void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 AddDecl(B->getBlockDecl());
2459}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002460void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002461 EnqueueChildren(E);
2462 AddTypeLoc(E->getTypeSourceInfo());
2463}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002464void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002465 for (auto &I : llvm::reverse(S->body()))
2466 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002467}
2468void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002469VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 AddStmt(S->getSubStmt());
2471 AddDeclarationNameInfo(S);
2472 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2473 AddNestedNameSpecifierLoc(QualifierLoc);
2474}
2475
2476void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002477VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002478 if (E->hasExplicitTemplateArgs())
2479 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 AddDeclarationNameInfo(E);
2481 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2482 AddNestedNameSpecifierLoc(QualifierLoc);
2483 if (!E->isImplicitAccess())
2484 AddStmt(E->getBase());
2485}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002486void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 // Enqueue the initializer , if any.
2488 AddStmt(E->getInitializer());
2489 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002490 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 // Enqueue the allocated type.
2492 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2493 // Enqueue the placement arguments.
2494 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2495 AddStmt(E->getPlacementArg(I-1));
2496}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002497void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2499 AddStmt(CE->getArg(I-1));
2500 AddStmt(CE->getCallee());
2501 AddStmt(CE->getArg(0));
2502}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002503void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2504 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 // Visit the name of the type being destroyed.
2506 AddTypeLoc(E->getDestroyedTypeInfo());
2507 // Visit the scope type that looks disturbingly like the nested-name-specifier
2508 // but isn't.
2509 AddTypeLoc(E->getScopeTypeInfo());
2510 // Visit the nested-name-specifier.
2511 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2512 AddNestedNameSpecifierLoc(QualifierLoc);
2513 // Visit base expression.
2514 AddStmt(E->getBase());
2515}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002516void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2517 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 AddTypeLoc(E->getTypeSourceInfo());
2519}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002520void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2521 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 EnqueueChildren(E);
2523 AddTypeLoc(E->getTypeSourceInfo());
2524}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002525void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 EnqueueChildren(E);
2527 if (E->isTypeOperand())
2528 AddTypeLoc(E->getTypeOperandSourceInfo());
2529}
2530
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002531void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2532 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 EnqueueChildren(E);
2534 AddTypeLoc(E->getTypeSourceInfo());
2535}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002536void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 EnqueueChildren(E);
2538 if (E->isTypeOperand())
2539 AddTypeLoc(E->getTypeOperandSourceInfo());
2540}
2541
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002542void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 EnqueueChildren(S);
2544 AddDecl(S->getExceptionDecl());
2545}
2546
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002547void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002548 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002549 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002550 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002551}
2552
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002553void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002554 if (DR->hasExplicitTemplateArgs())
2555 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 WL.push_back(DeclRefExprParts(DR, Parent));
2557}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002558void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2559 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002560 if (E->hasExplicitTemplateArgs())
2561 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 AddDeclarationNameInfo(E);
2563 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2564}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002565void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 unsigned size = WL.size();
2567 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002568 for (const auto *D : S->decls()) {
2569 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 isFirst = false;
2571 }
2572 if (size == WL.size())
2573 return;
2574 // Now reverse the entries we just added. This will match the DFS
2575 // ordering performed by the worklist.
2576 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2577 std::reverse(I, E);
2578}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002579void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002581 for (const DesignatedInitExpr::Designator &D :
2582 llvm::reverse(E->designators())) {
2583 if (D.isFieldDesignator()) {
2584 if (FieldDecl *Field = D.getField())
2585 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 continue;
2587 }
David Majnemerf7e36092016-06-23 00:15:04 +00002588 if (D.isArrayDesignator()) {
2589 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 continue;
2591 }
David Majnemerf7e36092016-06-23 00:15:04 +00002592 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2593 AddStmt(E->getArrayRangeEnd(D));
2594 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 }
2596}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002597void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 EnqueueChildren(E);
2599 AddTypeLoc(E->getTypeInfoAsWritten());
2600}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002601void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 AddStmt(FS->getBody());
2603 AddStmt(FS->getInc());
2604 AddStmt(FS->getCond());
2605 AddDecl(FS->getConditionVariable());
2606 AddStmt(FS->getInit());
2607}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002608void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2610}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002611void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 AddStmt(If->getElse());
2613 AddStmt(If->getThen());
2614 AddStmt(If->getCond());
2615 AddDecl(If->getConditionVariable());
2616}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002617void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 // We care about the syntactic form of the initializer list, only.
2619 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2620 IE = Syntactic;
2621 EnqueueChildren(IE);
2622}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002623void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 WL.push_back(MemberExprParts(M, Parent));
2625
2626 // If the base of the member access expression is an implicit 'this', don't
2627 // visit it.
2628 // FIXME: If we ever want to show these implicit accesses, this will be
2629 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002630 if (M->isImplicitAccess())
2631 return;
2632
2633 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002634 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002635 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2636 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2637 if (FD->isAnonymousStructOrUnion()) {
2638 AddStmt(SubME->getBase());
2639 return;
2640 }
2641 }
2642 }
2643
2644 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002645}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002646void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 AddTypeLoc(E->getEncodedTypeSourceInfo());
2648}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002649void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 EnqueueChildren(M);
2651 AddTypeLoc(M->getClassReceiverTypeInfo());
2652}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002653void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 // Visit the components of the offsetof expression.
2655 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 const OffsetOfNode &Node = E->getComponent(I-1);
2657 switch (Node.getKind()) {
2658 case OffsetOfNode::Array:
2659 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2660 break;
2661 case OffsetOfNode::Field:
2662 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2663 break;
2664 case OffsetOfNode::Identifier:
2665 case OffsetOfNode::Base:
2666 continue;
2667 }
2668 }
2669 // Visit the type into which we're computing the offset.
2670 AddTypeLoc(E->getTypeSourceInfo());
2671}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002672void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002673 if (E->hasExplicitTemplateArgs())
2674 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 WL.push_back(OverloadExprParts(E, Parent));
2676}
2677void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002678 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 EnqueueChildren(E);
2680 if (E->isArgumentType())
2681 AddTypeLoc(E->getArgumentTypeInfo());
2682}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002683void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 EnqueueChildren(S);
2685}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002686void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 AddStmt(S->getBody());
2688 AddStmt(S->getCond());
2689 AddDecl(S->getConditionVariable());
2690}
2691
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002692void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 AddStmt(W->getBody());
2694 AddStmt(W->getCond());
2695 AddDecl(W->getConditionVariable());
2696}
2697
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002698void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 for (unsigned I = E->getNumArgs(); I > 0; --I)
2700 AddTypeLoc(E->getArg(I-1));
2701}
2702
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002703void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 AddTypeLoc(E->getQueriedTypeSourceInfo());
2705}
2706
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002707void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 EnqueueChildren(E);
2709}
2710
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002711void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 VisitOverloadExpr(U);
2713 if (!U->isImplicitAccess())
2714 AddStmt(U->getBase());
2715}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002716void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 AddStmt(E->getSubExpr());
2718 AddTypeLoc(E->getWrittenTypeInfo());
2719}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002720void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 WL.push_back(SizeOfPackExprParts(E, Parent));
2722}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002723void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 // If the opaque value has a source expression, just transparently
2725 // visit that. This is useful for (e.g.) pseudo-object expressions.
2726 if (Expr *SourceExpr = E->getSourceExpr())
2727 return Visit(SourceExpr);
2728}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002729void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 AddStmt(E->getBody());
2731 WL.push_back(LambdaExprParts(E, Parent));
2732}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002733void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 // Treat the expression like its syntactic form.
2735 Visit(E->getSyntacticForm());
2736}
2737
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002738void EnqueueVisitor::VisitOMPExecutableDirective(
2739 const OMPExecutableDirective *D) {
2740 EnqueueChildren(D);
2741 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2742 E = D->clauses().end();
2743 I != E; ++I)
2744 EnqueueChildren(*I);
2745}
2746
Alexander Musman3aaab662014-08-19 11:27:13 +00002747void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2748 VisitOMPExecutableDirective(D);
2749}
2750
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002751void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2752 VisitOMPExecutableDirective(D);
2753}
2754
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002755void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002756 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002757}
2758
Alexey Bataevf29276e2014-06-18 04:14:57 +00002759void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002760 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002761}
2762
Alexander Musmanf82886e2014-09-18 05:12:34 +00002763void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2764 VisitOMPLoopDirective(D);
2765}
2766
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002767void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2768 VisitOMPExecutableDirective(D);
2769}
2770
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002771void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2772 VisitOMPExecutableDirective(D);
2773}
2774
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002775void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2776 VisitOMPExecutableDirective(D);
2777}
2778
Alexander Musman80c22892014-07-17 08:54:58 +00002779void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2780 VisitOMPExecutableDirective(D);
2781}
2782
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002783void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2784 VisitOMPExecutableDirective(D);
2785 AddDeclarationNameInfo(D);
2786}
2787
Alexey Bataev4acb8592014-07-07 13:01:15 +00002788void
2789EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002790 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002791}
2792
Alexander Musmane4e893b2014-09-23 09:33:00 +00002793void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2794 const OMPParallelForSimdDirective *D) {
2795 VisitOMPLoopDirective(D);
2796}
2797
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002798void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2799 const OMPParallelSectionsDirective *D) {
2800 VisitOMPExecutableDirective(D);
2801}
2802
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002803void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2804 VisitOMPExecutableDirective(D);
2805}
2806
Alexey Bataev68446b72014-07-18 07:47:19 +00002807void
2808EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2809 VisitOMPExecutableDirective(D);
2810}
2811
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002812void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2813 VisitOMPExecutableDirective(D);
2814}
2815
Alexey Bataev2df347a2014-07-18 10:17:07 +00002816void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2817 VisitOMPExecutableDirective(D);
2818}
2819
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002820void EnqueueVisitor::VisitOMPTaskgroupDirective(
2821 const OMPTaskgroupDirective *D) {
2822 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002823 if (const Expr *E = D->getReductionRef())
2824 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002825}
2826
Alexey Bataev6125da92014-07-21 11:26:11 +00002827void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2828 VisitOMPExecutableDirective(D);
2829}
2830
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002831void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2832 VisitOMPExecutableDirective(D);
2833}
2834
Alexey Bataev0162e452014-07-22 10:10:35 +00002835void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2836 VisitOMPExecutableDirective(D);
2837}
2838
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002839void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2840 VisitOMPExecutableDirective(D);
2841}
2842
Michael Wong65f367f2015-07-21 13:44:28 +00002843void EnqueueVisitor::VisitOMPTargetDataDirective(const
2844 OMPTargetDataDirective *D) {
2845 VisitOMPExecutableDirective(D);
2846}
2847
Samuel Antaodf67fc42016-01-19 19:15:56 +00002848void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2849 const OMPTargetEnterDataDirective *D) {
2850 VisitOMPExecutableDirective(D);
2851}
2852
Samuel Antao72590762016-01-19 20:04:50 +00002853void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2854 const OMPTargetExitDataDirective *D) {
2855 VisitOMPExecutableDirective(D);
2856}
2857
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002858void EnqueueVisitor::VisitOMPTargetParallelDirective(
2859 const OMPTargetParallelDirective *D) {
2860 VisitOMPExecutableDirective(D);
2861}
2862
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002863void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2864 const OMPTargetParallelForDirective *D) {
2865 VisitOMPLoopDirective(D);
2866}
2867
Alexey Bataev13314bf2014-10-09 04:18:56 +00002868void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2869 VisitOMPExecutableDirective(D);
2870}
2871
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002872void EnqueueVisitor::VisitOMPCancellationPointDirective(
2873 const OMPCancellationPointDirective *D) {
2874 VisitOMPExecutableDirective(D);
2875}
2876
Alexey Bataev80909872015-07-02 11:25:17 +00002877void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2878 VisitOMPExecutableDirective(D);
2879}
2880
Alexey Bataev49f6e782015-12-01 04:18:41 +00002881void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2882 VisitOMPLoopDirective(D);
2883}
2884
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002885void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2886 const OMPTaskLoopSimdDirective *D) {
2887 VisitOMPLoopDirective(D);
2888}
2889
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002890void EnqueueVisitor::VisitOMPDistributeDirective(
2891 const OMPDistributeDirective *D) {
2892 VisitOMPLoopDirective(D);
2893}
2894
Carlo Bertolli9925f152016-06-27 14:55:37 +00002895void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2896 const OMPDistributeParallelForDirective *D) {
2897 VisitOMPLoopDirective(D);
2898}
2899
Kelvin Li4a39add2016-07-05 05:00:15 +00002900void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2901 const OMPDistributeParallelForSimdDirective *D) {
2902 VisitOMPLoopDirective(D);
2903}
2904
Kelvin Li787f3fc2016-07-06 04:45:38 +00002905void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2906 const OMPDistributeSimdDirective *D) {
2907 VisitOMPLoopDirective(D);
2908}
2909
Kelvin Lia579b912016-07-14 02:54:56 +00002910void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2911 const OMPTargetParallelForSimdDirective *D) {
2912 VisitOMPLoopDirective(D);
2913}
2914
Kelvin Li986330c2016-07-20 22:57:10 +00002915void EnqueueVisitor::VisitOMPTargetSimdDirective(
2916 const OMPTargetSimdDirective *D) {
2917 VisitOMPLoopDirective(D);
2918}
2919
Kelvin Li02532872016-08-05 14:37:37 +00002920void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2921 const OMPTeamsDistributeDirective *D) {
2922 VisitOMPLoopDirective(D);
2923}
2924
Kelvin Li4e325f72016-10-25 12:50:55 +00002925void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2926 const OMPTeamsDistributeSimdDirective *D) {
2927 VisitOMPLoopDirective(D);
2928}
2929
Kelvin Li579e41c2016-11-30 23:51:03 +00002930void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2931 const OMPTeamsDistributeParallelForSimdDirective *D) {
2932 VisitOMPLoopDirective(D);
2933}
2934
Kelvin Li7ade93f2016-12-09 03:24:30 +00002935void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2936 const OMPTeamsDistributeParallelForDirective *D) {
2937 VisitOMPLoopDirective(D);
2938}
2939
Kelvin Libf594a52016-12-17 05:48:59 +00002940void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2941 const OMPTargetTeamsDirective *D) {
2942 VisitOMPExecutableDirective(D);
2943}
2944
Kelvin Li83c451e2016-12-25 04:52:54 +00002945void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2946 const OMPTargetTeamsDistributeDirective *D) {
2947 VisitOMPLoopDirective(D);
2948}
2949
Kelvin Li80e8f562016-12-29 22:16:30 +00002950void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2951 const OMPTargetTeamsDistributeParallelForDirective *D) {
2952 VisitOMPLoopDirective(D);
2953}
2954
Kelvin Li1851df52017-01-03 05:23:48 +00002955void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2956 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2957 VisitOMPLoopDirective(D);
2958}
2959
Kelvin Lida681182017-01-10 18:08:18 +00002960void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2961 const OMPTargetTeamsDistributeSimdDirective *D) {
2962 VisitOMPLoopDirective(D);
2963}
2964
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002965void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2967}
2968
2969bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2970 if (RegionOfInterest.isValid()) {
2971 SourceRange Range = getRawCursorExtent(C);
2972 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2973 return false;
2974 }
2975 return true;
2976}
2977
2978bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2979 while (!WL.empty()) {
2980 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002981 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002982
2983 // Set the Parent field, then back to its old value once we're done.
2984 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2985
2986 switch (LI.getKind()) {
2987 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002988 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 if (!D)
2990 continue;
2991
2992 // For now, perform default visitation for Decls.
2993 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2994 cast<DeclVisit>(&LI)->isFirst())))
2995 return true;
2996
2997 continue;
2998 }
2999 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003000 for (const TemplateArgumentLoc &Arg :
3001 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3002 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 return true;
3004 }
3005 continue;
3006 }
3007 case VisitorJob::TypeLocVisitKind: {
3008 // Perform default visitation for TypeLocs.
3009 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3010 return true;
3011 continue;
3012 }
3013 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003014 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003015 if (LabelStmt *stmt = LS->getStmt()) {
3016 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3017 TU))) {
3018 return true;
3019 }
3020 }
3021 continue;
3022 }
3023
3024 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3025 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3026 if (VisitNestedNameSpecifierLoc(V->get()))
3027 return true;
3028 continue;
3029 }
3030
3031 case VisitorJob::DeclarationNameInfoVisitKind: {
3032 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3033 ->get()))
3034 return true;
3035 continue;
3036 }
3037 case VisitorJob::MemberRefVisitKind: {
3038 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3039 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3040 return true;
3041 continue;
3042 }
3043 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003044 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 if (!S)
3046 continue;
3047
3048 // Update the current cursor.
3049 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3050 if (!IsInRegionOfInterest(Cursor))
3051 continue;
3052 switch (Visitor(Cursor, Parent, ClientData)) {
3053 case CXChildVisit_Break: return true;
3054 case CXChildVisit_Continue: break;
3055 case CXChildVisit_Recurse:
3056 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003057 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 EnqueueWorkList(WL, S);
3059 break;
3060 }
3061 continue;
3062 }
3063 case VisitorJob::MemberExprPartsKind: {
3064 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003065 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003066
3067 // Visit the nested-name-specifier
3068 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3069 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3070 return true;
3071
3072 // Visit the declaration name.
3073 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3074 return true;
3075
3076 // Visit the explicitly-specified template arguments, if any.
3077 if (M->hasExplicitTemplateArgs()) {
3078 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3079 *ArgEnd = Arg + M->getNumTemplateArgs();
3080 Arg != ArgEnd; ++Arg) {
3081 if (VisitTemplateArgumentLoc(*Arg))
3082 return true;
3083 }
3084 }
3085 continue;
3086 }
3087 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003088 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 // Visit nested-name-specifier, if present.
3090 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3091 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3092 return true;
3093 // Visit declaration name.
3094 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3095 return true;
3096 continue;
3097 }
3098 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003099 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003100 // Visit the nested-name-specifier.
3101 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3102 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3103 return true;
3104 // Visit the declaration name.
3105 if (VisitDeclarationNameInfo(O->getNameInfo()))
3106 return true;
3107 // Visit the overloaded declaration reference.
3108 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3109 return true;
3110 continue;
3111 }
3112 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003113 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 NamedDecl *Pack = E->getPack();
3115 if (isa<TemplateTypeParmDecl>(Pack)) {
3116 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3117 E->getPackLoc(), TU)))
3118 return true;
3119
3120 continue;
3121 }
3122
3123 if (isa<TemplateTemplateParmDecl>(Pack)) {
3124 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3125 E->getPackLoc(), TU)))
3126 return true;
3127
3128 continue;
3129 }
3130
3131 // Non-type template parameter packs and function parameter packs are
3132 // treated like DeclRefExpr cursors.
3133 continue;
3134 }
3135
3136 case VisitorJob::LambdaExprPartsKind: {
3137 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003138 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3140 CEnd = E->explicit_capture_end();
3141 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003142 // FIXME: Lambda init-captures.
3143 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003145
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3147 C->getLocation(),
3148 TU)))
3149 return true;
3150 }
3151
Haojian Wuef87c262018-12-18 15:29:12 +00003152 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003154 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3155 if (E->hasExplicitParameters()) {
3156 // Visit parameters.
3157 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3158 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003159 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003160 }
3161 if (E->hasExplicitResultType()) {
3162 // Visit result type.
3163 if (Visit(Proto.getReturnLoc()))
3164 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 }
3166 }
3167 break;
3168 }
3169
3170 case VisitorJob::PostChildrenVisitKind:
3171 if (PostChildrenVisitor(Parent, ClientData))
3172 return true;
3173 break;
3174 }
3175 }
3176 return false;
3177}
3178
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003179bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003180 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003181 if (!WorkListFreeList.empty()) {
3182 WL = WorkListFreeList.back();
3183 WL->clear();
3184 WorkListFreeList.pop_back();
3185 }
3186 else {
3187 WL = new VisitorWorkList();
3188 WorkListCache.push_back(WL);
3189 }
3190 EnqueueWorkList(*WL, S);
3191 bool result = RunVisitorWorkList(*WL);
3192 WorkListFreeList.push_back(WL);
3193 return result;
3194}
3195
3196namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003197typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003198RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3199 const DeclarationNameInfo &NI, SourceRange QLoc,
3200 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3202 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3203 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3204
3205 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3206
3207 RefNamePieces Pieces;
3208
3209 if (WantQualifier && QLoc.isValid())
3210 Pieces.push_back(QLoc);
3211
3212 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3213 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003214
3215 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3216 Pieces.push_back(*TemplateArgsLoc);
3217
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 if (Kind == DeclarationName::CXXOperatorName) {
3219 Pieces.push_back(SourceLocation::getFromRawEncoding(
3220 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3221 Pieces.push_back(SourceLocation::getFromRawEncoding(
3222 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3223 }
3224
3225 if (WantSinglePiece) {
3226 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3227 Pieces.clear();
3228 Pieces.push_back(R);
3229 }
3230
3231 return Pieces;
3232}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003233}
Guy Benyei11169dd2012-12-18 14:30:41 +00003234
3235//===----------------------------------------------------------------------===//
3236// Misc. API hooks.
3237//===----------------------------------------------------------------------===//
3238
Chad Rosier05c71aa2013-03-27 18:28:23 +00003239static void fatal_error_handler(void *user_data, const std::string& reason,
3240 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003241 // Write the result out to stderr avoiding errs() because raw_ostreams can
3242 // call report_fatal_error.
3243 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3244 ::abort();
3245}
3246
Chandler Carruth66660742014-06-27 16:37:27 +00003247namespace {
3248struct RegisterFatalErrorHandler {
3249 RegisterFatalErrorHandler() {
3250 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3251 }
3252};
3253}
3254
3255static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3256
Guy Benyei11169dd2012-12-18 14:30:41 +00003257CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3258 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 // We use crash recovery to make some of our APIs more reliable, implicitly
3260 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003261 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3262 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003263
Chandler Carruth66660742014-06-27 16:37:27 +00003264 // Look through the managed static to trigger construction of the managed
3265 // static which registers our fatal error handler. This ensures it is only
3266 // registered once.
3267 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003268
Adrian Prantlbc068582015-07-08 01:00:30 +00003269 // Initialize targets for clang module support.
3270 llvm::InitializeAllTargets();
3271 llvm::InitializeAllTargetMCs();
3272 llvm::InitializeAllAsmPrinters();
3273 llvm::InitializeAllAsmParsers();
3274
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003275 CIndexer *CIdxr = new CIndexer();
3276
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 if (excludeDeclarationsFromPCH)
3278 CIdxr->setOnlyLocalDecls();
3279 if (displayDiagnostics)
3280 CIdxr->setDisplayDiagnostics();
3281
3282 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3283 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3284 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3285 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3286 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3287 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3288
3289 return CIdxr;
3290}
3291
3292void clang_disposeIndex(CXIndex CIdx) {
3293 if (CIdx)
3294 delete static_cast<CIndexer *>(CIdx);
3295}
3296
3297void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3298 if (CIdx)
3299 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3300}
3301
3302unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3303 if (CIdx)
3304 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3305 return 0;
3306}
3307
Alex Lorenz08615792017-12-04 21:56:36 +00003308void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3309 const char *Path) {
3310 if (CIdx)
3311 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3312}
3313
Guy Benyei11169dd2012-12-18 14:30:41 +00003314void clang_toggleCrashRecovery(unsigned isEnabled) {
3315 if (isEnabled)
3316 llvm::CrashRecoveryContext::Enable();
3317 else
3318 llvm::CrashRecoveryContext::Disable();
3319}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003320
Guy Benyei11169dd2012-12-18 14:30:41 +00003321CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3322 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003323 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003324 enum CXErrorCode Result =
3325 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003326 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003327 assert((TU && Result == CXError_Success) ||
3328 (!TU && Result != CXError_Success));
3329 return TU;
3330}
3331
3332enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3333 const char *ast_filename,
3334 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003335 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003336 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003337
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003338 if (!CIdx || !ast_filename || !out_TU)
3339 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003340
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003341 LOG_FUNC_SECTION {
3342 *Log << ast_filename;
3343 }
3344
Guy Benyei11169dd2012-12-18 14:30:41 +00003345 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3346 FileSystemOptions FileSystemOpts;
3347
Justin Bognerd512c1e2014-10-15 00:33:06 +00003348 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3349 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003350 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003351 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3352 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003353 FileSystemOpts, /*UseDebugInfo=*/false,
3354 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003355 /*CaptureDiagnostics=*/true,
3356 /*AllowPCHWithCompilerErrors=*/true,
3357 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003358 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003359 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003360}
3361
3362unsigned clang_defaultEditingTranslationUnitOptions() {
3363 return CXTranslationUnit_PrecompiledPreamble |
3364 CXTranslationUnit_CacheCompletionResults;
3365}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003366
Guy Benyei11169dd2012-12-18 14:30:41 +00003367CXTranslationUnit
3368clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3369 const char *source_filename,
3370 int num_command_line_args,
3371 const char * const *command_line_args,
3372 unsigned num_unsaved_files,
3373 struct CXUnsavedFile *unsaved_files) {
3374 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3375 return clang_parseTranslationUnit(CIdx, source_filename,
3376 command_line_args, num_command_line_args,
3377 unsaved_files, num_unsaved_files,
3378 Options);
3379}
3380
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003381static CXErrorCode
3382clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3383 const char *const *command_line_args,
3384 int num_command_line_args,
3385 ArrayRef<CXUnsavedFile> unsaved_files,
3386 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003387 // Set up the initial return values.
3388 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003389 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003390
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003391 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003392 if (!CIdx || !out_TU)
3393 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003394
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3396
3397 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3398 setThreadBackgroundPriority();
3399
3400 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003401 bool CreatePreambleOnFirstParse =
3402 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 // FIXME: Add a flag for modules.
3404 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003405 = (options & (CXTranslationUnit_Incomplete |
3406 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003407 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003408 = options & CXTranslationUnit_CacheCompletionResults;
3409 bool IncludeBriefCommentsInCodeCompletion
3410 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003411 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3412 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003413 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3414 if (options & CXTranslationUnit_SkipFunctionBodies) {
3415 SkipFunctionBodies =
3416 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3417 ? SkipFunctionBodiesScope::Preamble
3418 : SkipFunctionBodiesScope::PreambleAndMainFile;
3419 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003420
3421 // Configure the diagnostics.
3422 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003423 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003424
Manuel Klimek016c0242016-03-01 10:56:19 +00003425 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003426 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003427
Guy Benyei11169dd2012-12-18 14:30:41 +00003428 // Recover resources if we crash before exiting this function.
3429 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3430 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003431 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003432
Ahmed Charlesb8984322014-03-07 20:03:18 +00003433 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3434 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003435
3436 // Recover resources if we crash before exiting this function.
3437 llvm::CrashRecoveryContextCleanupRegistrar<
3438 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3439
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003440 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003441 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003442 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003443 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 }
3445
Ahmed Charlesb8984322014-03-07 20:03:18 +00003446 std::unique_ptr<std::vector<const char *>> Args(
3447 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003448
3449 // Recover resources if we crash before exiting this method.
3450 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3451 ArgsCleanup(Args.get());
3452
3453 // Since the Clang C library is primarily used by batch tools dealing with
3454 // (often very broken) source code, where spell-checking can have a
3455 // significant negative impact on performance (particularly when
3456 // precompiled headers are involved), we disable it by default.
3457 // Only do this if we haven't found a spell-checking-related argument.
3458 bool FoundSpellCheckingArgument = false;
3459 for (int I = 0; I != num_command_line_args; ++I) {
3460 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3461 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3462 FoundSpellCheckingArgument = true;
3463 break;
3464 }
3465 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003466 Args->insert(Args->end(), command_line_args,
3467 command_line_args + num_command_line_args);
3468
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003469 if (!FoundSpellCheckingArgument)
3470 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3471
Guy Benyei11169dd2012-12-18 14:30:41 +00003472 // The 'source_filename' argument is optional. If the caller does not
3473 // specify it then it is assumed that the source file is specified
3474 // in the actual argument list.
3475 // Put the source file after command_line_args otherwise if '-x' flag is
3476 // present it will be unused.
3477 if (source_filename)
3478 Args->push_back(source_filename);
3479
3480 // Do we need the detailed preprocessing record?
3481 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3482 Args->push_back("-Xclang");
3483 Args->push_back("-detailed-preprocessing-record");
3484 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003485
3486 // Suppress any editor placeholder diagnostics.
3487 Args->push_back("-fallow-editor-placeholders");
3488
Guy Benyei11169dd2012-12-18 14:30:41 +00003489 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003490 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003491 // Unless the user specified that they want the preamble on the first parse
3492 // set it up to be created on the first reparse. This makes the first parse
3493 // faster, trading for a slower (first) reparse.
3494 unsigned PrecompilePreambleAfterNParses =
3495 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003496
Alex Lorenz08615792017-12-04 21:56:36 +00003497 LibclangInvocationReporter InvocationReporter(
3498 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003499 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3500 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003501 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003502 Args->data(), Args->data() + Args->size(),
3503 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003504 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3505 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003506 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3507 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003508 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003509 /*UserFilesAreVolatile=*/true, ForSerialization,
3510 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3511 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003512
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003513 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003514 if (!Unit && !ErrUnit)
3515 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003516
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 if (NumErrors != Diags->getClient()->getNumErrors()) {
3518 // Make sure to check that 'Unit' is non-NULL.
3519 if (CXXIdx->getDisplayDiagnostics())
3520 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3521 }
3522
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003523 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3524 return CXError_ASTReadError;
3525
David Blaikieea4395e2017-01-06 19:49:01 +00003526 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003527 if (CXTranslationUnitImpl *TU = *out_TU) {
3528 TU->ParsingOptions = options;
3529 TU->Arguments.reserve(Args->size());
3530 for (const char *Arg : *Args)
3531 TU->Arguments.push_back(Arg);
3532 return CXError_Success;
3533 }
3534 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003535}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003536
3537CXTranslationUnit
3538clang_parseTranslationUnit(CXIndex CIdx,
3539 const char *source_filename,
3540 const char *const *command_line_args,
3541 int num_command_line_args,
3542 struct CXUnsavedFile *unsaved_files,
3543 unsigned num_unsaved_files,
3544 unsigned options) {
3545 CXTranslationUnit TU;
3546 enum CXErrorCode Result = clang_parseTranslationUnit2(
3547 CIdx, source_filename, command_line_args, num_command_line_args,
3548 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003549 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003550 assert((TU && Result == CXError_Success) ||
3551 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003552 return TU;
3553}
3554
3555enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003556 CXIndex CIdx, const char *source_filename,
3557 const char *const *command_line_args, int num_command_line_args,
3558 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3559 unsigned options, CXTranslationUnit *out_TU) {
3560 SmallVector<const char *, 4> Args;
3561 Args.push_back("clang");
3562 Args.append(command_line_args, command_line_args + num_command_line_args);
3563 return clang_parseTranslationUnit2FullArgv(
3564 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3565 num_unsaved_files, options, out_TU);
3566}
3567
3568enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3569 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) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003573 LOG_FUNC_SECTION {
3574 *Log << source_filename << ": ";
3575 for (int i = 0; i != num_command_line_args; ++i)
3576 *Log << command_line_args[i] << " ";
3577 }
3578
Alp Toker9d85b182014-07-07 01:23:14 +00003579 if (num_unsaved_files && !unsaved_files)
3580 return CXError_InvalidArguments;
3581
Alp Toker5c532982014-07-07 22:42:03 +00003582 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003583 auto ParseTranslationUnitImpl = [=, &result] {
3584 result = clang_parseTranslationUnit_Impl(
3585 CIdx, source_filename, command_line_args, num_command_line_args,
3586 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3587 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003588
Guy Benyei11169dd2012-12-18 14:30:41 +00003589 llvm::CrashRecoveryContext CRC;
3590
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003591 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003592 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3593 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3594 fprintf(stderr, " 'command_line_args' : [");
3595 for (int i = 0; i != num_command_line_args; ++i) {
3596 if (i)
3597 fprintf(stderr, ", ");
3598 fprintf(stderr, "'%s'", command_line_args[i]);
3599 }
3600 fprintf(stderr, "],\n");
3601 fprintf(stderr, " 'unsaved_files' : [");
3602 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3603 if (i)
3604 fprintf(stderr, ", ");
3605 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3606 unsaved_files[i].Length);
3607 }
3608 fprintf(stderr, "],\n");
3609 fprintf(stderr, " 'options' : %d,\n", options);
3610 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003611
3612 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003613 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003614 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003615 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003616 }
Alp Toker5c532982014-07-07 22:42:03 +00003617
3618 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003619}
3620
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003621CXString clang_Type_getObjCEncoding(CXType CT) {
3622 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3623 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3624 std::string encoding;
3625 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3626 encoding);
3627
3628 return cxstring::createDup(encoding);
3629}
3630
3631static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3632 if (C.kind == CXCursor_MacroDefinition) {
3633 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3634 return MDR->getName();
3635 } else if (C.kind == CXCursor_MacroExpansion) {
3636 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3637 return ME.getName();
3638 }
3639 return nullptr;
3640}
3641
3642unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3643 const IdentifierInfo *II = getMacroIdentifier(C);
3644 if (!II) {
3645 return false;
3646 }
3647 ASTUnit *ASTU = getCursorASTUnit(C);
3648 Preprocessor &PP = ASTU->getPreprocessor();
3649 if (const MacroInfo *MI = PP.getMacroInfo(II))
3650 return MI->isFunctionLike();
3651 return false;
3652}
3653
3654unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3655 const IdentifierInfo *II = getMacroIdentifier(C);
3656 if (!II) {
3657 return false;
3658 }
3659 ASTUnit *ASTU = getCursorASTUnit(C);
3660 Preprocessor &PP = ASTU->getPreprocessor();
3661 if (const MacroInfo *MI = PP.getMacroInfo(II))
3662 return MI->isBuiltinMacro();
3663 return false;
3664}
3665
3666unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3667 const Decl *D = getCursorDecl(C);
3668 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3669 if (!FD) {
3670 return false;
3671 }
3672 return FD->isInlined();
3673}
3674
3675static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3676 if (callExpr->getNumArgs() != 1) {
3677 return nullptr;
3678 }
3679
3680 StringLiteral *S = nullptr;
3681 auto *arg = callExpr->getArg(0);
3682 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3683 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3684 auto *subExpr = I->getSubExprAsWritten();
3685
3686 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3687 return nullptr;
3688 }
3689
3690 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3691 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3692 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3693 } else {
3694 return nullptr;
3695 }
3696 return S;
3697}
3698
David Blaikie59272572016-04-13 18:23:33 +00003699struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003700 CXEvalResultKind EvalType;
3701 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003702 unsigned long long unsignedVal;
3703 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003704 double floatVal;
3705 char *stringVal;
3706 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003707 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003708 ~ExprEvalResult() {
3709 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3710 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003711 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003712 }
3713 }
3714};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003715
3716void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003717 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003718}
3719
3720CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3721 if (!E) {
3722 return CXEval_UnExposed;
3723 }
3724 return ((ExprEvalResult *)E)->EvalType;
3725}
3726
3727int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003728 return clang_EvalResult_getAsLongLong(E);
3729}
3730
3731long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003732 if (!E) {
3733 return 0;
3734 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003735 ExprEvalResult *Result = (ExprEvalResult*)E;
3736 if (Result->IsUnsignedInt)
3737 return Result->EvalData.unsignedVal;
3738 return Result->EvalData.intVal;
3739}
3740
3741unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3742 return ((ExprEvalResult *)E)->IsUnsignedInt;
3743}
3744
3745unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3746 if (!E) {
3747 return 0;
3748 }
3749
3750 ExprEvalResult *Result = (ExprEvalResult*)E;
3751 if (Result->IsUnsignedInt)
3752 return Result->EvalData.unsignedVal;
3753 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003754}
3755
3756double clang_EvalResult_getAsDouble(CXEvalResult E) {
3757 if (!E) {
3758 return 0;
3759 }
3760 return ((ExprEvalResult *)E)->EvalData.floatVal;
3761}
3762
3763const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3764 if (!E) {
3765 return nullptr;
3766 }
3767 return ((ExprEvalResult *)E)->EvalData.stringVal;
3768}
3769
3770static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3771 Expr::EvalResult ER;
3772 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003773 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003774 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003775
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003776 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003777 if (!expr->EvaluateAsRValue(ER, ctx))
3778 return nullptr;
3779
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003780 QualType rettype;
3781 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003782 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003783 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003784 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003785
David Blaikiebbc00882016-04-13 18:36:19 +00003786 if (ER.Val.isInt()) {
3787 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003788
3789 auto& val = ER.Val.getInt();
3790 if (val.isUnsigned()) {
3791 result->IsUnsignedInt = true;
3792 result->EvalData.unsignedVal = val.getZExtValue();
3793 } else {
3794 result->EvalData.intVal = val.getExtValue();
3795 }
3796
David Blaikiebbc00882016-04-13 18:36:19 +00003797 return result.release();
3798 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003799
David Blaikiebbc00882016-04-13 18:36:19 +00003800 if (ER.Val.isFloat()) {
3801 llvm::SmallVector<char, 100> Buffer;
3802 ER.Val.getFloat().toString(Buffer);
3803 std::string floatStr(Buffer.data(), Buffer.size());
3804 result->EvalType = CXEval_Float;
3805 bool ignored;
3806 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003807 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003808 llvm::APFloat::rmNearestTiesToEven, &ignored);
3809 result->EvalData.floatVal = apFloat.convertToDouble();
3810 return result.release();
3811 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003812
David Blaikiebbc00882016-04-13 18:36:19 +00003813 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3814 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3815 auto *subExpr = I->getSubExprAsWritten();
3816 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3817 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003818 const StringLiteral *StrE = nullptr;
3819 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003820 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003821
3822 if (ObjCExpr) {
3823 StrE = ObjCExpr->getString();
3824 result->EvalType = CXEval_ObjCStrLiteral;
3825 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003826 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003827 result->EvalType = CXEval_StrLiteral;
3828 }
3829
3830 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003831 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003832 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3833 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003834 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003835 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003836 }
3837 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3838 expr->getStmtClass() == Stmt::StringLiteralClass) {
3839 const StringLiteral *StrE = nullptr;
3840 const ObjCStringLiteral *ObjCExpr;
3841 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003842
David Blaikiebbc00882016-04-13 18:36:19 +00003843 if (ObjCExpr) {
3844 StrE = ObjCExpr->getString();
3845 result->EvalType = CXEval_ObjCStrLiteral;
3846 } else {
3847 StrE = cast<StringLiteral>(expr);
3848 result->EvalType = CXEval_StrLiteral;
3849 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003850
David Blaikiebbc00882016-04-13 18:36:19 +00003851 std::string strRef(StrE->getString().str());
3852 result->EvalData.stringVal = new char[strRef.size() + 1];
3853 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3854 result->EvalData.stringVal[strRef.size()] = '\0';
3855 return result.release();
3856 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003857
David Blaikiebbc00882016-04-13 18:36:19 +00003858 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3859 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003860
David Blaikiebbc00882016-04-13 18:36:19 +00003861 rettype = CC->getType();
3862 if (rettype.getAsString() == "CFStringRef" &&
3863 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003864
David Blaikiebbc00882016-04-13 18:36:19 +00003865 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3866 StringLiteral *S = getCFSTR_value(callExpr);
3867 if (S) {
3868 std::string strLiteral(S->getString().str());
3869 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003870
David Blaikiebbc00882016-04-13 18:36:19 +00003871 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3872 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3873 strLiteral.size());
3874 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003875 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003876 }
3877 }
3878
David Blaikiebbc00882016-04-13 18:36:19 +00003879 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3880 callExpr = static_cast<CallExpr *>(expr);
3881 rettype = callExpr->getCallReturnType(ctx);
3882
3883 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3884 return nullptr;
3885
3886 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3887 if (callExpr->getNumArgs() == 1 &&
3888 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3889 return nullptr;
3890 } else if (rettype.getAsString() == "CFStringRef") {
3891
3892 StringLiteral *S = getCFSTR_value(callExpr);
3893 if (S) {
3894 std::string strLiteral(S->getString().str());
3895 result->EvalType = CXEval_CFStr;
3896 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3897 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3898 strLiteral.size());
3899 result->EvalData.stringVal[strLiteral.size()] = '\0';
3900 return result.release();
3901 }
3902 }
3903 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3904 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3905 ValueDecl *V = D->getDecl();
3906 if (V->getKind() == Decl::Function) {
3907 std::string strName = V->getNameAsString();
3908 result->EvalType = CXEval_Other;
3909 result->EvalData.stringVal = new char[strName.size() + 1];
3910 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3911 result->EvalData.stringVal[strName.size()] = '\0';
3912 return result.release();
3913 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003914 }
3915
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003916 return nullptr;
3917}
3918
Alex Lorenz65317e12019-01-08 22:32:51 +00003919static const Expr *evaluateDeclExpr(const Decl *D) {
3920 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003921 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003922 if (auto *Var = dyn_cast<VarDecl>(D))
3923 return Var->getInit();
3924 else if (auto *Field = dyn_cast<FieldDecl>(D))
3925 return Field->getInClassInitializer();
3926 return nullptr;
3927}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003928
Alex Lorenz65317e12019-01-08 22:32:51 +00003929static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3930 assert(CS && "invalid compound statement");
3931 for (auto *bodyIterator : CS->body()) {
3932 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3933 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003934 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003935 return nullptr;
3936}
3937
Alex Lorenz65317e12019-01-08 22:32:51 +00003938CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3939 if (const Expr *E =
3940 clang_getCursorKind(C) == CXCursor_CompoundStmt
3941 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3942 : evaluateDeclExpr(getCursorDecl(C)))
3943 return const_cast<CXEvalResult>(
3944 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3945 return nullptr;
3946}
3947
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003948unsigned clang_Cursor_hasAttrs(CXCursor C) {
3949 const Decl *D = getCursorDecl(C);
3950 if (!D) {
3951 return 0;
3952 }
3953
3954 if (D->hasAttrs()) {
3955 return 1;
3956 }
3957
3958 return 0;
3959}
Guy Benyei11169dd2012-12-18 14:30:41 +00003960unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3961 return CXSaveTranslationUnit_None;
3962}
3963
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003964static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3965 const char *FileName,
3966 unsigned options) {
3967 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3969 setThreadBackgroundPriority();
3970
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003971 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3972 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003973}
3974
3975int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3976 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003977 LOG_FUNC_SECTION {
3978 *Log << TU << ' ' << FileName;
3979 }
3980
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003981 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003982 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003983 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003984 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003985
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003986 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003987 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3988 if (!CXXUnit->hasSema())
3989 return CXSaveError_InvalidTU;
3990
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003991 CXSaveError result;
3992 auto SaveTranslationUnitImpl = [=, &result]() {
3993 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3994 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003995
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003996 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003997 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003998
3999 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4000 PrintLibclangResourceUsage(TU);
4001
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004002 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 }
4004
4005 // We have an AST that has invalid nodes due to compiler errors.
4006 // Use a crash recovery thread for protection.
4007
4008 llvm::CrashRecoveryContext CRC;
4009
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004010 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4012 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4013 fprintf(stderr, " 'options' : %d,\n", options);
4014 fprintf(stderr, "}\n");
4015
4016 return CXSaveError_Unknown;
4017
4018 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4019 PrintLibclangResourceUsage(TU);
4020 }
4021
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004022 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004023}
4024
4025void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4026 if (CTUnit) {
4027 // If the translation unit has been marked as unsafe to free, just discard
4028 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004029 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4030 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004031 return;
4032
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004033 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004034 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004035 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4036 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004037 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 delete CTUnit;
4039 }
4040}
4041
Erik Verbruggen346066b2017-05-30 14:25:54 +00004042unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4043 if (CTUnit) {
4044 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4045
4046 if (Unit && Unit->isUnsafeToFree())
4047 return false;
4048
4049 Unit->ResetForParse();
4050 return true;
4051 }
4052
4053 return false;
4054}
4055
Guy Benyei11169dd2012-12-18 14:30:41 +00004056unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4057 return CXReparse_None;
4058}
4059
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004060static CXErrorCode
4061clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4062 ArrayRef<CXUnsavedFile> unsaved_files,
4063 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004064 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004065 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004066 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004067 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004068 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004069
4070 // Reset the associated diagnostics.
4071 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004072 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004073
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004074 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4076 setThreadBackgroundPriority();
4077
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004078 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004079 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004080
4081 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4082 new std::vector<ASTUnit::RemappedFile>());
4083
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 // Recover resources if we crash before exiting this function.
4085 llvm::CrashRecoveryContextCleanupRegistrar<
4086 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004087
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004088 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004089 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004090 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004091 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004092 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004093
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004094 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4095 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004096 return CXError_Success;
4097 if (isASTReadError(CXXUnit))
4098 return CXError_ASTReadError;
4099 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004100}
4101
4102int clang_reparseTranslationUnit(CXTranslationUnit TU,
4103 unsigned num_unsaved_files,
4104 struct CXUnsavedFile *unsaved_files,
4105 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004106 LOG_FUNC_SECTION {
4107 *Log << TU;
4108 }
4109
Alp Toker9d85b182014-07-07 01:23:14 +00004110 if (num_unsaved_files && !unsaved_files)
4111 return CXError_InvalidArguments;
4112
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004113 CXErrorCode result;
4114 auto ReparseTranslationUnitImpl = [=, &result]() {
4115 result = clang_reparseTranslationUnit_Impl(
4116 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4117 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004118
Guy Benyei11169dd2012-12-18 14:30:41 +00004119 llvm::CrashRecoveryContext CRC;
4120
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004121 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004122 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004123 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004124 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4126 PrintLibclangResourceUsage(TU);
4127
Alp Toker5c532982014-07-07 22:42:03 +00004128 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004129}
4130
4131
4132CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004133 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004134 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004135 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004136 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004137
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004138 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004139 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004140}
4141
4142CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004143 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004144 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004145 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004146 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004147
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004148 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004149 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4150}
4151
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004152CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4153 if (isNotUsableTU(CTUnit)) {
4154 LOG_BAD_TU(CTUnit);
4155 return nullptr;
4156 }
4157
4158 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4159 impl->TranslationUnit = CTUnit;
4160 return impl;
4161}
4162
4163CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4164 if (!TargetInfo)
4165 return cxstring::createEmpty();
4166
4167 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4168 assert(!isNotUsableTU(CTUnit) &&
4169 "Unexpected unusable translation unit in TargetInfo");
4170
4171 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4172 std::string Triple =
4173 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4174 return cxstring::createDup(Triple);
4175}
4176
4177int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4178 if (!TargetInfo)
4179 return -1;
4180
4181 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4182 assert(!isNotUsableTU(CTUnit) &&
4183 "Unexpected unusable translation unit in TargetInfo");
4184
4185 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4186 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4187}
4188
4189void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4190 if (!TargetInfo)
4191 return;
4192
4193 delete TargetInfo;
4194}
4195
Guy Benyei11169dd2012-12-18 14:30:41 +00004196//===----------------------------------------------------------------------===//
4197// CXFile Operations.
4198//===----------------------------------------------------------------------===//
4199
Guy Benyei11169dd2012-12-18 14:30:41 +00004200CXString clang_getFileName(CXFile SFile) {
4201 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004202 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004203
4204 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004205 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004206}
4207
4208time_t clang_getFileTime(CXFile SFile) {
4209 if (!SFile)
4210 return 0;
4211
4212 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4213 return FEnt->getModificationTime();
4214}
4215
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004216CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004217 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004218 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004219 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004220 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004221
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004222 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004223
4224 FileManager &FMgr = CXXUnit->getFileManager();
4225 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4226}
4227
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004228const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4229 size_t *size) {
4230 if (isNotUsableTU(TU)) {
4231 LOG_BAD_TU(TU);
4232 return nullptr;
4233 }
4234
4235 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4236 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4237 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004238 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004239 if (Invalid) {
4240 if (size)
4241 *size = 0;
4242 return nullptr;
4243 }
4244 if (size)
4245 *size = buf->getBufferSize();
4246 return buf->getBufferStart();
4247}
4248
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004249unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4250 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004251 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004252 LOG_BAD_TU(TU);
4253 return 0;
4254 }
4255
4256 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 return 0;
4258
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004259 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 FileEntry *FEnt = static_cast<FileEntry *>(file);
4261 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4262 .isFileMultipleIncludeGuarded(FEnt);
4263}
4264
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004265int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4266 if (!file || !outID)
4267 return 1;
4268
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004269 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004270 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4271 outID->data[0] = ID.getDevice();
4272 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004273 outID->data[2] = FEnt->getModificationTime();
4274 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004275}
4276
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004277int clang_File_isEqual(CXFile file1, CXFile file2) {
4278 if (file1 == file2)
4279 return true;
4280
4281 if (!file1 || !file2)
4282 return false;
4283
4284 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4285 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4286 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4287}
4288
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004289CXString clang_File_tryGetRealPathName(CXFile SFile) {
4290 if (!SFile)
4291 return cxstring::createNull();
4292
4293 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4294 return cxstring::createRef(FEnt->tryGetRealPathName());
4295}
4296
Guy Benyei11169dd2012-12-18 14:30:41 +00004297//===----------------------------------------------------------------------===//
4298// CXCursor Operations.
4299//===----------------------------------------------------------------------===//
4300
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004301static const Decl *getDeclFromExpr(const Stmt *E) {
4302 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 return getDeclFromExpr(CE->getSubExpr());
4304
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004305 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004306 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004307 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004309 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004311 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 if (PRE->isExplicitProperty())
4313 return PRE->getExplicitProperty();
4314 // It could be messaging both getter and setter as in:
4315 // ++myobj.myprop;
4316 // in which case prefer to associate the setter since it is less obvious
4317 // from inspecting the source that the setter is going to get called.
4318 if (PRE->isMessagingSetter())
4319 return PRE->getImplicitPropertySetter();
4320 return PRE->getImplicitPropertyGetter();
4321 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004322 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004324 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004325 if (Expr *Src = OVE->getSourceExpr())
4326 return getDeclFromExpr(Src);
4327
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004328 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004330 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 if (!CE->isElidable())
4332 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004333 if (const CXXInheritedCtorInitExpr *CE =
4334 dyn_cast<CXXInheritedCtorInitExpr>(E))
4335 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004336 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 return OME->getMethodDecl();
4338
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004339 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004340 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004341 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4343 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004344 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4346 isa<ParmVarDecl>(SizeOfPack->getPack()))
4347 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004348
4349 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004350}
4351
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004352static SourceLocation getLocationFromExpr(const Expr *E) {
4353 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 return getLocationFromExpr(CE->getSubExpr());
4355
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004356 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004358 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004359 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004360 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004362 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004364 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004366 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004368
4369 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004370}
4371
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004372extern "C" {
4373
Guy Benyei11169dd2012-12-18 14:30:41 +00004374unsigned clang_visitChildren(CXCursor parent,
4375 CXCursorVisitor visitor,
4376 CXClientData client_data) {
4377 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4378 /*VisitPreprocessorLast=*/false);
4379 return CursorVis.VisitChildren(parent);
4380}
4381
4382#ifndef __has_feature
4383#define __has_feature(x) 0
4384#endif
4385#if __has_feature(blocks)
4386typedef enum CXChildVisitResult
4387 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4388
4389static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4390 CXClientData client_data) {
4391 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4392 return block(cursor, parent);
4393}
4394#else
4395// If we are compiled with a compiler that doesn't have native blocks support,
4396// define and call the block manually, so the
4397typedef struct _CXChildVisitResult
4398{
4399 void *isa;
4400 int flags;
4401 int reserved;
4402 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4403 CXCursor);
4404} *CXCursorVisitorBlock;
4405
4406static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4407 CXClientData client_data) {
4408 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4409 return block->invoke(block, cursor, parent);
4410}
4411#endif
4412
4413
4414unsigned clang_visitChildrenWithBlock(CXCursor parent,
4415 CXCursorVisitorBlock block) {
4416 return clang_visitChildren(parent, visitWithBlock, block);
4417}
4418
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004419static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004421 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004422
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004423 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004425 if (const ObjCPropertyImplDecl *PropImpl =
4426 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004428 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004429
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004430 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004432 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004433
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004434 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 }
4436
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004437 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004438 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004439
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004440 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4442 // and returns different names. NamedDecl returns the class name and
4443 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004444 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004445
4446 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004447 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004448
4449 SmallString<1024> S;
4450 llvm::raw_svector_ostream os(S);
4451 ND->printName(os);
4452
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004453 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004454}
4455
4456CXString clang_getCursorSpelling(CXCursor C) {
4457 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004458 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004459
4460 if (clang_isReference(C.kind)) {
4461 switch (C.kind) {
4462 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004463 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004464 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 }
4466 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004467 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004468 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 }
4470 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004471 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004473 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 }
4475 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004476 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004477 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 }
4479 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004480 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 assert(Type && "Missing type decl");
4482
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004483 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 getAsString());
4485 }
4486 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004487 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 assert(Template && "Missing template decl");
4489
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004490 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 }
4492
4493 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004494 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 assert(NS && "Missing namespace decl");
4496
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004497 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 }
4499
4500 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004501 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 assert(Field && "Missing member decl");
4503
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004504 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 }
4506
4507 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004508 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 assert(Label && "Missing label");
4510
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004511 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 }
4513
4514 case CXCursor_OverloadedDeclRef: {
4515 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004516 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4517 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004518 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004519 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004521 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004522 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 OverloadedTemplateStorage *Ovl
4524 = Storage.get<OverloadedTemplateStorage*>();
4525 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004526 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004527 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 }
4529
4530 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004531 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 assert(Var && "Missing variable decl");
4533
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004534 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 }
4536
4537 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004538 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 }
4540 }
4541
4542 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004543 const Expr *E = getCursorExpr(C);
4544
4545 if (C.kind == CXCursor_ObjCStringLiteral ||
4546 C.kind == CXCursor_StringLiteral) {
4547 const StringLiteral *SLit;
4548 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4549 SLit = OSL->getString();
4550 } else {
4551 SLit = cast<StringLiteral>(E);
4552 }
4553 SmallString<256> Buf;
4554 llvm::raw_svector_ostream OS(Buf);
4555 SLit->outputString(OS);
4556 return cxstring::createDup(OS.str());
4557 }
4558
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004559 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 if (D)
4561 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004562 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 }
4564
4565 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004566 const Stmt *S = getCursorStmt(C);
4567 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004568 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004569
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004570 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 }
4572
4573 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004574 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 ->getNameStart());
4576
4577 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004578 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 ->getNameStart());
4580
4581 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004582 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004583
4584 if (clang_isDeclaration(C.kind))
4585 return getDeclSpelling(getCursorDecl(C));
4586
4587 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004588 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004589 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 }
4591
4592 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004593 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004594 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 }
4596
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004597 if (C.kind == CXCursor_PackedAttr) {
4598 return cxstring::createRef("packed");
4599 }
4600
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004601 if (C.kind == CXCursor_VisibilityAttr) {
4602 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4603 switch (AA->getVisibility()) {
4604 case VisibilityAttr::VisibilityType::Default:
4605 return cxstring::createRef("default");
4606 case VisibilityAttr::VisibilityType::Hidden:
4607 return cxstring::createRef("hidden");
4608 case VisibilityAttr::VisibilityType::Protected:
4609 return cxstring::createRef("protected");
4610 }
4611 llvm_unreachable("unknown visibility type");
4612 }
4613
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004614 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004615}
4616
4617CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4618 unsigned pieceIndex,
4619 unsigned options) {
4620 if (clang_Cursor_isNull(C))
4621 return clang_getNullRange();
4622
4623 ASTContext &Ctx = getCursorContext(C);
4624
4625 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004626 const Stmt *S = getCursorStmt(C);
4627 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 if (pieceIndex > 0)
4629 return clang_getNullRange();
4630 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4631 }
4632
4633 return clang_getNullRange();
4634 }
4635
4636 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004637 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4639 if (pieceIndex >= ME->getNumSelectorLocs())
4640 return clang_getNullRange();
4641 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4642 }
4643 }
4644
4645 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4646 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004647 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4649 if (pieceIndex >= MD->getNumSelectorLocs())
4650 return clang_getNullRange();
4651 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4652 }
4653 }
4654
4655 if (C.kind == CXCursor_ObjCCategoryDecl ||
4656 C.kind == CXCursor_ObjCCategoryImplDecl) {
4657 if (pieceIndex > 0)
4658 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004659 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4661 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004662 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4664 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4665 }
4666
4667 if (C.kind == CXCursor_ModuleImportDecl) {
4668 if (pieceIndex > 0)
4669 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004670 if (const ImportDecl *ImportD =
4671 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4673 if (!Locs.empty())
4674 return cxloc::translateSourceRange(Ctx,
4675 SourceRange(Locs.front(), Locs.back()));
4676 }
4677 return clang_getNullRange();
4678 }
4679
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004680 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004681 C.kind == CXCursor_ConversionFunction ||
4682 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004683 if (pieceIndex > 0)
4684 return clang_getNullRange();
4685 if (const FunctionDecl *FD =
4686 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4687 DeclarationNameInfo FunctionName = FD->getNameInfo();
4688 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4689 }
4690 return clang_getNullRange();
4691 }
4692
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 // FIXME: A CXCursor_InclusionDirective should give the location of the
4694 // filename, but we don't keep track of this.
4695
4696 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4697 // but we don't keep track of this.
4698
4699 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4700 // but we don't keep track of this.
4701
4702 // Default handling, give the location of the cursor.
4703
4704 if (pieceIndex > 0)
4705 return clang_getNullRange();
4706
4707 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4708 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4709 return cxloc::translateSourceRange(Ctx, Loc);
4710}
4711
Eli Bendersky44a206f2014-07-31 18:04:56 +00004712CXString clang_Cursor_getMangling(CXCursor C) {
4713 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4714 return cxstring::createEmpty();
4715
Eli Bendersky44a206f2014-07-31 18:04:56 +00004716 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004717 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004718 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4719 return cxstring::createEmpty();
4720
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004721 ASTContext &Ctx = D->getASTContext();
4722 index::CodegenNameGenerator CGNameGen(Ctx);
4723 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004724}
4725
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004726CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4727 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4728 return nullptr;
4729
4730 const Decl *D = getCursorDecl(C);
4731 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4732 return nullptr;
4733
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004734 ASTContext &Ctx = D->getASTContext();
4735 index::CodegenNameGenerator CGNameGen(Ctx);
4736 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004737 return cxstring::createSet(Manglings);
4738}
4739
Dave Lee1a532c92017-09-22 16:58:57 +00004740CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4741 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4742 return nullptr;
4743
4744 const Decl *D = getCursorDecl(C);
4745 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4746 return nullptr;
4747
4748 ASTContext &Ctx = D->getASTContext();
4749 index::CodegenNameGenerator CGNameGen(Ctx);
4750 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4751 return cxstring::createSet(Manglings);
4752}
4753
Jonathan Coe45ef5032018-01-16 10:19:56 +00004754CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4755 if (clang_Cursor_isNull(C))
4756 return 0;
4757 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4758}
4759
4760void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4761 if (Policy)
4762 delete static_cast<PrintingPolicy *>(Policy);
4763}
4764
4765unsigned
4766clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4767 enum CXPrintingPolicyProperty Property) {
4768 if (!Policy)
4769 return 0;
4770
4771 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4772 switch (Property) {
4773 case CXPrintingPolicy_Indentation:
4774 return P->Indentation;
4775 case CXPrintingPolicy_SuppressSpecifiers:
4776 return P->SuppressSpecifiers;
4777 case CXPrintingPolicy_SuppressTagKeyword:
4778 return P->SuppressTagKeyword;
4779 case CXPrintingPolicy_IncludeTagDefinition:
4780 return P->IncludeTagDefinition;
4781 case CXPrintingPolicy_SuppressScope:
4782 return P->SuppressScope;
4783 case CXPrintingPolicy_SuppressUnwrittenScope:
4784 return P->SuppressUnwrittenScope;
4785 case CXPrintingPolicy_SuppressInitializers:
4786 return P->SuppressInitializers;
4787 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4788 return P->ConstantArraySizeAsWritten;
4789 case CXPrintingPolicy_AnonymousTagLocations:
4790 return P->AnonymousTagLocations;
4791 case CXPrintingPolicy_SuppressStrongLifetime:
4792 return P->SuppressStrongLifetime;
4793 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4794 return P->SuppressLifetimeQualifiers;
4795 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4796 return P->SuppressTemplateArgsInCXXConstructors;
4797 case CXPrintingPolicy_Bool:
4798 return P->Bool;
4799 case CXPrintingPolicy_Restrict:
4800 return P->Restrict;
4801 case CXPrintingPolicy_Alignof:
4802 return P->Alignof;
4803 case CXPrintingPolicy_UnderscoreAlignof:
4804 return P->UnderscoreAlignof;
4805 case CXPrintingPolicy_UseVoidForZeroParams:
4806 return P->UseVoidForZeroParams;
4807 case CXPrintingPolicy_TerseOutput:
4808 return P->TerseOutput;
4809 case CXPrintingPolicy_PolishForDeclaration:
4810 return P->PolishForDeclaration;
4811 case CXPrintingPolicy_Half:
4812 return P->Half;
4813 case CXPrintingPolicy_MSWChar:
4814 return P->MSWChar;
4815 case CXPrintingPolicy_IncludeNewlines:
4816 return P->IncludeNewlines;
4817 case CXPrintingPolicy_MSVCFormatting:
4818 return P->MSVCFormatting;
4819 case CXPrintingPolicy_ConstantsAsWritten:
4820 return P->ConstantsAsWritten;
4821 case CXPrintingPolicy_SuppressImplicitBase:
4822 return P->SuppressImplicitBase;
4823 case CXPrintingPolicy_FullyQualifiedName:
4824 return P->FullyQualifiedName;
4825 }
4826
4827 assert(false && "Invalid CXPrintingPolicyProperty");
4828 return 0;
4829}
4830
4831void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4832 enum CXPrintingPolicyProperty Property,
4833 unsigned Value) {
4834 if (!Policy)
4835 return;
4836
4837 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4838 switch (Property) {
4839 case CXPrintingPolicy_Indentation:
4840 P->Indentation = Value;
4841 return;
4842 case CXPrintingPolicy_SuppressSpecifiers:
4843 P->SuppressSpecifiers = Value;
4844 return;
4845 case CXPrintingPolicy_SuppressTagKeyword:
4846 P->SuppressTagKeyword = Value;
4847 return;
4848 case CXPrintingPolicy_IncludeTagDefinition:
4849 P->IncludeTagDefinition = Value;
4850 return;
4851 case CXPrintingPolicy_SuppressScope:
4852 P->SuppressScope = Value;
4853 return;
4854 case CXPrintingPolicy_SuppressUnwrittenScope:
4855 P->SuppressUnwrittenScope = Value;
4856 return;
4857 case CXPrintingPolicy_SuppressInitializers:
4858 P->SuppressInitializers = Value;
4859 return;
4860 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4861 P->ConstantArraySizeAsWritten = Value;
4862 return;
4863 case CXPrintingPolicy_AnonymousTagLocations:
4864 P->AnonymousTagLocations = Value;
4865 return;
4866 case CXPrintingPolicy_SuppressStrongLifetime:
4867 P->SuppressStrongLifetime = Value;
4868 return;
4869 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4870 P->SuppressLifetimeQualifiers = Value;
4871 return;
4872 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4873 P->SuppressTemplateArgsInCXXConstructors = Value;
4874 return;
4875 case CXPrintingPolicy_Bool:
4876 P->Bool = Value;
4877 return;
4878 case CXPrintingPolicy_Restrict:
4879 P->Restrict = Value;
4880 return;
4881 case CXPrintingPolicy_Alignof:
4882 P->Alignof = Value;
4883 return;
4884 case CXPrintingPolicy_UnderscoreAlignof:
4885 P->UnderscoreAlignof = Value;
4886 return;
4887 case CXPrintingPolicy_UseVoidForZeroParams:
4888 P->UseVoidForZeroParams = Value;
4889 return;
4890 case CXPrintingPolicy_TerseOutput:
4891 P->TerseOutput = Value;
4892 return;
4893 case CXPrintingPolicy_PolishForDeclaration:
4894 P->PolishForDeclaration = Value;
4895 return;
4896 case CXPrintingPolicy_Half:
4897 P->Half = Value;
4898 return;
4899 case CXPrintingPolicy_MSWChar:
4900 P->MSWChar = Value;
4901 return;
4902 case CXPrintingPolicy_IncludeNewlines:
4903 P->IncludeNewlines = Value;
4904 return;
4905 case CXPrintingPolicy_MSVCFormatting:
4906 P->MSVCFormatting = Value;
4907 return;
4908 case CXPrintingPolicy_ConstantsAsWritten:
4909 P->ConstantsAsWritten = Value;
4910 return;
4911 case CXPrintingPolicy_SuppressImplicitBase:
4912 P->SuppressImplicitBase = Value;
4913 return;
4914 case CXPrintingPolicy_FullyQualifiedName:
4915 P->FullyQualifiedName = Value;
4916 return;
4917 }
4918
4919 assert(false && "Invalid CXPrintingPolicyProperty");
4920}
4921
4922CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4923 if (clang_Cursor_isNull(C))
4924 return cxstring::createEmpty();
4925
4926 if (clang_isDeclaration(C.kind)) {
4927 const Decl *D = getCursorDecl(C);
4928 if (!D)
4929 return cxstring::createEmpty();
4930
4931 SmallString<128> Str;
4932 llvm::raw_svector_ostream OS(Str);
4933 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4934 D->print(OS, UserPolicy ? *UserPolicy
4935 : getCursorContext(C).getPrintingPolicy());
4936
4937 return cxstring::createDup(OS.str());
4938 }
4939
4940 return cxstring::createEmpty();
4941}
4942
Guy Benyei11169dd2012-12-18 14:30:41 +00004943CXString clang_getCursorDisplayName(CXCursor C) {
4944 if (!clang_isDeclaration(C.kind))
4945 return clang_getCursorSpelling(C);
4946
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004947 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004948 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004949 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004950
4951 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004952 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004953 D = FunTmpl->getTemplatedDecl();
4954
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004955 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004956 SmallString<64> Str;
4957 llvm::raw_svector_ostream OS(Str);
4958 OS << *Function;
4959 if (Function->getPrimaryTemplate())
4960 OS << "<>";
4961 OS << "(";
4962 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4963 if (I)
4964 OS << ", ";
4965 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4966 }
4967
4968 if (Function->isVariadic()) {
4969 if (Function->getNumParams())
4970 OS << ", ";
4971 OS << "...";
4972 }
4973 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004974 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 }
4976
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004977 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004978 SmallString<64> Str;
4979 llvm::raw_svector_ostream OS(Str);
4980 OS << *ClassTemplate;
4981 OS << "<";
4982 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4983 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4984 if (I)
4985 OS << ", ";
4986
4987 NamedDecl *Param = Params->getParam(I);
4988 if (Param->getIdentifier()) {
4989 OS << Param->getIdentifier()->getName();
4990 continue;
4991 }
4992
4993 // There is no parameter name, which makes this tricky. Try to come up
4994 // with something useful that isn't too long.
4995 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4996 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4997 else if (NonTypeTemplateParmDecl *NTTP
4998 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4999 OS << NTTP->getType().getAsString(Policy);
5000 else
5001 OS << "template<...> class";
5002 }
5003
5004 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005005 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 }
5007
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005008 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5010 // If the type was explicitly written, use that.
5011 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005012 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005013
Benjamin Kramer9170e912013-02-22 15:46:01 +00005014 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 llvm::raw_svector_ostream OS(Str);
5016 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005017 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5018 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005019 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 }
5021
5022 return clang_getCursorSpelling(C);
5023}
5024
5025CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5026 switch (Kind) {
5027 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005028 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005030 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005032 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005034 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005036 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005038 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005040 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005042 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005091 case CXCursor_FixedPointLiteral:
5092 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005094 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005107 case CXCursor_OMPArraySectionExpr:
5108 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005159 case CXCursor_ObjCAvailabilityCheckExpr:
5160 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005161 case CXCursor_ObjCSelfExpr:
5162 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005251 case CXCursor_SEHLeaveStmt:
5252 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005262 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005268 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005270 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005272 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005273 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005274 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005275 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005276 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005278 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005280 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005281 case CXCursor_PackedAttr:
5282 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005283 case CXCursor_PureAttr:
5284 return cxstring::createRef("attribute(pure)");
5285 case CXCursor_ConstAttr:
5286 return cxstring::createRef("attribute(const)");
5287 case CXCursor_NoDuplicateAttr:
5288 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005289 case CXCursor_CUDAConstantAttr:
5290 return cxstring::createRef("attribute(constant)");
5291 case CXCursor_CUDADeviceAttr:
5292 return cxstring::createRef("attribute(device)");
5293 case CXCursor_CUDAGlobalAttr:
5294 return cxstring::createRef("attribute(global)");
5295 case CXCursor_CUDAHostAttr:
5296 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005297 case CXCursor_CUDASharedAttr:
5298 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005299 case CXCursor_VisibilityAttr:
5300 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005301 case CXCursor_DLLExport:
5302 return cxstring::createRef("attribute(dllexport)");
5303 case CXCursor_DLLImport:
5304 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005305 case CXCursor_NSReturnsRetained:
5306 return cxstring::createRef("attribute(ns_returns_retained)");
5307 case CXCursor_NSReturnsNotRetained:
5308 return cxstring::createRef("attribute(ns_returns_not_retained)");
5309 case CXCursor_NSReturnsAutoreleased:
5310 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5311 case CXCursor_NSConsumesSelf:
5312 return cxstring::createRef("attribute(ns_consumes_self)");
5313 case CXCursor_NSConsumed:
5314 return cxstring::createRef("attribute(ns_consumed)");
5315 case CXCursor_ObjCException:
5316 return cxstring::createRef("attribute(objc_exception)");
5317 case CXCursor_ObjCNSObject:
5318 return cxstring::createRef("attribute(NSObject)");
5319 case CXCursor_ObjCIndependentClass:
5320 return cxstring::createRef("attribute(objc_independent_class)");
5321 case CXCursor_ObjCPreciseLifetime:
5322 return cxstring::createRef("attribute(objc_precise_lifetime)");
5323 case CXCursor_ObjCReturnsInnerPointer:
5324 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5325 case CXCursor_ObjCRequiresSuper:
5326 return cxstring::createRef("attribute(objc_requires_super)");
5327 case CXCursor_ObjCRootClass:
5328 return cxstring::createRef("attribute(objc_root_class)");
5329 case CXCursor_ObjCSubclassingRestricted:
5330 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5331 case CXCursor_ObjCExplicitProtocolImpl:
5332 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5333 case CXCursor_ObjCDesignatedInitializer:
5334 return cxstring::createRef("attribute(objc_designated_initializer)");
5335 case CXCursor_ObjCRuntimeVisible:
5336 return cxstring::createRef("attribute(objc_runtime_visible)");
5337 case CXCursor_ObjCBoxable:
5338 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005339 case CXCursor_FlagEnum:
5340 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005342 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005344 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005346 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005348 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005350 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005354 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005355 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005356 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005358 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005360 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005362 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005364 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005365 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005366 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005368 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005369 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005370 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005371 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005372 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005374 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005375 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005376 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005378 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005379 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005380 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005381 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005382 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005384 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005385 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005386 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005387 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005388 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005389 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005390 return cxstring::createRef("OMPParallelDirective");
5391 case CXCursor_OMPSimdDirective:
5392 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005393 case CXCursor_OMPForDirective:
5394 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005395 case CXCursor_OMPForSimdDirective:
5396 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005397 case CXCursor_OMPSectionsDirective:
5398 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005399 case CXCursor_OMPSectionDirective:
5400 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005401 case CXCursor_OMPSingleDirective:
5402 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005403 case CXCursor_OMPMasterDirective:
5404 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005405 case CXCursor_OMPCriticalDirective:
5406 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005407 case CXCursor_OMPParallelForDirective:
5408 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005409 case CXCursor_OMPParallelForSimdDirective:
5410 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005411 case CXCursor_OMPParallelSectionsDirective:
5412 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005413 case CXCursor_OMPTaskDirective:
5414 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005415 case CXCursor_OMPTaskyieldDirective:
5416 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005417 case CXCursor_OMPBarrierDirective:
5418 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005419 case CXCursor_OMPTaskwaitDirective:
5420 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005421 case CXCursor_OMPTaskgroupDirective:
5422 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005423 case CXCursor_OMPFlushDirective:
5424 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005425 case CXCursor_OMPOrderedDirective:
5426 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005427 case CXCursor_OMPAtomicDirective:
5428 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005429 case CXCursor_OMPTargetDirective:
5430 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005431 case CXCursor_OMPTargetDataDirective:
5432 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005433 case CXCursor_OMPTargetEnterDataDirective:
5434 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005435 case CXCursor_OMPTargetExitDataDirective:
5436 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005437 case CXCursor_OMPTargetParallelDirective:
5438 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005439 case CXCursor_OMPTargetParallelForDirective:
5440 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005441 case CXCursor_OMPTargetUpdateDirective:
5442 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005443 case CXCursor_OMPTeamsDirective:
5444 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005445 case CXCursor_OMPCancellationPointDirective:
5446 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005447 case CXCursor_OMPCancelDirective:
5448 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005449 case CXCursor_OMPTaskLoopDirective:
5450 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005451 case CXCursor_OMPTaskLoopSimdDirective:
5452 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005453 case CXCursor_OMPDistributeDirective:
5454 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005455 case CXCursor_OMPDistributeParallelForDirective:
5456 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005457 case CXCursor_OMPDistributeParallelForSimdDirective:
5458 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005459 case CXCursor_OMPDistributeSimdDirective:
5460 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005461 case CXCursor_OMPTargetParallelForSimdDirective:
5462 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005463 case CXCursor_OMPTargetSimdDirective:
5464 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005465 case CXCursor_OMPTeamsDistributeDirective:
5466 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005467 case CXCursor_OMPTeamsDistributeSimdDirective:
5468 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005469 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5470 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005471 case CXCursor_OMPTeamsDistributeParallelForDirective:
5472 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005473 case CXCursor_OMPTargetTeamsDirective:
5474 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005475 case CXCursor_OMPTargetTeamsDistributeDirective:
5476 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005477 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5478 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005479 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5480 return cxstring::createRef(
5481 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005482 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5483 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005484 case CXCursor_OverloadCandidate:
5485 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005486 case CXCursor_TypeAliasTemplateDecl:
5487 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005488 case CXCursor_StaticAssert:
5489 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005490 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005491 return cxstring::createRef("FriendDecl");
5492 case CXCursor_ConvergentAttr:
5493 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005494 case CXCursor_WarnUnusedAttr:
5495 return cxstring::createRef("attribute(warn_unused)");
5496 case CXCursor_WarnUnusedResultAttr:
5497 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005498 case CXCursor_AlignedAttr:
5499 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005500 }
5501
5502 llvm_unreachable("Unhandled CXCursorKind");
5503}
5504
5505struct GetCursorData {
5506 SourceLocation TokenBeginLoc;
5507 bool PointsAtMacroArgExpansion;
5508 bool VisitedObjCPropertyImplDecl;
5509 SourceLocation VisitedDeclaratorDeclStartLoc;
5510 CXCursor &BestCursor;
5511
5512 GetCursorData(SourceManager &SM,
5513 SourceLocation tokenBegin, CXCursor &outputCursor)
5514 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5515 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5516 VisitedObjCPropertyImplDecl = false;
5517 }
5518};
5519
5520static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5521 CXCursor parent,
5522 CXClientData client_data) {
5523 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5524 CXCursor *BestCursor = &Data->BestCursor;
5525
5526 // If we point inside a macro argument we should provide info of what the
5527 // token is so use the actual cursor, don't replace it with a macro expansion
5528 // cursor.
5529 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5530 return CXChildVisit_Recurse;
5531
5532 if (clang_isDeclaration(cursor.kind)) {
5533 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005534 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005535 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5536 if (MD->isImplicit())
5537 return CXChildVisit_Break;
5538
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005539 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005540 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5541 // Check that when we have multiple @class references in the same line,
5542 // that later ones do not override the previous ones.
5543 // If we have:
5544 // @class Foo, Bar;
5545 // source ranges for both start at '@', so 'Bar' will end up overriding
5546 // 'Foo' even though the cursor location was at 'Foo'.
5547 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5548 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005549 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005550 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5551 if (PrevID != ID &&
5552 !PrevID->isThisDeclarationADefinition() &&
5553 !ID->isThisDeclarationADefinition())
5554 return CXChildVisit_Break;
5555 }
5556
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005557 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005558 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5559 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5560 // Check that when we have multiple declarators in the same line,
5561 // that later ones do not override the previous ones.
5562 // If we have:
5563 // int Foo, Bar;
5564 // source ranges for both start at 'int', so 'Bar' will end up overriding
5565 // 'Foo' even though the cursor location was at 'Foo'.
5566 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5567 return CXChildVisit_Break;
5568 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5569
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005570 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005571 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5572 (void)PropImp;
5573 // Check that when we have multiple @synthesize in the same line,
5574 // that later ones do not override the previous ones.
5575 // If we have:
5576 // @synthesize Foo, Bar;
5577 // source ranges for both start at '@', so 'Bar' will end up overriding
5578 // 'Foo' even though the cursor location was at 'Foo'.
5579 if (Data->VisitedObjCPropertyImplDecl)
5580 return CXChildVisit_Break;
5581 Data->VisitedObjCPropertyImplDecl = true;
5582 }
5583 }
5584
5585 if (clang_isExpression(cursor.kind) &&
5586 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005587 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005588 // Avoid having the cursor of an expression replace the declaration cursor
5589 // when the expression source range overlaps the declaration range.
5590 // This can happen for C++ constructor expressions whose range generally
5591 // include the variable declaration, e.g.:
5592 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5593 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5594 D->getLocation() == Data->TokenBeginLoc)
5595 return CXChildVisit_Break;
5596 }
5597 }
5598
5599 // If our current best cursor is the construction of a temporary object,
5600 // don't replace that cursor with a type reference, because we want
5601 // clang_getCursor() to point at the constructor.
5602 if (clang_isExpression(BestCursor->kind) &&
5603 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5604 cursor.kind == CXCursor_TypeRef) {
5605 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5606 // as having the actual point on the type reference.
5607 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5608 return CXChildVisit_Recurse;
5609 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005610
5611 // If we already have an Objective-C superclass reference, don't
5612 // update it further.
5613 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5614 return CXChildVisit_Break;
5615
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 *BestCursor = cursor;
5617 return CXChildVisit_Recurse;
5618}
5619
5620CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005621 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005622 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005623 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005624 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005625
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005626 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005627 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5628
5629 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5630 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5631
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005632 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005633 CXFile SearchFile;
5634 unsigned SearchLine, SearchColumn;
5635 CXFile ResultFile;
5636 unsigned ResultLine, ResultColumn;
5637 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5638 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5639 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005640
5641 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5642 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005643 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005644 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005645 SearchFileName = clang_getFileName(SearchFile);
5646 ResultFileName = clang_getFileName(ResultFile);
5647 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5648 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005649 *Log << llvm::format("(%s:%d:%d) = %s",
5650 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5651 clang_getCString(KindSpelling))
5652 << llvm::format("(%s:%d:%d):%s%s",
5653 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5654 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 clang_disposeString(SearchFileName);
5656 clang_disposeString(ResultFileName);
5657 clang_disposeString(KindSpelling);
5658 clang_disposeString(USR);
5659
5660 CXCursor Definition = clang_getCursorDefinition(Result);
5661 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5662 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5663 CXString DefinitionKindSpelling
5664 = clang_getCursorKindSpelling(Definition.kind);
5665 CXFile DefinitionFile;
5666 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005667 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005668 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005669 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005670 *Log << llvm::format(" -> %s(%s:%d:%d)",
5671 clang_getCString(DefinitionKindSpelling),
5672 clang_getCString(DefinitionFileName),
5673 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005674 clang_disposeString(DefinitionFileName);
5675 clang_disposeString(DefinitionKindSpelling);
5676 }
5677 }
5678
5679 return Result;
5680}
5681
5682CXCursor clang_getNullCursor(void) {
5683 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5684}
5685
5686unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005687 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5688 // can't set consistently. For example, when visiting a DeclStmt we will set
5689 // it but we don't set it on the result of clang_getCursorDefinition for
5690 // a reference of the same declaration.
5691 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5692 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5693 // to provide that kind of info.
5694 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005695 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005696 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005697 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005698
Guy Benyei11169dd2012-12-18 14:30:41 +00005699 return X == Y;
5700}
5701
5702unsigned clang_hashCursor(CXCursor C) {
5703 unsigned Index = 0;
5704 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5705 Index = 1;
5706
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005707 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005708 std::make_pair(C.kind, C.data[Index]));
5709}
5710
5711unsigned clang_isInvalid(enum CXCursorKind K) {
5712 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5713}
5714
5715unsigned clang_isDeclaration(enum CXCursorKind K) {
5716 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005717 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5718}
5719
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005720unsigned clang_isInvalidDeclaration(CXCursor C) {
5721 if (clang_isDeclaration(C.kind)) {
5722 if (const Decl *D = getCursorDecl(C))
5723 return D->isInvalidDecl();
5724 }
5725
5726 return 0;
5727}
5728
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005729unsigned clang_isReference(enum CXCursorKind K) {
5730 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5731}
Guy Benyei11169dd2012-12-18 14:30:41 +00005732
5733unsigned clang_isExpression(enum CXCursorKind K) {
5734 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5735}
5736
5737unsigned clang_isStatement(enum CXCursorKind K) {
5738 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5739}
5740
5741unsigned clang_isAttribute(enum CXCursorKind K) {
5742 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5743}
5744
5745unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5746 return K == CXCursor_TranslationUnit;
5747}
5748
5749unsigned clang_isPreprocessing(enum CXCursorKind K) {
5750 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5751}
5752
5753unsigned clang_isUnexposed(enum CXCursorKind K) {
5754 switch (K) {
5755 case CXCursor_UnexposedDecl:
5756 case CXCursor_UnexposedExpr:
5757 case CXCursor_UnexposedStmt:
5758 case CXCursor_UnexposedAttr:
5759 return true;
5760 default:
5761 return false;
5762 }
5763}
5764
5765CXCursorKind clang_getCursorKind(CXCursor C) {
5766 return C.kind;
5767}
5768
5769CXSourceLocation clang_getCursorLocation(CXCursor C) {
5770 if (clang_isReference(C.kind)) {
5771 switch (C.kind) {
5772 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005773 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005774 = getCursorObjCSuperClassRef(C);
5775 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5776 }
5777
5778 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005779 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005780 = getCursorObjCProtocolRef(C);
5781 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5782 }
5783
5784 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005785 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005786 = getCursorObjCClassRef(C);
5787 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5788 }
5789
5790 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005791 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5793 }
5794
5795 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005796 std::pair<const TemplateDecl *, SourceLocation> P =
5797 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005798 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5799 }
5800
5801 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005802 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005803 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5804 }
5805
5806 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005807 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005808 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5809 }
5810
5811 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005812 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005813 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5814 }
5815
5816 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005817 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005818 if (!BaseSpec)
5819 return clang_getNullLocation();
5820
5821 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5822 return cxloc::translateSourceLocation(getCursorContext(C),
5823 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005824
Guy Benyei11169dd2012-12-18 14:30:41 +00005825 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005826 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005827 }
5828
5829 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005830 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005831 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5832 }
5833
5834 case CXCursor_OverloadedDeclRef:
5835 return cxloc::translateSourceLocation(getCursorContext(C),
5836 getCursorOverloadedDeclRef(C).second);
5837
5838 default:
5839 // FIXME: Need a way to enumerate all non-reference cases.
5840 llvm_unreachable("Missed a reference kind");
5841 }
5842 }
5843
5844 if (clang_isExpression(C.kind))
5845 return cxloc::translateSourceLocation(getCursorContext(C),
5846 getLocationFromExpr(getCursorExpr(C)));
5847
5848 if (clang_isStatement(C.kind))
5849 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005850 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005851
5852 if (C.kind == CXCursor_PreprocessingDirective) {
5853 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5854 return cxloc::translateSourceLocation(getCursorContext(C), L);
5855 }
5856
5857 if (C.kind == CXCursor_MacroExpansion) {
5858 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005859 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005860 return cxloc::translateSourceLocation(getCursorContext(C), L);
5861 }
5862
5863 if (C.kind == CXCursor_MacroDefinition) {
5864 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5865 return cxloc::translateSourceLocation(getCursorContext(C), L);
5866 }
5867
5868 if (C.kind == CXCursor_InclusionDirective) {
5869 SourceLocation L
5870 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5871 return cxloc::translateSourceLocation(getCursorContext(C), L);
5872 }
5873
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005874 if (clang_isAttribute(C.kind)) {
5875 SourceLocation L
5876 = cxcursor::getCursorAttr(C)->getLocation();
5877 return cxloc::translateSourceLocation(getCursorContext(C), L);
5878 }
5879
Guy Benyei11169dd2012-12-18 14:30:41 +00005880 if (!clang_isDeclaration(C.kind))
5881 return clang_getNullLocation();
5882
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005883 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005884 if (!D)
5885 return clang_getNullLocation();
5886
5887 SourceLocation Loc = D->getLocation();
5888 // FIXME: Multiple variables declared in a single declaration
5889 // currently lack the information needed to correctly determine their
5890 // ranges when accounting for the type-specifier. We use context
5891 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5892 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005893 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005894 if (!cxcursor::isFirstInDeclGroup(C))
5895 Loc = VD->getLocation();
5896 }
5897
5898 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005899 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005900 Loc = MD->getSelectorStartLoc();
5901
5902 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5903}
5904
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005905} // end extern "C"
5906
Guy Benyei11169dd2012-12-18 14:30:41 +00005907CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5908 assert(TU);
5909
5910 // Guard against an invalid SourceLocation, or we may assert in one
5911 // of the following calls.
5912 if (SLoc.isInvalid())
5913 return clang_getNullCursor();
5914
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005915 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005916
5917 // Translate the given source location to make it point at the beginning of
5918 // the token under the cursor.
5919 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5920 CXXUnit->getASTContext().getLangOpts());
5921
5922 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5923 if (SLoc.isValid()) {
5924 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5925 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5926 /*VisitPreprocessorLast=*/true,
5927 /*VisitIncludedEntities=*/false,
5928 SourceLocation(SLoc));
5929 CursorVis.visitFileRegion();
5930 }
5931
5932 return Result;
5933}
5934
5935static SourceRange getRawCursorExtent(CXCursor C) {
5936 if (clang_isReference(C.kind)) {
5937 switch (C.kind) {
5938 case CXCursor_ObjCSuperClassRef:
5939 return getCursorObjCSuperClassRef(C).second;
5940
5941 case CXCursor_ObjCProtocolRef:
5942 return getCursorObjCProtocolRef(C).second;
5943
5944 case CXCursor_ObjCClassRef:
5945 return getCursorObjCClassRef(C).second;
5946
5947 case CXCursor_TypeRef:
5948 return getCursorTypeRef(C).second;
5949
5950 case CXCursor_TemplateRef:
5951 return getCursorTemplateRef(C).second;
5952
5953 case CXCursor_NamespaceRef:
5954 return getCursorNamespaceRef(C).second;
5955
5956 case CXCursor_MemberRef:
5957 return getCursorMemberRef(C).second;
5958
5959 case CXCursor_CXXBaseSpecifier:
5960 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5961
5962 case CXCursor_LabelRef:
5963 return getCursorLabelRef(C).second;
5964
5965 case CXCursor_OverloadedDeclRef:
5966 return getCursorOverloadedDeclRef(C).second;
5967
5968 case CXCursor_VariableRef:
5969 return getCursorVariableRef(C).second;
5970
5971 default:
5972 // FIXME: Need a way to enumerate all non-reference cases.
5973 llvm_unreachable("Missed a reference kind");
5974 }
5975 }
5976
5977 if (clang_isExpression(C.kind))
5978 return getCursorExpr(C)->getSourceRange();
5979
5980 if (clang_isStatement(C.kind))
5981 return getCursorStmt(C)->getSourceRange();
5982
5983 if (clang_isAttribute(C.kind))
5984 return getCursorAttr(C)->getRange();
5985
5986 if (C.kind == CXCursor_PreprocessingDirective)
5987 return cxcursor::getCursorPreprocessingDirective(C);
5988
5989 if (C.kind == CXCursor_MacroExpansion) {
5990 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005991 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005992 return TU->mapRangeFromPreamble(Range);
5993 }
5994
5995 if (C.kind == CXCursor_MacroDefinition) {
5996 ASTUnit *TU = getCursorASTUnit(C);
5997 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5998 return TU->mapRangeFromPreamble(Range);
5999 }
6000
6001 if (C.kind == CXCursor_InclusionDirective) {
6002 ASTUnit *TU = getCursorASTUnit(C);
6003 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6004 return TU->mapRangeFromPreamble(Range);
6005 }
6006
6007 if (C.kind == CXCursor_TranslationUnit) {
6008 ASTUnit *TU = getCursorASTUnit(C);
6009 FileID MainID = TU->getSourceManager().getMainFileID();
6010 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6011 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6012 return SourceRange(Start, End);
6013 }
6014
6015 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006016 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006017 if (!D)
6018 return SourceRange();
6019
6020 SourceRange R = D->getSourceRange();
6021 // FIXME: Multiple variables declared in a single declaration
6022 // currently lack the information needed to correctly determine their
6023 // ranges when accounting for the type-specifier. We use context
6024 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6025 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006026 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006027 if (!cxcursor::isFirstInDeclGroup(C))
6028 R.setBegin(VD->getLocation());
6029 }
6030 return R;
6031 }
6032 return SourceRange();
6033}
6034
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006035/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006036/// the decl-specifier-seq for declarations.
6037static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6038 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006039 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006040 if (!D)
6041 return SourceRange();
6042
6043 SourceRange R = D->getSourceRange();
6044
6045 // Adjust the start of the location for declarations preceded by
6046 // declaration specifiers.
6047 SourceLocation StartLoc;
6048 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6049 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006050 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006051 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006052 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006053 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006054 }
6055
6056 if (StartLoc.isValid() && R.getBegin().isValid() &&
6057 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6058 R.setBegin(StartLoc);
6059
6060 // FIXME: Multiple variables declared in a single declaration
6061 // currently lack the information needed to correctly determine their
6062 // ranges when accounting for the type-specifier. We use context
6063 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6064 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006065 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006066 if (!cxcursor::isFirstInDeclGroup(C))
6067 R.setBegin(VD->getLocation());
6068 }
6069
6070 return R;
6071 }
6072
6073 return getRawCursorExtent(C);
6074}
6075
Guy Benyei11169dd2012-12-18 14:30:41 +00006076CXSourceRange clang_getCursorExtent(CXCursor C) {
6077 SourceRange R = getRawCursorExtent(C);
6078 if (R.isInvalid())
6079 return clang_getNullRange();
6080
6081 return cxloc::translateSourceRange(getCursorContext(C), R);
6082}
6083
6084CXCursor clang_getCursorReferenced(CXCursor C) {
6085 if (clang_isInvalid(C.kind))
6086 return clang_getNullCursor();
6087
6088 CXTranslationUnit tu = getCursorTU(C);
6089 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006090 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 if (!D)
6092 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006093 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006094 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006095 if (const ObjCPropertyImplDecl *PropImpl =
6096 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006097 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6098 return MakeCXCursor(Property, tu);
6099
6100 return C;
6101 }
6102
6103 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006104 const Expr *E = getCursorExpr(C);
6105 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 if (D) {
6107 CXCursor declCursor = MakeCXCursor(D, tu);
6108 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6109 declCursor);
6110 return declCursor;
6111 }
6112
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006113 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 return MakeCursorOverloadedDeclRef(Ovl, tu);
6115
6116 return clang_getNullCursor();
6117 }
6118
6119 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006120 const Stmt *S = getCursorStmt(C);
6121 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 if (LabelDecl *label = Goto->getLabel())
6123 if (LabelStmt *labelS = label->getStmt())
6124 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6125
6126 return clang_getNullCursor();
6127 }
Richard Smith66a81862015-05-04 02:25:31 +00006128
Guy Benyei11169dd2012-12-18 14:30:41 +00006129 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006130 if (const MacroDefinitionRecord *Def =
6131 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006132 return MakeMacroDefinitionCursor(Def, tu);
6133 }
6134
6135 if (!clang_isReference(C.kind))
6136 return clang_getNullCursor();
6137
6138 switch (C.kind) {
6139 case CXCursor_ObjCSuperClassRef:
6140 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6141
6142 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006143 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6144 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 return MakeCXCursor(Def, tu);
6146
6147 return MakeCXCursor(Prot, tu);
6148 }
6149
6150 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006151 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6152 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 return MakeCXCursor(Def, tu);
6154
6155 return MakeCXCursor(Class, tu);
6156 }
6157
6158 case CXCursor_TypeRef:
6159 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6160
6161 case CXCursor_TemplateRef:
6162 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6163
6164 case CXCursor_NamespaceRef:
6165 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6166
6167 case CXCursor_MemberRef:
6168 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6169
6170 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006171 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006172 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6173 tu ));
6174 }
6175
6176 case CXCursor_LabelRef:
6177 // FIXME: We end up faking the "parent" declaration here because we
6178 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006179 return MakeCXCursor(getCursorLabelRef(C).first,
6180 cxtu::getASTUnit(tu)->getASTContext()
6181 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006182 tu);
6183
6184 case CXCursor_OverloadedDeclRef:
6185 return C;
6186
6187 case CXCursor_VariableRef:
6188 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6189
6190 default:
6191 // We would prefer to enumerate all non-reference cursor kinds here.
6192 llvm_unreachable("Unhandled reference cursor kind");
6193 }
6194}
6195
6196CXCursor clang_getCursorDefinition(CXCursor C) {
6197 if (clang_isInvalid(C.kind))
6198 return clang_getNullCursor();
6199
6200 CXTranslationUnit TU = getCursorTU(C);
6201
6202 bool WasReference = false;
6203 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6204 C = clang_getCursorReferenced(C);
6205 WasReference = true;
6206 }
6207
6208 if (C.kind == CXCursor_MacroExpansion)
6209 return clang_getCursorReferenced(C);
6210
6211 if (!clang_isDeclaration(C.kind))
6212 return clang_getNullCursor();
6213
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006214 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006215 if (!D)
6216 return clang_getNullCursor();
6217
6218 switch (D->getKind()) {
6219 // Declaration kinds that don't really separate the notions of
6220 // declaration and definition.
6221 case Decl::Namespace:
6222 case Decl::Typedef:
6223 case Decl::TypeAlias:
6224 case Decl::TypeAliasTemplate:
6225 case Decl::TemplateTypeParm:
6226 case Decl::EnumConstant:
6227 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006228 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006229 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006230 case Decl::IndirectField:
6231 case Decl::ObjCIvar:
6232 case Decl::ObjCAtDefsField:
6233 case Decl::ImplicitParam:
6234 case Decl::ParmVar:
6235 case Decl::NonTypeTemplateParm:
6236 case Decl::TemplateTemplateParm:
6237 case Decl::ObjCCategoryImpl:
6238 case Decl::ObjCImplementation:
6239 case Decl::AccessSpec:
6240 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006241 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006242 case Decl::ObjCPropertyImpl:
6243 case Decl::FileScopeAsm:
6244 case Decl::StaticAssert:
6245 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006246 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006247 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006248 case Decl::Label: // FIXME: Is this right??
6249 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006250 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006251 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006252 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006253 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006254 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006255 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006256 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006257 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006258 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006259 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006260 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006261 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006262 return C;
6263
6264 // Declaration kinds that don't make any sense here, but are
6265 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006266 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006267 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006268 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006269 break;
6270
6271 // Declaration kinds for which the definition is not resolvable.
6272 case Decl::UnresolvedUsingTypename:
6273 case Decl::UnresolvedUsingValue:
6274 break;
6275
6276 case Decl::UsingDirective:
6277 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6278 TU);
6279
6280 case Decl::NamespaceAlias:
6281 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6282
6283 case Decl::Enum:
6284 case Decl::Record:
6285 case Decl::CXXRecord:
6286 case Decl::ClassTemplateSpecialization:
6287 case Decl::ClassTemplatePartialSpecialization:
6288 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6289 return MakeCXCursor(Def, TU);
6290 return clang_getNullCursor();
6291
6292 case Decl::Function:
6293 case Decl::CXXMethod:
6294 case Decl::CXXConstructor:
6295 case Decl::CXXDestructor:
6296 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006297 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006299 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006300 return clang_getNullCursor();
6301 }
6302
Larisse Voufo39a1e502013-08-06 01:03:05 +00006303 case Decl::Var:
6304 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006305 case Decl::VarTemplatePartialSpecialization:
6306 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006308 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006309 return MakeCXCursor(Def, TU);
6310 return clang_getNullCursor();
6311 }
6312
6313 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006314 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006315 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6316 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6317 return clang_getNullCursor();
6318 }
6319
6320 case Decl::ClassTemplate: {
6321 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6322 ->getDefinition())
6323 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6324 TU);
6325 return clang_getNullCursor();
6326 }
6327
Larisse Voufo39a1e502013-08-06 01:03:05 +00006328 case Decl::VarTemplate: {
6329 if (VarDecl *Def =
6330 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6331 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6332 return clang_getNullCursor();
6333 }
6334
Guy Benyei11169dd2012-12-18 14:30:41 +00006335 case Decl::Using:
6336 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6337 D->getLocation(), TU);
6338
6339 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006340 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006341 return clang_getCursorDefinition(
6342 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6343 TU));
6344
6345 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006346 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 if (Method->isThisDeclarationADefinition())
6348 return C;
6349
6350 // Dig out the method definition in the associated
6351 // @implementation, if we have it.
6352 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006353 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006354 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6355 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6356 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6357 Method->isInstanceMethod()))
6358 if (Def->isThisDeclarationADefinition())
6359 return MakeCXCursor(Def, TU);
6360
6361 return clang_getNullCursor();
6362 }
6363
6364 case Decl::ObjCCategory:
6365 if (ObjCCategoryImplDecl *Impl
6366 = cast<ObjCCategoryDecl>(D)->getImplementation())
6367 return MakeCXCursor(Impl, TU);
6368 return clang_getNullCursor();
6369
6370 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006371 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006372 return MakeCXCursor(Def, TU);
6373 return clang_getNullCursor();
6374
6375 case Decl::ObjCInterface: {
6376 // There are two notions of a "definition" for an Objective-C
6377 // class: the interface and its implementation. When we resolved a
6378 // reference to an Objective-C class, produce the @interface as
6379 // the definition; when we were provided with the interface,
6380 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006381 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006382 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006383 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006384 return MakeCXCursor(Def, TU);
6385 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6386 return MakeCXCursor(Impl, TU);
6387 return clang_getNullCursor();
6388 }
6389
6390 case Decl::ObjCProperty:
6391 // FIXME: We don't really know where to find the
6392 // ObjCPropertyImplDecls that implement this property.
6393 return clang_getNullCursor();
6394
6395 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006396 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006397 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006398 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006399 return MakeCXCursor(Def, TU);
6400
6401 return clang_getNullCursor();
6402
6403 case Decl::Friend:
6404 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6405 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6406 return clang_getNullCursor();
6407
6408 case Decl::FriendTemplate:
6409 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6410 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6411 return clang_getNullCursor();
6412 }
6413
6414 return clang_getNullCursor();
6415}
6416
6417unsigned clang_isCursorDefinition(CXCursor C) {
6418 if (!clang_isDeclaration(C.kind))
6419 return 0;
6420
6421 return clang_getCursorDefinition(C) == C;
6422}
6423
6424CXCursor clang_getCanonicalCursor(CXCursor C) {
6425 if (!clang_isDeclaration(C.kind))
6426 return C;
6427
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006428 if (const Decl *D = getCursorDecl(C)) {
6429 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6431 return MakeCXCursor(CatD, getCursorTU(C));
6432
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006433 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6434 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006435 return MakeCXCursor(IFD, getCursorTU(C));
6436
6437 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6438 }
6439
6440 return C;
6441}
6442
6443int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6444 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6445}
6446
6447unsigned clang_getNumOverloadedDecls(CXCursor C) {
6448 if (C.kind != CXCursor_OverloadedDeclRef)
6449 return 0;
6450
6451 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006452 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006453 return E->getNumDecls();
6454
6455 if (OverloadedTemplateStorage *S
6456 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6457 return S->size();
6458
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006459 const Decl *D = Storage.get<const Decl *>();
6460 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006461 return Using->shadow_size();
6462
6463 return 0;
6464}
6465
6466CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6467 if (cursor.kind != CXCursor_OverloadedDeclRef)
6468 return clang_getNullCursor();
6469
6470 if (index >= clang_getNumOverloadedDecls(cursor))
6471 return clang_getNullCursor();
6472
6473 CXTranslationUnit TU = getCursorTU(cursor);
6474 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006475 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006476 return MakeCXCursor(E->decls_begin()[index], TU);
6477
6478 if (OverloadedTemplateStorage *S
6479 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6480 return MakeCXCursor(S->begin()[index], TU);
6481
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006482 const Decl *D = Storage.get<const Decl *>();
6483 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 // FIXME: This is, unfortunately, linear time.
6485 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6486 std::advance(Pos, index);
6487 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6488 }
6489
6490 return clang_getNullCursor();
6491}
6492
6493void clang_getDefinitionSpellingAndExtent(CXCursor C,
6494 const char **startBuf,
6495 const char **endBuf,
6496 unsigned *startLine,
6497 unsigned *startColumn,
6498 unsigned *endLine,
6499 unsigned *endColumn) {
6500 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006501 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6503
6504 SourceManager &SM = FD->getASTContext().getSourceManager();
6505 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6506 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6507 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6508 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6509 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6510 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6511}
6512
6513
6514CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6515 unsigned PieceIndex) {
6516 RefNamePieces Pieces;
6517
6518 switch (C.kind) {
6519 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006520 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6522 E->getQualifierLoc().getSourceRange());
6523 break;
6524
6525 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006526 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6527 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6528 Pieces =
6529 buildPieces(NameFlags, false, E->getNameInfo(),
6530 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6531 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 break;
6533
6534 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006535 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006536 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006537 const Expr *Callee = OCE->getCallee();
6538 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 Callee = ICE->getSubExpr();
6540
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006541 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006542 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6543 DRE->getQualifierLoc().getSourceRange());
6544 }
6545 break;
6546
6547 default:
6548 break;
6549 }
6550
6551 if (Pieces.empty()) {
6552 if (PieceIndex == 0)
6553 return clang_getCursorExtent(C);
6554 } else if (PieceIndex < Pieces.size()) {
6555 SourceRange R = Pieces[PieceIndex];
6556 if (R.isValid())
6557 return cxloc::translateSourceRange(getCursorContext(C), R);
6558 }
6559
6560 return clang_getNullRange();
6561}
6562
6563void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006564 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6565 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006566}
6567
6568void clang_executeOnThread(void (*fn)(void*), void *user_data,
6569 unsigned stack_size) {
6570 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6571}
6572
Guy Benyei11169dd2012-12-18 14:30:41 +00006573//===----------------------------------------------------------------------===//
6574// Token-based Operations.
6575//===----------------------------------------------------------------------===//
6576
6577/* CXToken layout:
6578 * int_data[0]: a CXTokenKind
6579 * int_data[1]: starting token location
6580 * int_data[2]: token length
6581 * int_data[3]: reserved
6582 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6583 * otherwise unused.
6584 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006585CXTokenKind clang_getTokenKind(CXToken CXTok) {
6586 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6587}
6588
6589CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6590 switch (clang_getTokenKind(CXTok)) {
6591 case CXToken_Identifier:
6592 case CXToken_Keyword:
6593 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006594 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 ->getNameStart());
6596
6597 case CXToken_Literal: {
6598 // We have stashed the starting pointer in the ptr_data field. Use it.
6599 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006600 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006601 }
6602
6603 case CXToken_Punctuation:
6604 case CXToken_Comment:
6605 break;
6606 }
6607
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006608 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006609 LOG_BAD_TU(TU);
6610 return cxstring::createEmpty();
6611 }
6612
Guy Benyei11169dd2012-12-18 14:30:41 +00006613 // We have to find the starting buffer pointer the hard way, by
6614 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006615 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006616 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006617 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006618
6619 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6620 std::pair<FileID, unsigned> LocInfo
6621 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6622 bool Invalid = false;
6623 StringRef Buffer
6624 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6625 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006626 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006627
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006628 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006629}
6630
6631CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006632 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006633 LOG_BAD_TU(TU);
6634 return clang_getNullLocation();
6635 }
6636
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006637 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006638 if (!CXXUnit)
6639 return clang_getNullLocation();
6640
6641 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6642 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6643}
6644
6645CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006646 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006647 LOG_BAD_TU(TU);
6648 return clang_getNullRange();
6649 }
6650
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006651 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006652 if (!CXXUnit)
6653 return clang_getNullRange();
6654
6655 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6656 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6657}
6658
6659static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6660 SmallVectorImpl<CXToken> &CXTokens) {
6661 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6662 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006663 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006664 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006665 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006666
6667 // Cannot tokenize across files.
6668 if (BeginLocInfo.first != EndLocInfo.first)
6669 return;
6670
6671 // Create a lexer
6672 bool Invalid = false;
6673 StringRef Buffer
6674 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6675 if (Invalid)
6676 return;
6677
6678 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6679 CXXUnit->getASTContext().getLangOpts(),
6680 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6681 Lex.SetCommentRetentionState(true);
6682
6683 // Lex tokens until we hit the end of the range.
6684 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6685 Token Tok;
6686 bool previousWasAt = false;
6687 do {
6688 // Lex the next token
6689 Lex.LexFromRawLexer(Tok);
6690 if (Tok.is(tok::eof))
6691 break;
6692
6693 // Initialize the CXToken.
6694 CXToken CXTok;
6695
6696 // - Common fields
6697 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6698 CXTok.int_data[2] = Tok.getLength();
6699 CXTok.int_data[3] = 0;
6700
6701 // - Kind-specific fields
6702 if (Tok.isLiteral()) {
6703 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006704 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 } else if (Tok.is(tok::raw_identifier)) {
6706 // Lookup the identifier to determine whether we have a keyword.
6707 IdentifierInfo *II
6708 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6709
6710 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6711 CXTok.int_data[0] = CXToken_Keyword;
6712 }
6713 else {
6714 CXTok.int_data[0] = Tok.is(tok::identifier)
6715 ? CXToken_Identifier
6716 : CXToken_Keyword;
6717 }
6718 CXTok.ptr_data = II;
6719 } else if (Tok.is(tok::comment)) {
6720 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006721 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006722 } else {
6723 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006724 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 }
6726 CXTokens.push_back(CXTok);
6727 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006728 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006729}
6730
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006731CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6732 LOG_FUNC_SECTION {
6733 *Log << TU << ' ' << Location;
6734 }
6735
6736 if (isNotUsableTU(TU)) {
6737 LOG_BAD_TU(TU);
6738 return NULL;
6739 }
6740
6741 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6742 if (!CXXUnit)
6743 return NULL;
6744
6745 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6746 if (Begin.isInvalid())
6747 return NULL;
6748 SourceManager &SM = CXXUnit->getSourceManager();
6749 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6750 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6751
6752 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6753
6754 SmallVector<CXToken, 32> CXTokens;
6755 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6756
6757 if (CXTokens.empty())
6758 return NULL;
6759
6760 CXTokens.resize(1);
6761 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6762
6763 memmove(Token, CXTokens.data(), sizeof(CXToken));
6764 return Token;
6765}
6766
Guy Benyei11169dd2012-12-18 14:30:41 +00006767void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6768 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006769 LOG_FUNC_SECTION {
6770 *Log << TU << ' ' << Range;
6771 }
6772
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006774 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006775 if (NumTokens)
6776 *NumTokens = 0;
6777
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006778 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006779 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006780 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006781 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006782
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006783 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006784 if (!CXXUnit || !Tokens || !NumTokens)
6785 return;
6786
6787 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6788
6789 SourceRange R = cxloc::translateCXSourceRange(Range);
6790 if (R.isInvalid())
6791 return;
6792
6793 SmallVector<CXToken, 32> CXTokens;
6794 getTokens(CXXUnit, R, CXTokens);
6795
6796 if (CXTokens.empty())
6797 return;
6798
Serge Pavlov52525732018-02-21 02:02:39 +00006799 *Tokens = static_cast<CXToken *>(
6800 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006801 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6802 *NumTokens = CXTokens.size();
6803}
6804
6805void clang_disposeTokens(CXTranslationUnit TU,
6806 CXToken *Tokens, unsigned NumTokens) {
6807 free(Tokens);
6808}
6809
Guy Benyei11169dd2012-12-18 14:30:41 +00006810//===----------------------------------------------------------------------===//
6811// Token annotation APIs.
6812//===----------------------------------------------------------------------===//
6813
Guy Benyei11169dd2012-12-18 14:30:41 +00006814static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6815 CXCursor parent,
6816 CXClientData client_data);
6817static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6818 CXClientData client_data);
6819
6820namespace {
6821class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006822 CXToken *Tokens;
6823 CXCursor *Cursors;
6824 unsigned NumTokens;
6825 unsigned TokIdx;
6826 unsigned PreprocessingTokIdx;
6827 CursorVisitor AnnotateVis;
6828 SourceManager &SrcMgr;
6829 bool HasContextSensitiveKeywords;
6830
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006831 struct PostChildrenAction {
6832 CXCursor cursor;
6833 enum Action { Invalid, Ignore, Postpone } action;
6834 };
6835 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6836
Guy Benyei11169dd2012-12-18 14:30:41 +00006837 struct PostChildrenInfo {
6838 CXCursor Cursor;
6839 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006840 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006841 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006842 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006843 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006844 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006845
6846 CXToken &getTok(unsigned Idx) {
6847 assert(Idx < NumTokens);
6848 return Tokens[Idx];
6849 }
6850 const CXToken &getTok(unsigned Idx) const {
6851 assert(Idx < NumTokens);
6852 return Tokens[Idx];
6853 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006854 bool MoreTokens() const { return TokIdx < NumTokens; }
6855 unsigned NextToken() const { return TokIdx; }
6856 void AdvanceToken() { ++TokIdx; }
6857 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006858 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006859 }
6860 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006861 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006862 }
6863 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006864 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006865 }
6866
6867 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006868 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006869 SourceRange);
6870
6871public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006872 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006873 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006874 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006875 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006876 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006877 AnnotateTokensVisitor, this,
6878 /*VisitPreprocessorLast=*/true,
6879 /*VisitIncludedEntities=*/false,
6880 RegionOfInterest,
6881 /*VisitDeclsOnly=*/false,
6882 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006883 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006884 HasContextSensitiveKeywords(false) { }
6885
6886 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6887 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006888 bool IsIgnoredChildCursor(CXCursor cursor) const;
6889 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6890
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006892 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6893 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6894
Guy Benyei11169dd2012-12-18 14:30:41 +00006895 void AnnotateTokens();
6896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006897 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006898 /// context-sensitive keywords.
6899 bool hasContextSensitiveKeywords() const {
6900 return HasContextSensitiveKeywords;
6901 }
6902
6903 ~AnnotateTokensWorker() {
6904 assert(PostChildrenInfos.empty());
6905 }
6906};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006907}
Guy Benyei11169dd2012-12-18 14:30:41 +00006908
6909void AnnotateTokensWorker::AnnotateTokens() {
6910 // Walk the AST within the region of interest, annotating tokens
6911 // along the way.
6912 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006913}
Guy Benyei11169dd2012-12-18 14:30:41 +00006914
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006915bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6916 if (PostChildrenInfos.empty())
6917 return false;
6918
6919 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6920 if (ChildAction.cursor == cursor &&
6921 ChildAction.action == PostChildrenAction::Ignore) {
6922 return true;
6923 }
6924 }
6925
6926 return false;
6927}
6928
6929const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6930 if (!clang_isExpression(Cursor.kind))
6931 return nullptr;
6932
6933 const Expr *E = getCursorExpr(Cursor);
6934 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6935 const OverloadedOperatorKind Kind = OCE->getOperator();
6936 if (Kind == OO_Call || Kind == OO_Subscript)
6937 return OCE;
6938 }
6939
6940 return nullptr;
6941}
6942
6943AnnotateTokensWorker::PostChildrenActions
6944AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6945 PostChildrenActions actions;
6946
6947 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6948 // visited before the arguments to the operator call. For the Call and
6949 // Subscript operator the range of this DeclRefExpr includes the whole call
6950 // expression, so that all tokens in that range would be mapped to the
6951 // operator function, including the tokens of the arguments. To avoid that,
6952 // ensure to visit this DeclRefExpr as last node.
6953 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6954 const Expr *Callee = OCE->getCallee();
6955 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6956 const Expr *SubExpr = ICE->getSubExpr();
6957 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00006958 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006959 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6960
6961 // Visit the DeclRefExpr as last.
6962 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6963 actions.push_back({cxChild, PostChildrenAction::Postpone});
6964
6965 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6966 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6967 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6968 actions.push_back({cxChild, PostChildrenAction::Ignore});
6969 }
6970 }
6971 }
6972
6973 return actions;
6974}
6975
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006976static inline void updateCursorAnnotation(CXCursor &Cursor,
6977 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006978 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006979 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006980 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006981}
6982
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006983/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006984//// between the cursor location and the source range is the same as
6985/// \arg compResult.
6986///
6987/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6988/// Pass RangeOverlap to annotate tokens inside a range.
6989void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6990 RangeComparisonResult compResult,
6991 SourceRange range) {
6992 while (MoreTokens()) {
6993 const unsigned I = NextToken();
6994 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006995 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6996 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006997
6998 SourceLocation TokLoc = GetTokenLoc(I);
6999 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007000 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007001 AdvanceToken();
7002 continue;
7003 }
7004 break;
7005 }
7006}
7007
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007008/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007009/// \returns true if it advanced beyond all macro tokens, false otherwise.
7010bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 CXCursor updateC,
7012 RangeComparisonResult compResult,
7013 SourceRange range) {
7014 assert(MoreTokens());
7015 assert(isFunctionMacroToken(NextToken()) &&
7016 "Should be called only for macro arg tokens");
7017
7018 // This works differently than annotateAndAdvanceTokens; because expanded
7019 // macro arguments can have arbitrary translation-unit source order, we do not
7020 // advance the token index one by one until a token fails the range test.
7021 // We only advance once past all of the macro arg tokens if all of them
7022 // pass the range test. If one of them fails we keep the token index pointing
7023 // at the start of the macro arg tokens so that the failing token will be
7024 // annotated by a subsequent annotation try.
7025
7026 bool atLeastOneCompFail = false;
7027
7028 unsigned I = NextToken();
7029 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7030 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7031 if (TokLoc.isFileID())
7032 continue; // not macro arg token, it's parens or comma.
7033 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7034 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7035 Cursors[I] = updateC;
7036 } else
7037 atLeastOneCompFail = true;
7038 }
7039
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007040 if (atLeastOneCompFail)
7041 return false;
7042
7043 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7044 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007045}
7046
7047enum CXChildVisitResult
7048AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007049 SourceRange cursorRange = getRawCursorExtent(cursor);
7050 if (cursorRange.isInvalid())
7051 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007052
7053 if (IsIgnoredChildCursor(cursor))
7054 return CXChildVisit_Continue;
7055
Guy Benyei11169dd2012-12-18 14:30:41 +00007056 if (!HasContextSensitiveKeywords) {
7057 // Objective-C properties can have context-sensitive keywords.
7058 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007059 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007060 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7061 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7062 }
7063 // Objective-C methods can have context-sensitive keywords.
7064 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7065 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007066 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007067 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7068 if (Method->getObjCDeclQualifier())
7069 HasContextSensitiveKeywords = true;
7070 else {
David Majnemer59f77922016-06-24 04:05:48 +00007071 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007072 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007073 HasContextSensitiveKeywords = true;
7074 break;
7075 }
7076 }
7077 }
7078 }
7079 }
7080 // C++ methods can have context-sensitive keywords.
7081 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007082 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007083 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7084 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7085 HasContextSensitiveKeywords = true;
7086 }
7087 }
7088 // C++ classes can have context-sensitive keywords.
7089 else if (cursor.kind == CXCursor_StructDecl ||
7090 cursor.kind == CXCursor_ClassDecl ||
7091 cursor.kind == CXCursor_ClassTemplate ||
7092 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007093 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007094 if (D->hasAttr<FinalAttr>())
7095 HasContextSensitiveKeywords = true;
7096 }
7097 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007098
7099 // Don't override a property annotation with its getter/setter method.
7100 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7101 parent.kind == CXCursor_ObjCPropertyDecl)
7102 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007103
7104 if (clang_isPreprocessing(cursor.kind)) {
7105 // Items in the preprocessing record are kept separate from items in
7106 // declarations, so we keep a separate token index.
7107 unsigned SavedTokIdx = TokIdx;
7108 TokIdx = PreprocessingTokIdx;
7109
7110 // Skip tokens up until we catch up to the beginning of the preprocessing
7111 // entry.
7112 while (MoreTokens()) {
7113 const unsigned I = NextToken();
7114 SourceLocation TokLoc = GetTokenLoc(I);
7115 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7116 case RangeBefore:
7117 AdvanceToken();
7118 continue;
7119 case RangeAfter:
7120 case RangeOverlap:
7121 break;
7122 }
7123 break;
7124 }
7125
7126 // Look at all of the tokens within this range.
7127 while (MoreTokens()) {
7128 const unsigned I = NextToken();
7129 SourceLocation TokLoc = GetTokenLoc(I);
7130 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7131 case RangeBefore:
7132 llvm_unreachable("Infeasible");
7133 case RangeAfter:
7134 break;
7135 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007136 // For macro expansions, just note where the beginning of the macro
7137 // expansion occurs.
7138 if (cursor.kind == CXCursor_MacroExpansion) {
7139 if (TokLoc == cursorRange.getBegin())
7140 Cursors[I] = cursor;
7141 AdvanceToken();
7142 break;
7143 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007144 // We may have already annotated macro names inside macro definitions.
7145 if (Cursors[I].kind != CXCursor_MacroExpansion)
7146 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007147 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007148 continue;
7149 }
7150 break;
7151 }
7152
7153 // Save the preprocessing token index; restore the non-preprocessing
7154 // token index.
7155 PreprocessingTokIdx = TokIdx;
7156 TokIdx = SavedTokIdx;
7157 return CXChildVisit_Recurse;
7158 }
7159
7160 if (cursorRange.isInvalid())
7161 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007162
7163 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007164 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 const enum CXCursorKind K = clang_getCursorKind(parent);
7166 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007167 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7168 // Attributes are annotated out-of-order, skip tokens until we reach it.
7169 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 ? clang_getNullCursor() : parent;
7171
7172 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7173
7174 // Avoid having the cursor of an expression "overwrite" the annotation of the
7175 // variable declaration that it belongs to.
7176 // This can happen for C++ constructor expressions whose range generally
7177 // include the variable declaration, e.g.:
7178 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007179 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007180 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007181 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007182 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007183 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7184 E->getBeginLoc() == D->getLocation() &&
7185 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007186 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007187 AdvanceToken();
7188 }
7189 }
7190 }
7191
7192 // Before recursing into the children keep some state that we are going
7193 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7194 // extra work after the child nodes are visited.
7195 // Note that we don't call VisitChildren here to avoid traversing statements
7196 // code-recursively which can blow the stack.
7197
7198 PostChildrenInfo Info;
7199 Info.Cursor = cursor;
7200 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007201 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007202 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007203 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007204 PostChildrenInfos.push_back(Info);
7205
7206 return CXChildVisit_Recurse;
7207}
7208
7209bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7210 if (PostChildrenInfos.empty())
7211 return false;
7212 const PostChildrenInfo &Info = PostChildrenInfos.back();
7213 if (!clang_equalCursors(Info.Cursor, cursor))
7214 return false;
7215
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007216 HandlePostPonedChildCursors(Info);
7217
Guy Benyei11169dd2012-12-18 14:30:41 +00007218 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7219 const unsigned AfterChildren = NextToken();
7220 SourceRange cursorRange = Info.CursorRange;
7221
7222 // Scan the tokens that are at the end of the cursor, but are not captured
7223 // but the child cursors.
7224 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7225
7226 // Scan the tokens that are at the beginning of the cursor, but are not
7227 // capture by the child cursors.
7228 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7229 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7230 break;
7231
7232 Cursors[I] = cursor;
7233 }
7234
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007235 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7236 // encountered the attribute cursor.
7237 if (clang_isAttribute(cursor.kind))
7238 TokIdx = Info.BeforeReachingCursorIdx;
7239
Guy Benyei11169dd2012-12-18 14:30:41 +00007240 PostChildrenInfos.pop_back();
7241 return false;
7242}
7243
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007244void AnnotateTokensWorker::HandlePostPonedChildCursors(
7245 const PostChildrenInfo &Info) {
7246 for (const auto &ChildAction : Info.ChildActions) {
7247 if (ChildAction.action == PostChildrenAction::Postpone) {
7248 HandlePostPonedChildCursor(ChildAction.cursor,
7249 Info.BeforeChildrenTokenIdx);
7250 }
7251 }
7252}
7253
7254void AnnotateTokensWorker::HandlePostPonedChildCursor(
7255 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007256 unsigned I = StartTokenIndex;
7257
7258 // The bracket tokens of a Call or Subscript operator are mapped to
7259 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7260 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7261 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007262 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7263 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007264 if (clang_Range_isNull(CXRefNameRange))
7265 break; // All ranges handled.
7266
7267 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7268 while (I < NumTokens) {
7269 const SourceLocation TokenLocation = GetTokenLoc(I);
7270 if (!TokenLocation.isValid())
7271 break;
7272
7273 // Adapt the end range, because LocationCompare() reports
7274 // RangeOverlap even for the not-inclusive end location.
7275 const SourceLocation fixedEnd =
7276 RefNameRange.getEnd().getLocWithOffset(-1);
7277 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7278
7279 const RangeComparisonResult ComparisonResult =
7280 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7281
7282 if (ComparisonResult == RangeOverlap) {
7283 Cursors[I++] = Cursor;
7284 } else if (ComparisonResult == RangeBefore) {
7285 ++I; // Not relevant token, check next one.
7286 } else if (ComparisonResult == RangeAfter) {
7287 break; // All tokens updated for current range, check next.
7288 }
7289 }
7290 }
7291}
7292
Guy Benyei11169dd2012-12-18 14:30:41 +00007293static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7294 CXCursor parent,
7295 CXClientData client_data) {
7296 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7297}
7298
7299static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7300 CXClientData client_data) {
7301 return static_cast<AnnotateTokensWorker*>(client_data)->
7302 postVisitChildren(cursor);
7303}
7304
7305namespace {
7306
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007307/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007308/// and mark tokens that are macro arguments. This info is used by the
7309/// AnnotateTokensWorker.
7310class MarkMacroArgTokensVisitor {
7311 SourceManager &SM;
7312 CXToken *Tokens;
7313 unsigned NumTokens;
7314 unsigned CurIdx;
7315
7316public:
7317 MarkMacroArgTokensVisitor(SourceManager &SM,
7318 CXToken *tokens, unsigned numTokens)
7319 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7320
7321 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7322 if (cursor.kind != CXCursor_MacroExpansion)
7323 return CXChildVisit_Continue;
7324
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007325 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007326 if (macroRange.getBegin() == macroRange.getEnd())
7327 return CXChildVisit_Continue; // it's not a function macro.
7328
7329 for (; CurIdx < NumTokens; ++CurIdx) {
7330 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7331 macroRange.getBegin()))
7332 break;
7333 }
7334
7335 if (CurIdx == NumTokens)
7336 return CXChildVisit_Break;
7337
7338 for (; CurIdx < NumTokens; ++CurIdx) {
7339 SourceLocation tokLoc = getTokenLoc(CurIdx);
7340 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7341 break;
7342
7343 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7344 }
7345
7346 if (CurIdx == NumTokens)
7347 return CXChildVisit_Break;
7348
7349 return CXChildVisit_Continue;
7350 }
7351
7352private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007353 CXToken &getTok(unsigned Idx) {
7354 assert(Idx < NumTokens);
7355 return Tokens[Idx];
7356 }
7357 const CXToken &getTok(unsigned Idx) const {
7358 assert(Idx < NumTokens);
7359 return Tokens[Idx];
7360 }
7361
Guy Benyei11169dd2012-12-18 14:30:41 +00007362 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007363 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007364 }
7365
7366 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7367 // The third field is reserved and currently not used. Use it here
7368 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007369 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007370 }
7371};
7372
7373} // end anonymous namespace
7374
7375static CXChildVisitResult
7376MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7377 CXClientData client_data) {
7378 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7379 parent);
7380}
7381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007382/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007383/// \returns true if lexing was finished, false otherwise.
7384static bool lexNext(Lexer &Lex, Token &Tok,
7385 unsigned &NextIdx, unsigned NumTokens) {
7386 if (NextIdx >= NumTokens)
7387 return true;
7388
7389 ++NextIdx;
7390 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007391 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007392}
7393
Guy Benyei11169dd2012-12-18 14:30:41 +00007394static void annotatePreprocessorTokens(CXTranslationUnit TU,
7395 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007396 CXCursor *Cursors,
7397 CXToken *Tokens,
7398 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007399 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007400
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007401 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007402 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7403 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007404 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007405 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007406 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007407
7408 if (BeginLocInfo.first != EndLocInfo.first)
7409 return;
7410
7411 StringRef Buffer;
7412 bool Invalid = false;
7413 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7414 if (Buffer.empty() || Invalid)
7415 return;
7416
7417 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7418 CXXUnit->getASTContext().getLangOpts(),
7419 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7420 Buffer.end());
7421 Lex.SetCommentRetentionState(true);
7422
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007423 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007424 // Lex tokens in raw mode until we hit the end of the range, to avoid
7425 // entering #includes or expanding macros.
7426 while (true) {
7427 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007428 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7429 break;
7430 unsigned TokIdx = NextIdx-1;
7431 assert(Tok.getLocation() ==
7432 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007433
7434 reprocess:
7435 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007436 // We have found a preprocessing directive. Annotate the tokens
7437 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007438 //
7439 // FIXME: Some simple tests here could identify macro definitions and
7440 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007441
7442 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007443 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7444 break;
7445
Craig Topper69186e72014-06-08 08:38:04 +00007446 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007447 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007448 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7449 break;
7450
7451 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007452 IdentifierInfo &II =
7453 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007454 SourceLocation MappedTokLoc =
7455 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7456 MI = getMacroInfo(II, MappedTokLoc, TU);
7457 }
7458 }
7459
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007460 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007461 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007462 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7463 finished = true;
7464 break;
7465 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007466 // If we are in a macro definition, check if the token was ever a
7467 // macro name and annotate it if that's the case.
7468 if (MI) {
7469 SourceLocation SaveLoc = Tok.getLocation();
7470 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007471 MacroDefinitionRecord *MacroDef =
7472 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007473 Tok.setLocation(SaveLoc);
7474 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007475 Cursors[NextIdx - 1] =
7476 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007477 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007478 } while (!Tok.isAtStartOfLine());
7479
7480 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7481 assert(TokIdx <= LastIdx);
7482 SourceLocation EndLoc =
7483 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7484 CXCursor Cursor =
7485 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7486
7487 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007488 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007489
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007490 if (finished)
7491 break;
7492 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007493 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007494 }
7495}
7496
7497// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007498static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7499 CXToken *Tokens, unsigned NumTokens,
7500 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007501 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007502 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7503 setThreadBackgroundPriority();
7504
7505 // Determine the region of interest, which contains all of the tokens.
7506 SourceRange RegionOfInterest;
7507 RegionOfInterest.setBegin(
7508 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7509 RegionOfInterest.setEnd(
7510 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7511 Tokens[NumTokens-1])));
7512
Guy Benyei11169dd2012-12-18 14:30:41 +00007513 // Relex the tokens within the source range to look for preprocessing
7514 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007515 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007516
7517 // If begin location points inside a macro argument, set it to the expansion
7518 // location so we can have the full context when annotating semantically.
7519 {
7520 SourceManager &SM = CXXUnit->getSourceManager();
7521 SourceLocation Loc =
7522 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7523 if (Loc.isMacroID())
7524 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7525 }
7526
Guy Benyei11169dd2012-12-18 14:30:41 +00007527 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7528 // Search and mark tokens that are macro argument expansions.
7529 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7530 Tokens, NumTokens);
7531 CursorVisitor MacroArgMarker(TU,
7532 MarkMacroArgTokensVisitorDelegate, &Visitor,
7533 /*VisitPreprocessorLast=*/true,
7534 /*VisitIncludedEntities=*/false,
7535 RegionOfInterest);
7536 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7537 }
7538
7539 // Annotate all of the source locations in the region of interest that map to
7540 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007541 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007542
7543 // FIXME: We use a ridiculous stack size here because the data-recursion
7544 // algorithm uses a large stack frame than the non-data recursive version,
7545 // and AnnotationTokensWorker currently transforms the data-recursion
7546 // algorithm back into a traditional recursion by explicitly calling
7547 // VisitChildren(). We will need to remove this explicit recursive call.
7548 W.AnnotateTokens();
7549
7550 // If we ran into any entities that involve context-sensitive keywords,
7551 // take another pass through the tokens to mark them as such.
7552 if (W.hasContextSensitiveKeywords()) {
7553 for (unsigned I = 0; I != NumTokens; ++I) {
7554 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7555 continue;
7556
7557 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7558 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007559 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007560 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7561 if (Property->getPropertyAttributesAsWritten() != 0 &&
7562 llvm::StringSwitch<bool>(II->getName())
7563 .Case("readonly", true)
7564 .Case("assign", true)
7565 .Case("unsafe_unretained", true)
7566 .Case("readwrite", true)
7567 .Case("retain", true)
7568 .Case("copy", true)
7569 .Case("nonatomic", true)
7570 .Case("atomic", true)
7571 .Case("getter", true)
7572 .Case("setter", true)
7573 .Case("strong", true)
7574 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007575 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007576 .Default(false))
7577 Tokens[I].int_data[0] = CXToken_Keyword;
7578 }
7579 continue;
7580 }
7581
7582 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7583 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7584 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7585 if (llvm::StringSwitch<bool>(II->getName())
7586 .Case("in", true)
7587 .Case("out", true)
7588 .Case("inout", true)
7589 .Case("oneway", true)
7590 .Case("bycopy", true)
7591 .Case("byref", true)
7592 .Default(false))
7593 Tokens[I].int_data[0] = CXToken_Keyword;
7594 continue;
7595 }
7596
7597 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7598 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7599 Tokens[I].int_data[0] = CXToken_Keyword;
7600 continue;
7601 }
7602 }
7603 }
7604}
7605
Guy Benyei11169dd2012-12-18 14:30:41 +00007606void clang_annotateTokens(CXTranslationUnit TU,
7607 CXToken *Tokens, unsigned NumTokens,
7608 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007609 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007610 LOG_BAD_TU(TU);
7611 return;
7612 }
7613 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007614 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007615 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007616 }
7617
7618 LOG_FUNC_SECTION {
7619 *Log << TU << ' ';
7620 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7621 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7622 *Log << clang_getRange(bloc, eloc);
7623 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007624
7625 // Any token we don't specifically annotate will have a NULL cursor.
7626 CXCursor C = clang_getNullCursor();
7627 for (unsigned I = 0; I != NumTokens; ++I)
7628 Cursors[I] = C;
7629
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007630 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007631 if (!CXXUnit)
7632 return;
7633
7634 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007635
7636 auto AnnotateTokensImpl = [=]() {
7637 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7638 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007639 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007640 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007641 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7642 }
7643}
7644
Guy Benyei11169dd2012-12-18 14:30:41 +00007645//===----------------------------------------------------------------------===//
7646// Operations for querying linkage of a cursor.
7647//===----------------------------------------------------------------------===//
7648
Guy Benyei11169dd2012-12-18 14:30:41 +00007649CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7650 if (!clang_isDeclaration(cursor.kind))
7651 return CXLinkage_Invalid;
7652
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007653 const Decl *D = cxcursor::getCursorDecl(cursor);
7654 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007655 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007656 case NoLinkage:
7657 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007658 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007659 case InternalLinkage: return CXLinkage_Internal;
7660 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007661 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007662 case ExternalLinkage: return CXLinkage_External;
7663 };
7664
7665 return CXLinkage_Invalid;
7666}
Guy Benyei11169dd2012-12-18 14:30:41 +00007667
7668//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007669// Operations for querying visibility of a cursor.
7670//===----------------------------------------------------------------------===//
7671
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007672CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7673 if (!clang_isDeclaration(cursor.kind))
7674 return CXVisibility_Invalid;
7675
7676 const Decl *D = cxcursor::getCursorDecl(cursor);
7677 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7678 switch (ND->getVisibility()) {
7679 case HiddenVisibility: return CXVisibility_Hidden;
7680 case ProtectedVisibility: return CXVisibility_Protected;
7681 case DefaultVisibility: return CXVisibility_Default;
7682 };
7683
7684 return CXVisibility_Invalid;
7685}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007686
7687//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007688// Operations for querying language of a cursor.
7689//===----------------------------------------------------------------------===//
7690
7691static CXLanguageKind getDeclLanguage(const Decl *D) {
7692 if (!D)
7693 return CXLanguage_C;
7694
7695 switch (D->getKind()) {
7696 default:
7697 break;
7698 case Decl::ImplicitParam:
7699 case Decl::ObjCAtDefsField:
7700 case Decl::ObjCCategory:
7701 case Decl::ObjCCategoryImpl:
7702 case Decl::ObjCCompatibleAlias:
7703 case Decl::ObjCImplementation:
7704 case Decl::ObjCInterface:
7705 case Decl::ObjCIvar:
7706 case Decl::ObjCMethod:
7707 case Decl::ObjCProperty:
7708 case Decl::ObjCPropertyImpl:
7709 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007710 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007711 return CXLanguage_ObjC;
7712 case Decl::CXXConstructor:
7713 case Decl::CXXConversion:
7714 case Decl::CXXDestructor:
7715 case Decl::CXXMethod:
7716 case Decl::CXXRecord:
7717 case Decl::ClassTemplate:
7718 case Decl::ClassTemplatePartialSpecialization:
7719 case Decl::ClassTemplateSpecialization:
7720 case Decl::Friend:
7721 case Decl::FriendTemplate:
7722 case Decl::FunctionTemplate:
7723 case Decl::LinkageSpec:
7724 case Decl::Namespace:
7725 case Decl::NamespaceAlias:
7726 case Decl::NonTypeTemplateParm:
7727 case Decl::StaticAssert:
7728 case Decl::TemplateTemplateParm:
7729 case Decl::TemplateTypeParm:
7730 case Decl::UnresolvedUsingTypename:
7731 case Decl::UnresolvedUsingValue:
7732 case Decl::Using:
7733 case Decl::UsingDirective:
7734 case Decl::UsingShadow:
7735 return CXLanguage_CPlusPlus;
7736 }
7737
7738 return CXLanguage_C;
7739}
7740
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007741static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7742 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007743 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007744
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007745 switch (D->getAvailability()) {
7746 case AR_Available:
7747 case AR_NotYetIntroduced:
7748 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007749 return getCursorAvailabilityForDecl(
7750 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007751 return CXAvailability_Available;
7752
7753 case AR_Deprecated:
7754 return CXAvailability_Deprecated;
7755
7756 case AR_Unavailable:
7757 return CXAvailability_NotAvailable;
7758 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007759
7760 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007761}
7762
Guy Benyei11169dd2012-12-18 14:30:41 +00007763enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7764 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007765 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7766 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007767
7768 return CXAvailability_Available;
7769}
7770
7771static CXVersion convertVersion(VersionTuple In) {
7772 CXVersion Out = { -1, -1, -1 };
7773 if (In.empty())
7774 return Out;
7775
7776 Out.Major = In.getMajor();
7777
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007778 Optional<unsigned> Minor = In.getMinor();
7779 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007780 Out.Minor = *Minor;
7781 else
7782 return Out;
7783
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007784 Optional<unsigned> Subminor = In.getSubminor();
7785 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007786 Out.Subminor = *Subminor;
7787
7788 return Out;
7789}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007790
Alex Lorenz1345ea22017-06-12 19:06:30 +00007791static void getCursorPlatformAvailabilityForDecl(
7792 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7793 int *always_unavailable, CXString *unavailable_message,
7794 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007795 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007796 for (auto A : D->attrs()) {
7797 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007798 HadAvailAttr = true;
7799 if (always_deprecated)
7800 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007801 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007802 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007803 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007804 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007805 continue;
7806 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007807
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007808 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007809 HadAvailAttr = true;
7810 if (always_unavailable)
7811 *always_unavailable = 1;
7812 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007813 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007814 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7815 }
7816 continue;
7817 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007818
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007819 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007820 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007821 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007822 }
7823 }
7824
7825 if (!HadAvailAttr)
7826 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7827 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007828 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7829 deprecated_message, always_unavailable, unavailable_message,
7830 AvailabilityAttrs);
7831
7832 if (AvailabilityAttrs.empty())
7833 return;
7834
Fangrui Song55fab262018-09-26 22:16:28 +00007835 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007836 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7837 return LHS->getPlatform()->getName() <
7838 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007839 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007840 ASTContext &Ctx = D->getASTContext();
7841 auto It = std::unique(
7842 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7843 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7844 if (LHS->getPlatform() != RHS->getPlatform())
7845 return false;
7846
7847 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7848 LHS->getDeprecated() == RHS->getDeprecated() &&
7849 LHS->getObsoleted() == RHS->getObsoleted() &&
7850 LHS->getMessage() == RHS->getMessage() &&
7851 LHS->getReplacement() == RHS->getReplacement())
7852 return true;
7853
7854 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7855 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7856 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7857 return false;
7858
7859 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7860 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7861
7862 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7863 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7864 if (LHS->getMessage().empty())
7865 LHS->setMessage(Ctx, RHS->getMessage());
7866 if (LHS->getReplacement().empty())
7867 LHS->setReplacement(Ctx, RHS->getReplacement());
7868 }
7869
7870 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7871 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7872 if (LHS->getMessage().empty())
7873 LHS->setMessage(Ctx, RHS->getMessage());
7874 if (LHS->getReplacement().empty())
7875 LHS->setReplacement(Ctx, RHS->getReplacement());
7876 }
7877
7878 return true;
7879 });
7880 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007881}
7882
Alex Lorenz1345ea22017-06-12 19:06:30 +00007883int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007884 CXString *deprecated_message,
7885 int *always_unavailable,
7886 CXString *unavailable_message,
7887 CXPlatformAvailability *availability,
7888 int availability_size) {
7889 if (always_deprecated)
7890 *always_deprecated = 0;
7891 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007892 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007893 if (always_unavailable)
7894 *always_unavailable = 0;
7895 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007896 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007897
Guy Benyei11169dd2012-12-18 14:30:41 +00007898 if (!clang_isDeclaration(cursor.kind))
7899 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007900
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007901 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007902 if (!D)
7903 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007904
Alex Lorenz1345ea22017-06-12 19:06:30 +00007905 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7906 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7907 always_unavailable, unavailable_message,
7908 AvailabilityAttrs);
7909 for (const auto &Avail :
7910 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7911 .take_front(availability_size))) {
7912 availability[Avail.index()].Platform =
7913 cxstring::createDup(Avail.value()->getPlatform()->getName());
7914 availability[Avail.index()].Introduced =
7915 convertVersion(Avail.value()->getIntroduced());
7916 availability[Avail.index()].Deprecated =
7917 convertVersion(Avail.value()->getDeprecated());
7918 availability[Avail.index()].Obsoleted =
7919 convertVersion(Avail.value()->getObsoleted());
7920 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7921 availability[Avail.index()].Message =
7922 cxstring::createDup(Avail.value()->getMessage());
7923 }
7924
7925 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007926}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007927
Guy Benyei11169dd2012-12-18 14:30:41 +00007928void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7929 clang_disposeString(availability->Platform);
7930 clang_disposeString(availability->Message);
7931}
7932
7933CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7934 if (clang_isDeclaration(cursor.kind))
7935 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7936
7937 return CXLanguage_Invalid;
7938}
7939
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007940CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7941 const Decl *D = cxcursor::getCursorDecl(cursor);
7942 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7943 switch (VD->getTLSKind()) {
7944 case VarDecl::TLS_None:
7945 return CXTLS_None;
7946 case VarDecl::TLS_Dynamic:
7947 return CXTLS_Dynamic;
7948 case VarDecl::TLS_Static:
7949 return CXTLS_Static;
7950 }
7951 }
7952
7953 return CXTLS_None;
7954}
7955
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007956 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007957 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007958 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007959static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007960 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007961 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007962
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007963 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007964 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7965 return FunTmpl;
7966
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007967 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007968 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7969 return ClassTmpl;
7970
7971 return D;
7972}
7973
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007974
7975enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7976 StorageClass sc = SC_None;
7977 const Decl *D = getCursorDecl(C);
7978 if (D) {
7979 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7980 sc = FD->getStorageClass();
7981 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7982 sc = VD->getStorageClass();
7983 } else {
7984 return CX_SC_Invalid;
7985 }
7986 } else {
7987 return CX_SC_Invalid;
7988 }
7989 switch (sc) {
7990 case SC_None:
7991 return CX_SC_None;
7992 case SC_Extern:
7993 return CX_SC_Extern;
7994 case SC_Static:
7995 return CX_SC_Static;
7996 case SC_PrivateExtern:
7997 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007998 case SC_Auto:
7999 return CX_SC_Auto;
8000 case SC_Register:
8001 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008002 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008003 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008004}
8005
Guy Benyei11169dd2012-12-18 14:30:41 +00008006CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8007 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008008 if (const Decl *D = getCursorDecl(cursor)) {
8009 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008010 if (!DC)
8011 return clang_getNullCursor();
8012
8013 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8014 getCursorTU(cursor));
8015 }
8016 }
8017
8018 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008019 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008020 return MakeCXCursor(D, getCursorTU(cursor));
8021 }
8022
8023 return clang_getNullCursor();
8024}
8025
8026CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8027 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008028 if (const Decl *D = getCursorDecl(cursor)) {
8029 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 if (!DC)
8031 return clang_getNullCursor();
8032
8033 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8034 getCursorTU(cursor));
8035 }
8036 }
8037
8038 // FIXME: Note that we can't easily compute the lexical context of a
8039 // statement or expression, so we return nothing.
8040 return clang_getNullCursor();
8041}
8042
8043CXFile clang_getIncludedFile(CXCursor cursor) {
8044 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008045 return nullptr;
8046
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008047 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008048 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008049}
8050
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008051unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8052 if (C.kind != CXCursor_ObjCPropertyDecl)
8053 return CXObjCPropertyAttr_noattr;
8054
8055 unsigned Result = CXObjCPropertyAttr_noattr;
8056 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8057 ObjCPropertyDecl::PropertyAttributeKind Attr =
8058 PD->getPropertyAttributesAsWritten();
8059
8060#define SET_CXOBJCPROP_ATTR(A) \
8061 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8062 Result |= CXObjCPropertyAttr_##A
8063 SET_CXOBJCPROP_ATTR(readonly);
8064 SET_CXOBJCPROP_ATTR(getter);
8065 SET_CXOBJCPROP_ATTR(assign);
8066 SET_CXOBJCPROP_ATTR(readwrite);
8067 SET_CXOBJCPROP_ATTR(retain);
8068 SET_CXOBJCPROP_ATTR(copy);
8069 SET_CXOBJCPROP_ATTR(nonatomic);
8070 SET_CXOBJCPROP_ATTR(setter);
8071 SET_CXOBJCPROP_ATTR(atomic);
8072 SET_CXOBJCPROP_ATTR(weak);
8073 SET_CXOBJCPROP_ATTR(strong);
8074 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008075 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008076#undef SET_CXOBJCPROP_ATTR
8077
8078 return Result;
8079}
8080
Michael Wu6e88f532018-08-03 05:38:29 +00008081CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8082 if (C.kind != CXCursor_ObjCPropertyDecl)
8083 return cxstring::createNull();
8084
8085 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8086 Selector sel = PD->getGetterName();
8087 if (sel.isNull())
8088 return cxstring::createNull();
8089
8090 return cxstring::createDup(sel.getAsString());
8091}
8092
8093CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8094 if (C.kind != CXCursor_ObjCPropertyDecl)
8095 return cxstring::createNull();
8096
8097 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8098 Selector sel = PD->getSetterName();
8099 if (sel.isNull())
8100 return cxstring::createNull();
8101
8102 return cxstring::createDup(sel.getAsString());
8103}
8104
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008105unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8106 if (!clang_isDeclaration(C.kind))
8107 return CXObjCDeclQualifier_None;
8108
8109 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8110 const Decl *D = getCursorDecl(C);
8111 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8112 QT = MD->getObjCDeclQualifier();
8113 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8114 QT = PD->getObjCDeclQualifier();
8115 if (QT == Decl::OBJC_TQ_None)
8116 return CXObjCDeclQualifier_None;
8117
8118 unsigned Result = CXObjCDeclQualifier_None;
8119 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8120 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8121 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8122 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8123 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8124 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8125
8126 return Result;
8127}
8128
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008129unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8130 if (!clang_isDeclaration(C.kind))
8131 return 0;
8132
8133 const Decl *D = getCursorDecl(C);
8134 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8135 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8136 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8137 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8138
8139 return 0;
8140}
8141
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008142unsigned clang_Cursor_isVariadic(CXCursor C) {
8143 if (!clang_isDeclaration(C.kind))
8144 return 0;
8145
8146 const Decl *D = getCursorDecl(C);
8147 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8148 return FD->isVariadic();
8149 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8150 return MD->isVariadic();
8151
8152 return 0;
8153}
8154
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008155unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8156 CXString *language, CXString *definedIn,
8157 unsigned *isGenerated) {
8158 if (!clang_isDeclaration(C.kind))
8159 return 0;
8160
8161 const Decl *D = getCursorDecl(C);
8162
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008163 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008164 if (language)
8165 *language = cxstring::createDup(attr->getLanguage());
8166 if (definedIn)
8167 *definedIn = cxstring::createDup(attr->getDefinedIn());
8168 if (isGenerated)
8169 *isGenerated = attr->getGeneratedDeclaration();
8170 return 1;
8171 }
8172 return 0;
8173}
8174
Guy Benyei11169dd2012-12-18 14:30:41 +00008175CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8176 if (!clang_isDeclaration(C.kind))
8177 return clang_getNullRange();
8178
8179 const Decl *D = getCursorDecl(C);
8180 ASTContext &Context = getCursorContext(C);
8181 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8182 if (!RC)
8183 return clang_getNullRange();
8184
8185 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8186}
8187
8188CXString clang_Cursor_getRawCommentText(CXCursor C) {
8189 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008190 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008191
8192 const Decl *D = getCursorDecl(C);
8193 ASTContext &Context = getCursorContext(C);
8194 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8195 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8196 StringRef();
8197
8198 // Don't duplicate the string because RawText points directly into source
8199 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008200 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008201}
8202
8203CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8204 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008205 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008206
8207 const Decl *D = getCursorDecl(C);
8208 const ASTContext &Context = getCursorContext(C);
8209 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8210
8211 if (RC) {
8212 StringRef BriefText = RC->getBriefText(Context);
8213
8214 // Don't duplicate the string because RawComment ensures that this memory
8215 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008216 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008217 }
8218
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008219 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008220}
8221
Guy Benyei11169dd2012-12-18 14:30:41 +00008222CXModule clang_Cursor_getModule(CXCursor C) {
8223 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008224 if (const ImportDecl *ImportD =
8225 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008226 return ImportD->getImportedModule();
8227 }
8228
Craig Topper69186e72014-06-08 08:38:04 +00008229 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008230}
8231
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008232CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8233 if (isNotUsableTU(TU)) {
8234 LOG_BAD_TU(TU);
8235 return nullptr;
8236 }
8237 if (!File)
8238 return nullptr;
8239 FileEntry *FE = static_cast<FileEntry *>(File);
8240
8241 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8242 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8243 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8244
Richard Smithfeb54b62014-10-23 02:01:19 +00008245 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008246}
8247
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008248CXFile clang_Module_getASTFile(CXModule CXMod) {
8249 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008250 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008251 Module *Mod = static_cast<Module*>(CXMod);
8252 return const_cast<FileEntry *>(Mod->getASTFile());
8253}
8254
Guy Benyei11169dd2012-12-18 14:30:41 +00008255CXModule clang_Module_getParent(CXModule CXMod) {
8256 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008257 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008258 Module *Mod = static_cast<Module*>(CXMod);
8259 return Mod->Parent;
8260}
8261
8262CXString clang_Module_getName(CXModule CXMod) {
8263 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008264 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008265 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008266 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008267}
8268
8269CXString clang_Module_getFullName(CXModule CXMod) {
8270 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008271 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008272 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008273 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008274}
8275
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008276int clang_Module_isSystem(CXModule CXMod) {
8277 if (!CXMod)
8278 return 0;
8279 Module *Mod = static_cast<Module*>(CXMod);
8280 return Mod->IsSystem;
8281}
8282
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008283unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8284 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008285 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008286 LOG_BAD_TU(TU);
8287 return 0;
8288 }
8289 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008290 return 0;
8291 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008292 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8293 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8294 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008295}
8296
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008297CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8298 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008299 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008300 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008301 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008302 }
8303 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008304 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008305 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008306 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008307
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008308 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8309 if (Index < TopHeaders.size())
8310 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008311
Craig Topper69186e72014-06-08 08:38:04 +00008312 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008313}
8314
Guy Benyei11169dd2012-12-18 14:30:41 +00008315//===----------------------------------------------------------------------===//
8316// C++ AST instrospection.
8317//===----------------------------------------------------------------------===//
8318
Jonathan Coe29565352016-04-27 12:48:25 +00008319unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8320 if (!clang_isDeclaration(C.kind))
8321 return 0;
8322
8323 const Decl *D = cxcursor::getCursorDecl(C);
8324 const CXXConstructorDecl *Constructor =
8325 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8326 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8327}
8328
8329unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8330 if (!clang_isDeclaration(C.kind))
8331 return 0;
8332
8333 const Decl *D = cxcursor::getCursorDecl(C);
8334 const CXXConstructorDecl *Constructor =
8335 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8336 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8337}
8338
8339unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8340 if (!clang_isDeclaration(C.kind))
8341 return 0;
8342
8343 const Decl *D = cxcursor::getCursorDecl(C);
8344 const CXXConstructorDecl *Constructor =
8345 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8346 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8347}
8348
8349unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8350 if (!clang_isDeclaration(C.kind))
8351 return 0;
8352
8353 const Decl *D = cxcursor::getCursorDecl(C);
8354 const CXXConstructorDecl *Constructor =
8355 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8356 // Passing 'false' excludes constructors marked 'explicit'.
8357 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8358}
8359
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008360unsigned clang_CXXField_isMutable(CXCursor C) {
8361 if (!clang_isDeclaration(C.kind))
8362 return 0;
8363
8364 if (const auto D = cxcursor::getCursorDecl(C))
8365 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8366 return FD->isMutable() ? 1 : 0;
8367 return 0;
8368}
8369
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008370unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8371 if (!clang_isDeclaration(C.kind))
8372 return 0;
8373
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008374 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008375 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008376 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008377 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8378}
8379
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008380unsigned clang_CXXMethod_isConst(CXCursor C) {
8381 if (!clang_isDeclaration(C.kind))
8382 return 0;
8383
8384 const Decl *D = cxcursor::getCursorDecl(C);
8385 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008386 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008387 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008388}
8389
Jonathan Coe29565352016-04-27 12:48:25 +00008390unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8391 if (!clang_isDeclaration(C.kind))
8392 return 0;
8393
8394 const Decl *D = cxcursor::getCursorDecl(C);
8395 const CXXMethodDecl *Method =
8396 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8397 return (Method && Method->isDefaulted()) ? 1 : 0;
8398}
8399
Guy Benyei11169dd2012-12-18 14:30:41 +00008400unsigned clang_CXXMethod_isStatic(CXCursor C) {
8401 if (!clang_isDeclaration(C.kind))
8402 return 0;
8403
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008404 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008405 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008406 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008407 return (Method && Method->isStatic()) ? 1 : 0;
8408}
8409
8410unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8411 if (!clang_isDeclaration(C.kind))
8412 return 0;
8413
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008414 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008415 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008416 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008417 return (Method && Method->isVirtual()) ? 1 : 0;
8418}
Guy Benyei11169dd2012-12-18 14:30:41 +00008419
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008420unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8421 if (!clang_isDeclaration(C.kind))
8422 return 0;
8423
8424 const auto *D = cxcursor::getCursorDecl(C);
8425 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8426 if (RD)
8427 RD = RD->getDefinition();
8428 return (RD && RD->isAbstract()) ? 1 : 0;
8429}
8430
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008431unsigned clang_EnumDecl_isScoped(CXCursor C) {
8432 if (!clang_isDeclaration(C.kind))
8433 return 0;
8434
8435 const Decl *D = cxcursor::getCursorDecl(C);
8436 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8437 return (Enum && Enum->isScoped()) ? 1 : 0;
8438}
8439
Guy Benyei11169dd2012-12-18 14:30:41 +00008440//===----------------------------------------------------------------------===//
8441// Attribute introspection.
8442//===----------------------------------------------------------------------===//
8443
Guy Benyei11169dd2012-12-18 14:30:41 +00008444CXType clang_getIBOutletCollectionType(CXCursor C) {
8445 if (C.kind != CXCursor_IBOutletCollectionAttr)
8446 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8447
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008448 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008449 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8450
8451 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8452}
Guy Benyei11169dd2012-12-18 14:30:41 +00008453
8454//===----------------------------------------------------------------------===//
8455// Inspecting memory usage.
8456//===----------------------------------------------------------------------===//
8457
8458typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8459
8460static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8461 enum CXTUResourceUsageKind k,
8462 unsigned long amount) {
8463 CXTUResourceUsageEntry entry = { k, amount };
8464 entries.push_back(entry);
8465}
8466
Guy Benyei11169dd2012-12-18 14:30:41 +00008467const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8468 const char *str = "";
8469 switch (kind) {
8470 case CXTUResourceUsage_AST:
8471 str = "ASTContext: expressions, declarations, and types";
8472 break;
8473 case CXTUResourceUsage_Identifiers:
8474 str = "ASTContext: identifiers";
8475 break;
8476 case CXTUResourceUsage_Selectors:
8477 str = "ASTContext: selectors";
8478 break;
8479 case CXTUResourceUsage_GlobalCompletionResults:
8480 str = "Code completion: cached global results";
8481 break;
8482 case CXTUResourceUsage_SourceManagerContentCache:
8483 str = "SourceManager: content cache allocator";
8484 break;
8485 case CXTUResourceUsage_AST_SideTables:
8486 str = "ASTContext: side tables";
8487 break;
8488 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8489 str = "SourceManager: malloc'ed memory buffers";
8490 break;
8491 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8492 str = "SourceManager: mmap'ed memory buffers";
8493 break;
8494 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8495 str = "ExternalASTSource: malloc'ed memory buffers";
8496 break;
8497 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8498 str = "ExternalASTSource: mmap'ed memory buffers";
8499 break;
8500 case CXTUResourceUsage_Preprocessor:
8501 str = "Preprocessor: malloc'ed memory";
8502 break;
8503 case CXTUResourceUsage_PreprocessingRecord:
8504 str = "Preprocessor: PreprocessingRecord";
8505 break;
8506 case CXTUResourceUsage_SourceManager_DataStructures:
8507 str = "SourceManager: data structures and tables";
8508 break;
8509 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8510 str = "Preprocessor: header search tables";
8511 break;
8512 }
8513 return str;
8514}
8515
8516CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008517 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008518 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008519 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008520 return usage;
8521 }
8522
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008523 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008524 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008525 ASTContext &astContext = astUnit->getASTContext();
8526
8527 // How much memory is used by AST nodes and types?
8528 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8529 (unsigned long) astContext.getASTAllocatedMemory());
8530
8531 // How much memory is used by identifiers?
8532 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8533 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8534
8535 // How much memory is used for selectors?
8536 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8537 (unsigned long) astContext.Selectors.getTotalMemory());
8538
8539 // How much memory is used by ASTContext's side tables?
8540 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8541 (unsigned long) astContext.getSideTableAllocatedMemory());
8542
8543 // How much memory is used for caching global code completion results?
8544 unsigned long completionBytes = 0;
8545 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008546 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008547 completionBytes = completionAllocator->getTotalMemory();
8548 }
8549 createCXTUResourceUsageEntry(*entries,
8550 CXTUResourceUsage_GlobalCompletionResults,
8551 completionBytes);
8552
8553 // How much memory is being used by SourceManager's content cache?
8554 createCXTUResourceUsageEntry(*entries,
8555 CXTUResourceUsage_SourceManagerContentCache,
8556 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8557
8558 // How much memory is being used by the MemoryBuffer's in SourceManager?
8559 const SourceManager::MemoryBufferSizes &srcBufs =
8560 astUnit->getSourceManager().getMemoryBufferSizes();
8561
8562 createCXTUResourceUsageEntry(*entries,
8563 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8564 (unsigned long) srcBufs.malloc_bytes);
8565 createCXTUResourceUsageEntry(*entries,
8566 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8567 (unsigned long) srcBufs.mmap_bytes);
8568 createCXTUResourceUsageEntry(*entries,
8569 CXTUResourceUsage_SourceManager_DataStructures,
8570 (unsigned long) astContext.getSourceManager()
8571 .getDataStructureSizes());
8572
8573 // How much memory is being used by the ExternalASTSource?
8574 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8575 const ExternalASTSource::MemoryBufferSizes &sizes =
8576 esrc->getMemoryBufferSizes();
8577
8578 createCXTUResourceUsageEntry(*entries,
8579 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8580 (unsigned long) sizes.malloc_bytes);
8581 createCXTUResourceUsageEntry(*entries,
8582 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8583 (unsigned long) sizes.mmap_bytes);
8584 }
8585
8586 // How much memory is being used by the Preprocessor?
8587 Preprocessor &pp = astUnit->getPreprocessor();
8588 createCXTUResourceUsageEntry(*entries,
8589 CXTUResourceUsage_Preprocessor,
8590 pp.getTotalMemory());
8591
8592 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8593 createCXTUResourceUsageEntry(*entries,
8594 CXTUResourceUsage_PreprocessingRecord,
8595 pRec->getTotalMemory());
8596 }
8597
8598 createCXTUResourceUsageEntry(*entries,
8599 CXTUResourceUsage_Preprocessor_HeaderSearch,
8600 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008601
Guy Benyei11169dd2012-12-18 14:30:41 +00008602 CXTUResourceUsage usage = { (void*) entries.get(),
8603 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008604 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008605 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008606 return usage;
8607}
8608
8609void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8610 if (usage.data)
8611 delete (MemUsageEntries*) usage.data;
8612}
8613
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008614CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8615 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008616 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008617 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008618
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008619 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008620 LOG_BAD_TU(TU);
8621 return skipped;
8622 }
8623
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008624 if (!file)
8625 return skipped;
8626
8627 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8628 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8629 if (!ppRec)
8630 return skipped;
8631
8632 ASTContext &Ctx = astUnit->getASTContext();
8633 SourceManager &sm = Ctx.getSourceManager();
8634 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8635 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008636 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008637
8638 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8639 std::vector<SourceRange> wantedRanges;
8640 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8641 i != ei; ++i) {
8642 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8643 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008644 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8645 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008646 }
8647
8648 skipped->count = wantedRanges.size();
8649 skipped->ranges = new CXSourceRange[skipped->count];
8650 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8651 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8652
8653 return skipped;
8654}
8655
Cameron Desrochersd8091282016-08-18 15:43:55 +00008656CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8657 CXSourceRangeList *skipped = new CXSourceRangeList;
8658 skipped->count = 0;
8659 skipped->ranges = nullptr;
8660
8661 if (isNotUsableTU(TU)) {
8662 LOG_BAD_TU(TU);
8663 return skipped;
8664 }
8665
8666 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8667 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8668 if (!ppRec)
8669 return skipped;
8670
8671 ASTContext &Ctx = astUnit->getASTContext();
8672
8673 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8674
8675 skipped->count = SkippedRanges.size();
8676 skipped->ranges = new CXSourceRange[skipped->count];
8677 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8678 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8679
8680 return skipped;
8681}
8682
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008683void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8684 if (ranges) {
8685 delete[] ranges->ranges;
8686 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008687 }
8688}
8689
Guy Benyei11169dd2012-12-18 14:30:41 +00008690void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8691 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8692 for (unsigned I = 0; I != Usage.numEntries; ++I)
8693 fprintf(stderr, " %s: %lu\n",
8694 clang_getTUResourceUsageName(Usage.entries[I].kind),
8695 Usage.entries[I].amount);
8696
8697 clang_disposeCXTUResourceUsage(Usage);
8698}
8699
8700//===----------------------------------------------------------------------===//
8701// Misc. utility functions.
8702//===----------------------------------------------------------------------===//
8703
Richard Smith0a7b2972018-07-03 21:34:13 +00008704/// Default to using our desired 8 MB stack size on "safety" threads.
8705static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008706
8707namespace clang {
8708
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008709bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008710 unsigned Size) {
8711 if (!Size)
8712 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008713 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008714 return CRC.RunSafelyOnThread(Fn, Size);
8715 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008716}
8717
8718unsigned GetSafetyThreadStackSize() {
8719 return SafetyStackThreadSize;
8720}
8721
8722void SetSafetyThreadStackSize(unsigned Value) {
8723 SafetyStackThreadSize = Value;
8724}
8725
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008726}
Guy Benyei11169dd2012-12-18 14:30:41 +00008727
8728void clang::setThreadBackgroundPriority() {
8729 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8730 return;
8731
Nico Weber18cfd9f2019-04-21 19:18:41 +00008732#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008733 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008734#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008735}
8736
8737void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8738 if (!Unit)
8739 return;
8740
8741 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8742 DEnd = Unit->stored_diag_end();
8743 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008744 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008745 CXString Msg = clang_formatDiagnostic(&Diag,
8746 clang_defaultDiagnosticDisplayOptions());
8747 fprintf(stderr, "%s\n", clang_getCString(Msg));
8748 clang_disposeString(Msg);
8749 }
Nico Weber1865df42018-04-27 19:11:14 +00008750#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008751 // On Windows, force a flush, since there may be multiple copies of
8752 // stderr and stdout in the file system, all with different buffers
8753 // but writing to the same device.
8754 fflush(stderr);
8755#endif
8756}
8757
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008758MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8759 SourceLocation MacroDefLoc,
8760 CXTranslationUnit TU){
8761 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008762 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008763 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008764 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008765
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008766 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008767 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008768 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008769 if (MD) {
8770 for (MacroDirective::DefInfo
8771 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8772 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8773 return Def.getMacroInfo();
8774 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008775 }
8776
Craig Topper69186e72014-06-08 08:38:04 +00008777 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008778}
8779
Richard Smith66a81862015-05-04 02:25:31 +00008780const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008781 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008782 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008783 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008784 const IdentifierInfo *II = MacroDef->getName();
8785 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008786 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008787
8788 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8789}
8790
Richard Smith66a81862015-05-04 02:25:31 +00008791MacroDefinitionRecord *
8792cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8793 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008794 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008795 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008796 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008797 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008798
8799 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008800 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008801 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8802 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008803 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008804
8805 // Check that the token is inside the definition and not its argument list.
8806 SourceManager &SM = Unit->getSourceManager();
8807 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008808 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008809 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008810 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008811
8812 Preprocessor &PP = Unit->getPreprocessor();
8813 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8814 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008815 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008816
Alp Toker2d57cea2014-05-17 04:53:25 +00008817 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008818 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008819 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008820
8821 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008822 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008823 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008824
Richard Smith20e883e2015-04-29 23:20:19 +00008825 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008826 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008827 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008828
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008829 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008830}
8831
Richard Smith66a81862015-05-04 02:25:31 +00008832MacroDefinitionRecord *
8833cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8834 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008835 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008836 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008837
8838 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008839 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008840 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008841 Preprocessor &PP = Unit->getPreprocessor();
8842 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008843 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008844 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8845 Token Tok;
8846 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008847 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008848
8849 return checkForMacroInMacroDefinition(MI, Tok, TU);
8850}
8851
Guy Benyei11169dd2012-12-18 14:30:41 +00008852CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008853 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008854}
8855
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008856Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8857 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008858 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008859 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008860 if (Unit->isMainFileAST())
8861 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008862 return *this;
8863 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008864 } else {
8865 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008866 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008867 return *this;
8868}
8869
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008870Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8871 *this << FE->getName();
8872 return *this;
8873}
8874
8875Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8876 CXString cursorName = clang_getCursorDisplayName(cursor);
8877 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8878 clang_disposeString(cursorName);
8879 return *this;
8880}
8881
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008882Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8883 CXFile File;
8884 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008885 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008886 CXString FileName = clang_getFileName(File);
8887 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8888 clang_disposeString(FileName);
8889 return *this;
8890}
8891
8892Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8893 CXSourceLocation BLoc = clang_getRangeStart(range);
8894 CXSourceLocation ELoc = clang_getRangeEnd(range);
8895
8896 CXFile BFile;
8897 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008898 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008899
8900 CXFile EFile;
8901 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008902 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008903
8904 CXString BFileName = clang_getFileName(BFile);
8905 if (BFile == EFile) {
8906 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8907 BLine, BColumn, ELine, EColumn);
8908 } else {
8909 CXString EFileName = clang_getFileName(EFile);
8910 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8911 BLine, BColumn)
8912 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8913 ELine, EColumn);
8914 clang_disposeString(EFileName);
8915 }
8916 clang_disposeString(BFileName);
8917 return *this;
8918}
8919
8920Logger &cxindex::Logger::operator<<(CXString Str) {
8921 *this << clang_getCString(Str);
8922 return *this;
8923}
8924
8925Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8926 LogOS << Fmt;
8927 return *this;
8928}
8929
Chandler Carruth37ad2582014-06-27 15:14:39 +00008930static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8931
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008932cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008933 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008934
8935 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8936
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008937 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008938 OS << "[libclang:" << Name << ':';
8939
Alp Toker1a86ad22014-07-06 06:24:00 +00008940#ifdef USE_DARWIN_THREADS
8941 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008942 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8943 OS << tid << ':';
8944#endif
8945
8946 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8947 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008948 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008949
8950 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008951 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008952 OS << "--------------------------------------------------\n";
8953 }
8954}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00008955
8956#ifdef CLANG_TOOL_EXTRA_BUILD
8957// This anchor is used to force the linker to link the clang-tidy plugin.
8958extern volatile int ClangTidyPluginAnchorSource;
8959static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8960 ClangTidyPluginAnchorSource;
8961
8962// This anchor is used to force the linker to link the clang-include-fixer
8963// plugin.
8964extern volatile int ClangIncludeFixerPluginAnchorSource;
8965static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8966 ClangIncludeFixerPluginAnchorSource;
8967#endif